This commit is contained in:
Dan Chao
2016-03-09 13:05:38 -08:00
1189 changed files with 312457 additions and 215118 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
# Auto detect text files and perform LF normalization
* text=none
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
+37 -37
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
+1
View File
@@ -1596,4 +1596,5 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](scroller/scroller.d.ts) [Zynga Scroller](https://github.com/zynga/scroller) by [Boris Yankov](https://github.com/borisyankov)
* [:link:](zynga-scroller/zynga-scroller.d.ts) [Zynga Scroller](http://zynga.github.com/scroller) by [Marcelo Haskell Camargo](https://github.com/haskellcamargo)
* [:link:](viewporter/viewporter.d.ts) [Zynga Viewporter](https://github.com/zynga/viewporter) by [Boris Yankov](https://github.com/borisyankov)
* [:link:](flickity/flickity.d.ts) [Flickity](https://github.com/metafizzy/flickity) by [Chris McGrath](https://github.com/clmcgrath)
+368 -368
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");
}
+47 -47
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;
}
+61
View File
@@ -0,0 +1,61 @@
/// <reference path="HubSpot-pace.d.ts" />
pace.start({
document: false
});
pace.start();
pace.restart();
pace.stop();
var paceOptions: HubSpotPaceInterfaces.PaceOptions;
paceOptions = {
// Disable the 'elements' source
elements: false,
// Only show the progress on regular and ajax-y page navigation,
// not every request
restartOnRequestAfter: false
}
paceOptions = {
ajax: false, // disabled
document: false, // disabled
eventLag: false, // disabled
elements: {
selectors: ['.my-page']
}
};
paceOptions = {
elements: {
selectors: ['.timeline,.timeline-error', '.user-profile,.profile-error']
}
}
paceOptions = {
restartOnPushState: false
}
paceOptions = {
restartOnRequestAfter: false
}
pace.options = {
restartOnRequestAfter: false
}
pace.ignore(function(){
});
pace.track(function(){
});
pace.options = {
ajax: {
ignoreURLs: ['some-substring', /some-regexp/]
}
};
+115
View File
@@ -0,0 +1,115 @@
// Type definitions for pace v0.7.5
// Project: https://github.com/HubSpot/pace
// Definitions by: Borislav Zhivkov <https://github.com/borislavjivkov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module HubSpotPaceInterfaces {
interface PaceOptions {
/**
* How long should it take for the bar to animate to a new point after receiving it
*/
catchupTime?: number;
/**
* How quickly should the bar be moving before it has any progress info from a new source in %/ms
*/
initialRate?: number;
/**
* What is the minimum amount of time the bar should be on the screen. Irrespective of this number, the bar will always be on screen for 33 * (100 / maxProgressPerFrame) + ghostTime ms.
*/
minTime?: number;
/**
* What is the minimum amount of time the bar should sit after the last update before disappearing
*/
ghostTime?: number;
/**
* Its easy for a bunch of the bar to be eaten in the first few frames before we know how much there is to load. This limits how much of the bar can be used per frame
*/
maxProgressPerFrame?: number;
/**
* This tweaks the animation easing
*/
easeFactor?: number;
/**
* Should pace automatically start when the page is loaded, or should it wait for `start` to be called? Always false if pace is loaded with AMD or CommonJS.
*/
startOnPageLoad?: boolean;
/**
* Should we restart the browser when pushState or replaceState is called? (Generally means ajax navigation has occured)
*/
restartOnPushState?: boolean;
/**
* Should we show the progress bar for every ajax request (not just regular or ajax-y page navigation)? Set to false to disable. If so, how many ms does the request have to be running for before we show the progress?
*/
restartOnRequestAfter?: boolean | number;
/**
* What element should the pace element be appended to on the page?
*/
target?: string;
document?: boolean | string;
elements?: boolean | PaceElementsOptions;
eventLag?: boolean | PaceEventLagOptions;
ajax?: boolean | PaceAjaxOptions;
}
interface PaceElementsOptions {
/**
* How frequently in ms should we check for the elements being tested for using the element monitor?
*/
checkInterval?: number;
/**
* What elements should we wait for before deciding the page is fully loaded (not required)
*/
selectors?: string[];
}
interface PaceEventLagOptions {
/**
* When we first start measuring event lag, not much is going on in the browser yet, so it's not uncommon for the numbers to be abnormally low for the first few samples. This configures how many samples we need before we consider a low number to mean completion.
*/
minSamples?: number;
/**
* How many samples should we average to decide what the current lag is?
*/
sampleCount?: number;
/**
* Above how many ms of lag is the CPU considered busy?
*/
lagThreshold?: number;
}
interface PaceAjaxOptions {
/**
* Which HTTP methods should we track?
*/
trackMethods?: string[];
/**
* Should we track web socket connections?
*/
trackWebSockets?: boolean;
/**
* A list of regular expressions or substrings of URLS we should ignore (for both tracking and restarting)
*/
ignoreURLs?: (string | RegExp)[];
}
interface Pace {
options: PaceOptions;
start(options?: PaceOptions): void;
restart(): void;
stop(): void;
track(fn: () => void, ...args: any[]): void;
ignore(fn: () => void, ...args: any[]): void;
on(event: string, handler: (...args: any[]) => void, context?: any): void;
off(event: string, handler?: (...args: any[]) => void): void;
once(event: string, handler: (...args: any[]) => void, context?: any): void;
}
enum PaceEvent { start, stop, restart, done, hide }
}
declare var pace: HubSpotPaceInterfaces.Pace;
declare module "HubSpot-pace" {
export = pace;
}
+5
View File
@@ -0,0 +1,5 @@
- [ ] I tried using the latest `xxxx/xxxx.d.ts` file in this repo and had problems.
- [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
- [ ] I have a question that is inappropriate for [StackOverflow](https://stackoverflow.com/). (Please ask any appropriate questions there).
- [ ] I want to talk about `xxxx/xxxx.d.ts`.
- The authors of that type definition are cc/ @....
+8
View File
@@ -0,0 +1,8 @@
case 1. Add a new type definition.
- [ ] checked compilation succeeds with `--target es6` and `--noImplicitAny` options.
- [ ] has correct [naming convention](http://definitelytyped.org/guides/contributing.html#naming-the-file)
- [ ] has a [test file](http://definitelytyped.org/guides/contributing.html#tests) with the suffix of `-tests.ts` or `-tests.tsx`.
case 2. Improvement to existing type definition.
- documentation or source code reference which provides context for the suggested changes. url http://api.jquery.com/html .
- it has been reviewed by a DefinitelyTyped member.
+1 -1
View File
@@ -22,7 +22,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi
## How to get the definitions
* Directly from the Github repos
* Directly from the GitHub repos
* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped)
* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd)
+107 -107
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]
};
+15 -15
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;
}
}
+1 -1
View File
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
@@ -1 +1 @@
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
@@ -1 +1 @@
@@ -1 +1 @@
+1 -1
View File
@@ -7,7 +7,7 @@
/// <reference path='../node/node.d.ts'/>
/// <reference path='../redis/redis.d.ts'/>
/// <reference path="../mongodb/mongodb.d.ts" />
/// <reference path="../mongodb/mongodb-1.4.9.d.ts" />
declare module "acl" {
import http = require('http');
+3 -2
View File
@@ -17,7 +17,8 @@ console.log(zip.readAsText("some_folder/my_file.txt"));
zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*overwrite*/true)
// extracts everything
zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true);
// extracts everything and calls callback -> async extracction
zip.extractAllToAsync(/*target path*/"/home/me/zipcontent/", /*overwrite*/true, (error: Error)=> {});
// creating archives
var zip = new AdmZip();
@@ -58,4 +59,4 @@ zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", false, true);
function isAdmZipEntry(obj: any): obj is AdmZip.IZipEntry {
return obj !== null && typeof obj === "object" && typeof obj['entryName'] === 'string';
}
}
+9 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for adm-zip v0.4.4
// Project: https://github.com/cthackers/adm-zip
// Definitions by: John Vilk <https://github.com/jvilk>
// Definitions by: John Vilk <https://github.com/jvilk>, Abner Oliveira <https://github.com/abner>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
@@ -211,6 +211,14 @@ declare module "adm-zip" {
* will be overwriten if this is true. Default is FALSE
*/
extractAllTo(targetPath: string, overwrite?: boolean): void;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* @param callback The callback function will be called afeter extraction
*/
extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no ``targetFileName`` is provided, it will
-1
View File
@@ -1464,7 +1464,6 @@ declare module ag.grid {
addDropTarget(eDropTarget: any, dropTargetCallback: any): void;
}
}
declare function require(name: string): any;
declare module ag.grid {
class AgList {
private eGui;
+106
View File
@@ -0,0 +1,106 @@
///<reference path="agenda.d.ts"/>
import * as Agenda from "agenda";
var mongoConnectionString = "mongodb://127.0.0.1/agenda";
var agenda = new Agenda({ db: { address: mongoConnectionString } });
agenda.define('delete old users', (job, done) => {
});
agenda.on('ready', () => {
agenda.every('3 minutes', 'delete old users');
// Alternatively, you could also do:
agenda.every('*/3 * * * *', 'delete old users');
agenda.start();
});
agenda.define('send email report', { priority: 'high', concurrency: 10 }, (job, done) => {
});
agenda.on('ready', () => {
agenda.schedule('in 20 minutes', 'send email report', { to: 'admin@example.com' });
agenda.start();
});
agenda.on('ready', () => {
var weeklyReport = agenda.create('send email report', { to: 'another-guy@example.com' });
weeklyReport.repeatEvery('1 week').save();
agenda.start();
});
var agenda = new Agenda({ processEvery: '30 seconds' });
agenda.defaultConcurrency(5);
var agenda = new Agenda({ defaultConcurrency: 5 });
agenda.lockLimit(0);
var agenda = new Agenda({ lockLimit: 0 });
agenda.defaultLockLimit(0);
var agenda = new Agenda({ defaultLockLimit: 0 });
agenda.defaultLockLifetime(10000);
var agenda = new Agenda({ defaultLockLifetime: 10000 });
agenda.define('some long running job', function(job, done) {
done();
});
agenda.every('15 minutes', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);
agenda.schedule('tomorrow at noon', 'printAnalyticsReport', { userCount: 100 });
agenda.schedule('tomorrow at noon', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);
agenda.now('do the hokey pokey');
var job = agenda.create('printAnalyticsReport', { userCount: 100 });
job.save(function(err) {
console.log("Job successfully saved");
});
agenda.jobs({ name: 'printAnalyticsReport' }, function(err, jobs) {
// Work with jobs (see below)
});
agenda.cancel({ name: 'printAnalyticsReport' }, function(err, numRemoved) {
});
agenda.purge(function(err, numRemoved) {
});
agenda.stop(function() {
process.exit(0);
});
job.repeatEvery('10 minutes');
job.repeatAt('3:30pm');
job.schedule('tomorrow at 6pm');
job.priority('low');
job.priority(10);
job.unique({ 'data.type': 'active', 'data.userId': '123' });
job.fail('insuficient disk space');
job.fail(new Error('insufficient disk space'));
job.run(function(err, job) {
console.log("I don't know why you would need to do this...");
});
job.remove(function(err) {
if (!err) console.log("Successfully removed job from collection");
})
+443
View File
@@ -0,0 +1,443 @@
// Type definitions for Agenda v0.8.9
// Project: https://github.com/rschmukler/agenda
// Definitions by: Meir Gottlieb <https://github.com/meirgottlieb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path='../node/node.d.ts' />
/// <reference path='../mongodb/mongodb.d.ts' />
declare module "agenda" {
import {EventEmitter} from "events";
import {Db, Collection, ObjectID} from "mongodb";
interface Callback {
(err?: Error): void;
}
interface ResultCallback<T> {
(err?: Error, result?: T): void;
}
/**
* Agenda Configuration.
*/
interface AgendaConfiguration {
/**
* Sets the interval with which the queue is checked. A number in milliseconds or a frequency string.
*/
processEvery?: string | number;
/**
* Takes a number which specifies the default number of a specific job that can be running at any given moment.
* By default it is 5.
*/
defaultConcurrency?: number;
/**
* Takes a number which specifies the max number of jobs that can be running at any given moment. By default it
* is 20.
*/
maxConcurrency?: number;
/**
* Takes a number which specifies the default number of a specific job that can be locked at any given moment.
* By default it is 0 for no max.
*/
defaultLockLimit?: number;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
*/
lockLimit?: number;
/**
* Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This
* can be overridden by specifying the lockLifetime option to a defined job.
*/
defaultLockLifetime?: number;
/**
* Specifies that Agenda should be initialized using and existing MongoDB connection.
*/
mongo?: {
/**
* The MongoDB database connection to use.
*/
db: Db;
/**
* The name of the collection to use.
*/
collection?: string;
}
/**
* Specifies that Agenda should connect to MongoDB.
*/
db?: {
/**
* The connection URL.
*/
address: string;
/**
* The name of the collection to use.
*/
collection?: string;
/**
* Connection options to pass to MongoDB.
*/
options?: any;
}
}
/**
* The database record associated with a job.
*/
interface JobAttributes {
/**
* The record identity.
*/
_id: ObjectID;
/**
* The name of the job.
*/
name: string;
/**
* The type of the job (single|normal).
*/
type: string;
/**
* The job details.
*/
data: { [name: string]: any };
/**
* The priority of the job.
*/
priority: number;
/**
* How often the job is repeated using a human-readable or cron format.
*/
repeatInterval: string | number;
/**
* The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/).
*/
repeatTimezone: string;
/**
* Date/time the job was las modified.
*/
lastModifiedBy: string;
/**
* Date/time the job will run next.
*/
nextRunAt: Date;
/**
* Date/time the job was locked.
*/
lockedAt: Date;
/**
* Date/time the job was last run.
*/
lastRunAt: Date;
/**
* Date/time the job last finished running.
*/
lastFinishedAt: Date;
/**
* The reason the job failed.
*/
failReason: string;
/**
* The number of times the job has failed.
*/
failCount: number;
/**
* The date/time the job last failed.
*/
failedAt: Date;
}
/**
* A scheduled job.
*/
interface Job {
/**
* The database record associated with the job.
*/
attrs: JobAttributes;
/**
* Specifies an interval on which the job should repeat.
* @param interval A human-readable format String, a cron format String, or a Number.
* @param options An optional argument that can include a timezone field. The timezone should be a string as
* accepted by moment-timezone and is considered when using an interval in the cron string format.
*/
repeatEvery(interval: string | number, options?: { timezone?: string }): Job
/**
* Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples).
* @param time
*/
repeatAt(time: string): Job
/**
* Disables the job.
*/
disable(): Job;
/**
* Enables the job.
*/
enable(): Job;
/**
* Ensure that only one instance of this job exists with the specified properties
* @param value The properties associated with the job that must be unqiue.
* @param opts
*/
unique(value: any, opts?: { insertOnly?: boolean }): Job;
/**
* Specifies the next time at which the job should run.
* @param time The next time at which the job should run.
*/
schedule(time: string | Date): Job;
/**
* Specifies the priority weighting of the job.
* @param value The priority of the job (lowest|low|normal|high|highest|number).
*/
priority(value: string | number): Job;
/**
* Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.
* @param reason A message or Error object that indicates why the job failed.
*/
fail(reason: string | Error): Job;
/**
* Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually
* @param cb Called when the job is completed.
*/
run(cb?: ResultCallback<Job>): Job;
/**
* Returns true if the job is running; otherwise, returns false.
*/
isRunning(): boolean;
/**
* Saves the job into the database.
* @param cb Called when the job is saved.
*/
save(cb?: ResultCallback<Job>): Job;
/**
* Removes the job from the database and cancels the job.
* @param cb Called after the job has beeb removed from the database.
*/
remove(cb?: Callback): void;
/**
* Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running
* jobs.
* @param cb Called after the job has been saved to the database.
*/
touch(cb?: Callback): void;
}
interface JobOptions {
/**
* Maximum number of that job that can be running at once (per instance of agenda)
*/
concurrency?: number;
/**
* Maximum number of that job that can be locked at once (per instance of agenda)
*/
lockLimit?: number;
/**
* Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will
* automatically unlock if done() is called.
*/
lockLifetime?: number;
/**
* (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run
* first.
*/
priority?: string | number;
}
class Agenda extends EventEmitter {
/**
* Constructs a new Agenda object.
* @param config Optional configuration to initialize the Agenda.
* @param cb Optional callback called with the MongoDB colleciton.
*/
constructor(config?: AgendaConfiguration, cb?: ResultCallback<Collection>);
/**
* Connect to the specified MongoDB server and database.
*/
database(url: string, collection?: string, options?: any, cb?: ResultCallback<Collection>): Agenda;
/**
* Initialize agenda with an existing MongoDB connection.
*/
mongo(db: Db, collection?: string, cb?: ResultCallback<Collection>): Agenda;
/**
* Sets the agenda name.
*/
name(value: string): Agenda;
/**
* Sets the interval with which the queue is checked. A number in milliseconds or a frequency string.
*/
processEvery(interval: string | number): Agenda;
/**
* Takes a number which specifies the max number of jobs that can be running at any given moment. By default it
* is 20.
* @param value The value to set.
*/
maxConcurrency(value: number): Agenda;
/**
* Takes a number which specifies the default number of a specific job that can be running at any given moment.
* By default it is 5.
* @param value The value to set.
*/
defaultConcurrency(value: number): Agenda;
/**
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
* 0 for no max.
* @param value The value to set.
*/
lockLimit(value: number): Agenda;
/**
* Takes a number which specifies the default number of a specific job that can be locked at any given moment.
* By default it is 0 for no max.
* @param value The value to set.
*/
defaultLockLimit(value: number): Agenda;
/**
* Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This
* can be overridden by specifying the lockLifetime option to a defined job.
* @param value The value to set.
*/
defaultLockLifetime(value: number): Agenda;
/**
* Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn
* how to manually work with jobs.
* @param name The name of the job.
* @param data Data to associated with the job.
*/
create(name: string, data?: any): Job;
/**
* Find all Jobs matching `query` and pass same back in cb().
* @param query
* @param cb
*/
jobs(query: any, cb: ResultCallback<Job[]>): void;
/**
* Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want
* to remove old jobs.
* @param cb Called with the number of jobs removed.
*/
purge(cb?: ResultCallback<number>): void;
/**
* Defines a job with the name of jobName. When a job of job name gets run, it will be passed to fn(job, done).
* To maintain asynchronous behavior, you must call done() when you are processing the job. If your function is
* synchronous, you may omit done from the signature.
* @param name The name of the jobs.
* @param options The options for the job.
* @param handler The handler to execute.
*/
define(name: string, handler: (job?: Job, done?: (err?: Error) => void) => void): void;
define(name: string, options: JobOptions, handler: (job?: Job, done?: (err?: Error) => void) => void): void;
/**
* Runs job name at the given interval. Optionally, data and options can be passed in.
* @param interval Can be a human-readable format String, a cron format String, or a Number.
* @param names The name or names of the job(s) to run.
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param options An optional argument that will be passed to job.repeatEvery.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback<Job>): Job;
every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback<Job[]>): Job[];
/**
* Schedules a job to run name once at a given time.
* @param when A Date or a String such as tomorrow at 5pm.
* @param names The name or names of the job(s) to run.
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback<Job>): Job;
schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback<Job[]>): Job[];
/**
* Schedules a job to run name once immediately.
* @param name The name of the job to run.
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
* @param cb An optional callback function which will be called when the job has been persisted in the database.
*/
now(name: string, data?: any, cb?: ResultCallback<Job>): Job;
/**
* Cancels any jobs matching the passed mongodb-native query, and removes them from the database.
* @param query Mongodb native query.
* @param cb Called with the number of jobs removed.
*/
cancel(query: any, cb?: ResultCallback<number>): void;
/**
* Starts the job queue processing, checking processEvery time to see if there are new jobs.
*/
start(): void;
/**
* Stops the job queue processing. Unlocks currently running jobs.
* @param cb Called after the job processing queue shuts down and unlocks all jobs.
*/
stop(cb: Callback): void;
}
module Agenda {
}
export = Agenda;
}
+2 -4
View File
@@ -2,10 +2,8 @@
* Created by shearerbeard on 6/28/15.
*/
///<reference path="alt.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
import Alt = require("alt");
import Promise = require("es6-promise");
//New alt instance
var alt = new Alt();
@@ -43,8 +41,8 @@ class AbstractStoreModel<S> implements AltJS.StoreModel<S> {
class GenerateActionsClass extends AbstractActions {
constructor(config:AltJS.Alt) {
this.generateActions("notifyTest");
super(config);
this.generateActions("notifyTest");
}
}
@@ -74,7 +72,7 @@ var testSource:AltJS.Source = {
fakeLoad():AltJS.SourceModel<string> {
return {
remote() {
return new Promise.Promise<string>((res:any, rej:any) => {
return new Promise<string>((res:any, rej:any) => {
setTimeout(() => {
if(true) {
res("stuff");
-1
View File
@@ -4,7 +4,6 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../react/react.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
declare module AltJS {
-2
View File
@@ -3,8 +3,6 @@
// Definitions by: Matti Lehtinen <https://github.com/MattiLehtinen/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../es6-promise/es6-promise.d.ts"/>
declare module "amazon-product-api" {
interface ICredentials {
+1 -1
View File
@@ -1 +1 @@
+1 -1
View File
@@ -1 +1 @@
+1
View File
@@ -38,6 +38,7 @@ declare module "amqplib/properties" {
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
deadLetterRoutingKey?: string;
maxLength?: number;
}
interface DeleteQueue {
+21
View File
@@ -0,0 +1,21 @@
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='angular-cookie.d.ts' />
angular.module('myApp', ['ipCookie'])
.controller('cookieController', ['ipCookie', function(ipCookie: angular.cookie.CookieService) {
ipCookie('key', 'value');
ipCookie('key', { value: 'value'});
ipCookie('key', [1, 2, 3]);
ipCookie('key', 'value', { expires: 21 });
ipCookie('key', 'value', { encode: function (value) { return value; } });
ipCookie();
ipCookie('key');
ipCookie('key', undefined, {decode: function (value) { return value; }});
ipCookie.remove('key');
ipCookie.remove('key', { path: '/some/path/' });
var obj: Object = '255';
}]);
+65
View File
@@ -0,0 +1,65 @@
// Type definitions for angular-cookie v4.1.0
// Project: https://github.com/ivpusic/angular-cookie
// Definitions by: Borislav Zhivkov <https://github.com/borislavjivkov>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.cookie {
interface CookieService {
/**
* Get all cookies
*/
(): any;
/**
* Get a cookie with a specific key
*/
(key: string): any;
/**
* Create a cookie
*/
(key: string, value: any, options?: CookieOptions): any;
/**
* Remove a cookie
*/
remove(key: string, options?: CookieOptions): void;
}
interface CookieOptions {
/**
* The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie.
*/
domain?: string;
/**
* The path gives you the chance to specify a directory where the cookie is active.
*/
path?: string;
/**
* Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date the cookie is trashed when you close the browser.
*/
expires?: number;
/**
* Allows you to set the expiration time in hours, minutes, seconds, or `milliseconds. If this is not specified, any expiration time specified will default to days.
*/
expirationUnit?: string;
/**
* The Secure attribute is meant to keep cookie communication limited to encrypted transmission, directing browsers to use cookies only via secure/encrypted connections.
*/
secure?: boolean;
/**
* The method that will be used to encode the cookie value (should be passed when using Set).
*/
encode?: (value: any) => any;
/**
* The method that will be used to decode extracted cookie values (should be passed when using Get).
*/
decode?: (value: any) => any;
}
}
@@ -0,0 +1,30 @@
/// <reference path="angular-environment.d.ts" />
var envServiceProvider: angular.environment.ServiceProvider;
var envService: angular.environment.Service;
envServiceProvider.config({
domains: {
development: ['localhost', 'dev.local'],
production: ['acme.com', 'acme.net', 'acme.org']
},
vars: {
development: {
apiUrl: '//localhost/api',
staticUrl: '//localhost/static'
},
production: {
apiUrl: '//api.acme.com/v2',
staticUrl: '//static.acme.com'
}
}
});
envServiceProvider.check();
envService.get();
envService.set('production');
var isProd: boolean = envService.is('production');
var val: any = envService.read('apiUrl');
+52
View File
@@ -0,0 +1,52 @@
// Type definitions for angular-environment v1.0.4
// Project: https://github.com/juanpablob/angular-environment
// Definitions by: Matt Wheatley <https://github.com/terrawheat>
// Definitions: https://github.com/LiberisLabs
declare module angular.environment {
interface ServiceProvider {
/**
* Sets the configuration object
*/
config: (config: angular.environment.Config) => void;
/**
* Evaluates the current domain and
* loads the correct environment variables.
*/
check: () => void;
}
interface Service {
/**
* Retrieve the current environment
*/
get: () => string,
/**
* Force sets the current environment
*/
set: (environment: string) => void,
/**
* Evaluates current environment against
* environment parameter.
*/
is: (environment: string) => boolean,
/**
* Retrieves the correct version of a
* variable for the current environment.
*/
read: (key: string) => any;
}
interface Config {
/**
* Map of domains to their environments
*/
domains: { [environment: string]: Array<string> },
/**
* List of variables split by environment
*/
vars: { [environment: string]: { [variable: string]: any }},
}
}
+22 -12
View File
@@ -21,7 +21,9 @@ declare module AngularFormly {
}
interface IFieldGroup {
data?: Object;
data?: {
[key: string]: any;
};
className?: string;
elementAttributes?: string;
fieldGroup?: IFieldArray;
@@ -37,7 +39,9 @@ declare module AngularFormly {
interface IFormOptionsAPI {
data?: Object;
data?: {
[key: string]: any;
};
fieldTransform?: Function;
formState?: Object;
removeChromeAutoComplete?: boolean;
@@ -101,13 +105,13 @@ declare module AngularFormly {
type?: string;
//expression types
onBlur?: string;
onChange?: string;
onClick?: string;
onFocus?: string;
onKeydown?: string;
onKeypress?: string;
onKeyup?: string;
onBlur?: string | IExpressionFunction;
onChange?: string | IExpressionFunction;
onClick?: string | IExpressionFunction;
onFocus?: string | IExpressionFunction;
onKeydown?: string | IExpressionFunction;
onKeypress?: string | IExpressionFunction;
onKeyup?: string | IExpressionFunction;
//Bootstrap types
label?: string;
@@ -177,7 +181,9 @@ declare module AngularFormly {
*
* see http://docs.angular-formly.com/docs/field-configuration-object#data-object
*/
data?: Object;
data?: {
[key: string]: any;
};
/**
@@ -198,7 +204,9 @@ declare module AngularFormly {
className?: string;
elementAttributes?: string;
elementAttributes?: {
[key: string]: string;
};
/**
@@ -534,7 +542,9 @@ declare module AngularFormly {
apiCheckOptions?: Object;
defaultOptions?: IFieldConfigurationObject | Function;
controller?: Function | string | any[];
data?: Object;
data?: {
[key: string]: any;
};
extends?: string;
link?: ng.IDirectiveLinkFn;
overwriteOk?: boolean;
@@ -0,0 +1,12 @@
/// <reference path="angular-fullscreen.d.ts" />
angular
.module('TestApp', ['FBAngular'])
.controller('TestCtrl', (Fullscreen: ng.fullscreen.IFullscreen) => {
Fullscreen.all();
Fullscreen.toggleAll();
Fullscreen.enable(document.getElementById('test-id'));
Fullscreen.cancel();
Fullscreen.isEnabled();
Fullscreen.isSupported();
});
+34
View File
@@ -0,0 +1,34 @@
// Type definitions for AngularJS HTML5 Fullscreen v1.0.1
// Project: https://github.com/fabiobiondi/angular-fullscreen
// Definitions by: Julien Paroche <https://github.com/julienpa>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/angular-fullscreen
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.fullscreen {
/**
* Prefixing interface name with "I" is not recommended: http://www.typescriptlang.org/Handbook#writing-dts-files
* However, we let it here to keep consistency with all the other Angular-related definitions
*/
interface IFullscreen {
// enable document fullscreen
all(): void;
// enable or disable the document fullscreen
toggleAll(): void;
// enable fullscreen to a specific element
enable(element: Element|HTMLElement): void;
// disable fullscreen
cancel(): void;
// return true if fullscreen is enabled, otherwise false
isEnabled(): boolean;
// return true if fullscreen API is supported by your browser
isSupported(): boolean;
}
}
@@ -0,0 +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;
}
}
@@ -1,4 +1,5 @@
/// <reference path="angular-google-analytics.d.ts" />
/// <reference path="angular-google-analytics-service.d.ts" />
function ConfigurationMethodChaining(AnalyticsProvider: angular.google.analytics.AnalyticsProvider) {
AnalyticsProvider
@@ -54,3 +55,41 @@ function SetRouteTrackingBehaviors(AnalyticsProvider: angular.google.analytics.A
AnalyticsProvider.setPageEvent("$stateChangeSuccess");
AnalyticsProvider.setRemoveRegExp(/\/\d+?$/);
}
function RetrieveCurrentURL(Analytics: angular.google.analytics.AnalyticsService) {
var test = Analytics.getUrl();
}
function ManualScriptTagInjection(Analytics: angular.google.analytics.AnalyticsService) {
Analytics.createScriptTag();
Analytics.createAnalyticsScriptTag();
}
function SetCustomDimensions(Analytics: angular.google.analytics.AnalyticsService) {
Analytics.set('&uid', 1234);
Analytics.set('dimension1', 'Paid');
Analytics.set('dimension2', 'Paid', 'accountName');
}
function PageTracking(Analytics: angular.google.analytics.AnalyticsService) {
Analytics.trackPage('/video/detail/XXX');
Analytics.trackPage('/video/detail/XXX', 'Video XXX');
Analytics.trackPage('/video/detail/XXX', 'Video XXX', { dimension15: 'My Custom Dimension', metric18: 8000 });
}
function EventTracking(Analytics: angular.google.analytics.AnalyticsService) {
Analytics.trackEvent('video', 'play', 'django.mp4');
Analytics.trackEvent('video', 'play', 'django.mp4', 4);
Analytics.trackEvent('video', 'play', 'django.mp4', 4, true);
Analytics.trackEvent('video', 'play', 'django.mp4', 4, true, { dimension15: 'My Custom Dimension', metric18: 8000 });
}
function ExceptionTracking(Analytics: angular.google.analytics.AnalyticsService) {
Analytics.trackException('Function "foo" is undefined on object "bar"', true);
}
function OfflineMode(Analytics: angular.google.analytics.AnalyticsService) {
Analytics.offline(true);
Analytics.offline(false);
Analytics.offlineQueue;
}
+65 -65
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();
});
+259 -259
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;
}
}
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="./angular-load.d.ts" />
angular.module('app',['angularLoad'])
.run(['angularLoad',(angularLoad:angular.load.IAngularLoadService)=> {
angularLoad.loadScript("https://ajax.googleapis.com/ajax/libs/angular_material/1.0.4/angular-material.min.js").then(
()=>console.log("angular material js loaded")
);
angularLoad.loadCss("https://ajax.googleapis.com/ajax/libs/angular_material/1.0.4/angular-material.css").then(
()=>console.log("angular material css loaded")
);
}]);
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for angular-load v0.4.1
// Project: https://github.com/urish/angular-load
// Definitions by: david-gang <https://github.com/david-gang>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.load {
interface IAngularLoadService {
loadScript(url:string): ng.IPromise<any>;
loadCss(url:string): ng.IPromise<any>;
}
}
+11 -2
View File
@@ -63,7 +63,10 @@ declare module angular.material {
interface IDialogOptions {
templateUrl?: string;
template?: string;
autoWrap?: boolean; // default: true
targetEvent?: MouseEvent;
openFrom?: any;
closeTo?: any;
scope?: angular.IScope; // default: new child scope
preserveScope?: boolean; // default: false
disableParentScroll?: boolean; // default: true
@@ -77,8 +80,10 @@ declare module angular.material {
resolve?: {[index: string]: angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
fullscreen?: boolean;
onShowing?: Function;
onComplete?: Function;
onRemoving?: Function;
fullscreen?: boolean;
}
interface IDialogService {
@@ -224,7 +229,7 @@ declare module angular.material {
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
}
interface IDateLocaleProvider {
months: string[];
shortMonths: string[];
@@ -239,4 +244,8 @@ declare module angular.material {
msgCalendar: string;
msgOpenCalendar: string;
}
interface IMenuService {
hide(response?: any, options?: any): angular.IPromise<any>;
}
}
+255 -255
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');
}]);
+352 -352
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 { }
}
@@ -174,6 +174,7 @@ var user = odataResourceClass.odata()
.skip(10)
.take(20)
.orderBy("Name", "desc")
.transformUrl((s)=>s)
.single();
user.$save();
+1
View File
@@ -281,6 +281,7 @@ declare module OData {
constructor(callback: ProviderCallback<T>);
filter(operand1: any, operand2?: any, operand3?: any): Provider<T>;
orderBy(arg1: string, arg2?: string): Provider<T>;
transformUrl(transformMethod : (url:string)=>string): Provider<T>;
take(amount: number): Provider<T>;
skip(amount: number): Provider<T>;
private execute();
+11 -1
View File
@@ -406,9 +406,19 @@ function TestElementArrayFinder() {
elementArrayFinder.each(function(element: protractor.ElementFinder){
// nothing
});
stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){
return 'abc';
})
});
stringPromise = elementArrayFinder.map<string>(function(element: protractor.ElementFinder, index: number): string {
return 'abc';
});
stringPromise = elementArrayFinder.map<string, webdriver.promise.Promise<string>>(function(element: protractor.ElementFinder, index: number): webdriver.promise.Promise<string> {
return element.getText();
});
elementArrayFinder = elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){
return element.getText().then((text: string) => {
return text === "foo";
+1
View File
@@ -992,6 +992,7 @@ declare module protractor {
* of values returned by the map function.
*/
map<T>(mapFn: (element: ElementFinder, index: number) => T): webdriver.promise.Promise<T[]>;
map<T, T2>(mapFn: (element: ElementFinder, index: number) => T2): webdriver.promise.Promise<T[]>;
/**
* Apply a filter function to each element within the ElementArrayFinder. Returns
@@ -0,0 +1,29 @@
/// <reference path='../angularjs/angular.d.ts' />
/// <reference path='angular-touchspin.d.ts' />
angular
.module('touchspin-tests', ['lm.touchspin'])
.config(function(touchspinConfigProvider: angularTouchSpin.ITouchSpinConfigProvider) {
touchspinConfigProvider.defaults(<angularTouchSpin.ITouchSpinOptions>{
min: 0,
max: 0,
step: 0,
decimals: 0,
stepInterval: 0,
forceStepDivisibility: '', // none | floor | round | ceil
stepIntervalDelay: 0,
verticalButtons: true,
verticalUpClass: '',
verticalDownClass: '',
initVal: 0,
prefix: '',
postfix: '',
prefixExtraClass: '',
postfixExtraClass: '',
mousewheel: true,
buttonDownClass: '',
buttonUpClass: '',
buttonDownTxt: '',
buttonUpTxt: ''
});
});
+43
View File
@@ -0,0 +1,43 @@
// Type definitions for Angular Touchspin v1.0.0
// Project: https://github.com/nkovacic/angular-touchspin
// Definitions by: Niko Kovačič <https://github.com/nkovacic>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
//// <reference path="../angularjs/angular.d.ts" />
declare module "angular-touchspin" {
let _: string;
export = _;
}
declare module angularTouchSpin {
interface ITouchSpinOptions {
min?: number;
max?: number;
step?: number;
decimals?: number;
stepInterval?: number;
forceStepDivisibility?: string; // none | floor | round | ceil
stepIntervalDelay?: number;
verticalButtons?: boolean;
verticalUpClass?: string;
verticalDownClass?: string;
initVal?: number;
prefix?: string;
postfix?: string;
prefixExtraClass?: string;
postfixExtraClass?: string;
mousewheel?: boolean;
buttonDownClass?: string;
buttonUpClass?: string;
buttonDownTxt?: string;
buttonUpTxt?: string;
}
interface ITouchSpinConfig extends ITouchSpinOptions { }
interface ITouchSpinConfigProvider {
defaults(touchSpinOptions: ITouchSpinOptions): void;
}
}
+9 -1
View File
@@ -6,7 +6,15 @@
/// <reference path="../angularjs/angular.d.ts" />
// Support for AMD require
declare module 'angular-bootstrap' {}
declare module 'angular-bootstrap' {
let _: string;
export = _;
}
declare module 'angular-ui-bootstrap' {
let _: string;
export = _;
}
declare module angular.ui.bootstrap {
+165 -59
View File
@@ -1,68 +1,114 @@
/// <reference path="../jasmine/jasmine.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
/// <reference path="../angularjs/angular-mocks.d.ts" />
/// <reference path="angular-wizard.d.ts" />
// test file taken from https://github.com/mgonto/angular-wizard
interface WizardScope extends ng.IScope {
referenceCurrentStep:string;
stepValidation:()=>void;
finishedWizard:()=>void;
enterValidation:()=>void;
interface IWizardScope extends ng.IScope {
referenceCurrentStep: string;
stepValidation: () => void;
finishedWizard: () => void;
enterValidation: () => void;
exitValidation: boolean;
dynamicStepDisabled: string;
}
describe('AngularWizard', function () {
var $compile:ng.ICompileService,
$rootScope:ng.IRootScopeService, WizardHandler:angular.mgoAngularWizard.WizardHandler, scope:WizardScope;
var $compile: ng.ICompileService,
$q: ng.IQService,
$rootScope: ng.IRootScopeService,
$timeout: ng.ITimeoutService,
WizardHandler: angular.mgoAngularWizard.WizardHandler;
beforeEach(() => angular.module('mgo-angular-wizard'));
beforeEach(inject(function (_$compile_: ng.ICompileService,
_$q_: ng.IQService,
_$rootScope_: ng.IRootScopeService,
_$timeout_: ng.ITimeoutService,
_WizardHandler_: angular.mgoAngularWizard.WizardHandler) {
$compile = _$compile_;
$q = _$q_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
WizardHandler = _WizardHandler_;
}));
/**
* Create the view with wizard to test
* Create the generic view with wizard to test
* @param {Scope} scope A scope to bind to
* @return {[DOM element]} A DOM element compiled
*/
function createView(scope:WizardScope) {
function createGenericView(scope: IWizardScope) {
scope.referenceCurrentStep = null;
var element = angular.element('<wizard on-finish="finishedWizard()" current-step="referenceCurrentStep" ng-init="msg = 14" >'
+ ' <wz-step title="Starting" canenter="enterValidation">'
+ ' <h1>This is the first step</h1>'
+ ' <p>Here you can use whatever you want. You can use other directives, binding, etc.</p>'
+ ' <input type="submit" wz-next value="Continue" />'
+ ' </wz-step>'
+ ' <wz-step title="Continuing" canexit="stepValidation">'
+ ' <h1>Continuing</h1>'
+ ' <p>You have continued here!</p>'
+ ' <input type="submit" wz-next value="Go on" />'
+ ' </wz-step>'
+ ' <wz-step title="More steps" canenter="enterValidation">'
+ ' <p>Even more steps!!</p>'
+ ' <input type="submit" wz-next value="Finish now" />'
+ ' </wz-step>'
+ '</wizard>');
+ ' <wz-step wz-title="Starting" canenter="enterValidation" description="Step description">'
+ ' <h1>This is the first step</h1>'
+ ' <p>Here you can use whatever you want. You can use other directives, binding, etc.</p>'
+ ' <input type="submit" wz-next value="Continue" />'
+ ' </wz-step>'
+ ' <wz-step wz-title="Dynamic" wz-disabled="{{dynamicStepDisabled == \'Y\'}}">'
+ ' <h1>Dynamic {{dynamicStepDisabled}}</h1>'
+ ' <p>You have continued here!</p>'
+ ' <input type="submit" wz-next value="Go on" />'
+ ' </wz-step>'
+ ' <wz-step wz-title="Continuing" canexit="stepValidation">'
+ ' <h1>Continuing</h1>'
+ ' <p>You have continued here!</p>'
+ ' <input type="submit" wz-next value="Go on" />'
+ ' </wz-step>'
+ ' <wz-step wz-title="More steps" canenter="enterValidation">'
+ ' <p>Even more steps!!</p>'
+ ' <input type="submit" wz-next value="Finish now" />'
+ ' </wz-step>'
+ '</wizard>');
var elementCompiled = $compile(element)(scope);
$rootScope.$digest();
return elementCompiled;
}
it("should correctly create the wizard", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
var view = createGenericView(scope);
expect(WizardHandler).toBeTruthy();
expect(view.find('section').length).toEqual(3);
expect(view.find('section').length).toEqual(4);
// expect the correct step to be desirable one
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to the next step", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Dynamic');
});
it("should render only those steps which are enabled", function () {
var scope =<IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should enable or disable dynamic steps based on conditions", function () {
var scope = <IWizardScope>$rootScope.$new();
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
scope.dynamicStepDisabled = 'Y';
$rootScope.$digest();
WizardHandler.wizard().goTo(2);
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should return to a previous step", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
@@ -72,24 +118,27 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to a step specified by name", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo('More steps');
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to a step specified by index", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo(2);
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to next step becasue callback is truthy", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next(function () {
return true
@@ -98,8 +147,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should NOT go to next step because callback is falsey", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next(function () {
return false
@@ -108,16 +158,18 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should go to next step because CANEXIT is UNDEFINED", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should go to next step because CANEXIT is TRUE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return true;
};
@@ -130,8 +182,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should NOT go to next step because CANEXIT is FALSE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return false;
};
@@ -144,8 +197,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should go to next step because CANENTER is TRUE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.enterValidation = function () {
return true;
};
@@ -158,8 +212,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should NOT go to next step because CANENTER is FALSE", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.enterValidation = function () {
return false;
};
@@ -172,8 +227,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should NOT return to a previous step. Although CANEXIT is false and we are heading to a previous state, the can enter validation is false", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return false;
};
@@ -189,8 +245,9 @@ describe('AngularWizard', function () {
expect(scope.referenceCurrentStep).toEqual('Continuing');
});
it("should return to a previous step even though CANEXIT is false", function () {
var view = createView(scope);
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.stepValidation = function () {
return false;
};
@@ -202,17 +259,66 @@ describe('AngularWizard', function () {
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("should finish", function () {
var flag = false;
scope.finishedWizard = function () {
flag = true;
it("should go to the next step because the promise that CANENTER returns resolves to true", function (done) {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.enterValidation = function () {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve(true);
done();
});
return deferred.promise;
};
var view = createView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$timeout.flush();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should go to the next step because CANEXIT is set to true", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
scope.exitValidation = true;
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Continuing');
WizardHandler.wizard().next();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
});
it("should finish", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var flag = false;
scope.finishedWizard = function () { flag = true; };
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().finish();
expect(flag).toBeTruthy();
$rootScope.$digest();
});
it("should go to first step when reset is called", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect(scope.referenceCurrentStep).toEqual('Starting');
WizardHandler.wizard().goTo(2);
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('More steps');
WizardHandler.wizard().reset();
$rootScope.$digest();
expect(scope.referenceCurrentStep).toEqual('Starting');
});
it("step description should be accessible", function () {
var scope = <IWizardScope>$rootScope.$new();
scope.dynamicStepDisabled = 'Y';
var view = createGenericView(scope);
expect((<any>view.isolateScope()).steps[0].description).toEqual('Step description');
});
});
+28 -11
View File
@@ -1,21 +1,38 @@
// Type definitions for Angular Wizard 0.4.2
// Type definitions for Angular Wizard 0.6.1
// Project: https://github.com/mgonto/angular-wizard
// Definitions by: Marko Jurisic <https://github.com/mjurisic>
// Definitions by: Marko Jurisic <https://github.com/mjurisic>, Ronald Wildenberg <https://github.com/rwwilden>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.mgoAngularWizard {
interface WizardHandler {
wizard(name?:string): Wizard;
addWizard(name:string, wizard:Wizard):void;
removeWizard(name:string):void;
wizard(name?: string): Wizard;
addWizard(name: string, wizard: Wizard): void;
removeWizard(name: string): void;
}
interface Wizard {
next(nextHandler?:Function):void;
previous():void;
goTo(step:number):void;
goTo(step:string):void;
finish():void;
currentStepNumber():number;
next(nextHandler?: () => boolean): void;
previous(): void;
cancel: () => void;
goTo(step: number | string): void;
finish(): void;
reset: () => void;
addStep: (step: WzStep) => void;
currentStep: () => WzStep;
currentStepNumber(): number;
currentStepDescription: () => string;
currentStepTitle: () => string;
getEnabledSteps(): WzStep[];
}
interface WzStep {
canenter: (...args: any[]) => boolean;
canexit: (...args: any[]) => boolean;
description: string;
selected: boolean;
title: string;
wzData: any;
wzTitle: string;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-3
View File
@@ -1,3 +0,0 @@
/// <reference path="angular2.d.ts"/>
// No tests, because angular 2 typings are not in DefinitelyTyped.
-13
View File
@@ -1,13 +0,0 @@
// Type definitions for Angular 2
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Angular 2 distributes typings in our NPM package.
// To get the typings, simply:
// $ npm install angular2
// and use TypeScript 1.6.2 or later.
//
// Note that TypeScript must be configured with
// --moduleResolution node
// which is the default when --module commonjs
-1007
View File
File diff suppressed because it is too large Load Diff
-1310
View File
File diff suppressed because it is too large Load Diff
-1310
View File
File diff suppressed because it is too large Load Diff
-352
View File
@@ -1,352 +0,0 @@
// Type definitions for Angular v2.0.0-alpha.30
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
///<reference path="./angular2-2.0.0-alpha.30.d.ts"/>
/**
* @module
* @public
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ng {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*
* @exportedAs angular2/router
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
previousUrl: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config({ 'path': '/', 'component': IndexCmp});
* ```
*
* Or:
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(config: StringMap<string, any>| List<StringMap<string, any>>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: any): void;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction): Promise<any>;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): string;
}
class RootRouter extends Router {
commit(instruction: any): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
/**
* Given an instruction, update the contents of this outlet.
*/
activate(instruction: Instruction): Promise<any>;
deactivate(): Promise<any>;
canDeactivate(instruction: Instruction): Promise<boolean>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig({
* path: '/user', component: UserCmp, as: 'user'
* });
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*
* @exportedAs angular2/router
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: StringMap<string, any>): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): string;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: any, onThrow?: any, onReturn?: any): void;
}
var appBaseHrefToken : OpaqueToken ;
class Instruction {
reuseComponentsFrom(oldInstruction: Instruction): void;
params(): StringMap<string, string>;
hasChild(): boolean;
}
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
var routerDirectives : List<any> ;
var routerInjectables : List<any> ;
var RouteConfig:any;
}
declare module "angular2/router" {
export = ng;
}
-459
View File
@@ -1,459 +0,0 @@
// Type definitions for Angular v2.0.0-alpha.31
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
///<reference path="./angular2-2.0.0-alpha.31.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ng {
interface List<T> extends Array<T> {}
interface Map<K,V> {}
interface StringMap<K,V> extends Map<K,V> {}
export class Instruction {
// "capturedUrl" is the part of the URL captured by this instruction
// "accumulatedUrl" is the part of the URL captured by this instruction and all children
accumulatedUrl: string;
reuse: boolean;
specificity: number;
private _params: StringMap<string, string>;
constructor (component: any, capturedUrl: string,
_recognizer: PathRecognizer, child: Instruction);
params(): StringMap<string, string>;
}
class TouchMap {
map: StringMap<string, string>;
keys: StringMap<string, boolean>;
constructor(map: StringMap<string, any>);
get(key: string): string;
getUnused(): StringMap<string, any>;
}
export class Segment {
name: string;
regex: string;
generate(params: TouchMap): string;
}
export class PathRecognizer {
segments: List<Segment>;
regex: RegExp;
specificity: number;
terminal: boolean;
path: string;
handler: RouteHandler;
constructor(path: string, handler: RouteHandler);
parseParams(url: string): StringMap<string, string>;
generate(params: StringMap<string, any>): string;
resolveComponentType(): Promise<any>;
}
export interface RouteHandler {
componentType: Function;
resolveComponentType(): Promise<any>;
}
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config({ 'path': '/', 'component': IndexCmp});
* ```
*
* Or:
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(config: StringMap<string, any>| List<StringMap<string, any>>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: any): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): string;
}
class RootRouter extends Router {
commit(instruction: any): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig({
* path: '/user', component: UserCmp, as: 'user'
* });
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: StringMap<string, any>): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): string;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: any, onThrow?: any, onReturn?: any): void;
}
var appBaseHrefToken : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate]
*/
interface OnActivate {
onActivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onDeactivate]
*/
interface OnDeactivate {
onDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onReuse]
*/
interface OnReuse {
onReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canDeactivate]
*/
interface CanDeactivate {
canDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canReuse]
*/
interface CanReuse {
canReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
var CanActivate:any;
var routerDirectives : List<any> ;
var routerInjectables : List<any> ;
var RouteConfig:any;
}
declare module "angular2/router" {
export = ng;
}
-469
View File
@@ -1,469 +0,0 @@
// Type definitions for Angular v2.0.0-alpha.34
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
///<reference path="./angular2-2.0.0-alpha.34.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ng {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): string;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition, isRootLevelRoute?: boolean): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any, isRootComponent?: boolean): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): string;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const appBaseHrefToken : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate]
*/
interface OnActivate {
onActivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onDeactivate]
*/
interface OnDeactivate {
onDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [onReuse]
*/
interface OnReuse {
onReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canDeactivate]
*/
interface CanDeactivate {
canDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
/**
* Defines route lifecycle method [canReuse]
*/
interface CanReuse {
canReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
}
var CanActivate : (hook: (next: Instruction, prev: Instruction) => Promise<boolean>| boolean) => ClassDecorator ;
/**
* An `Instruction` represents the component hierarchy of the application based on a given route
*/
class Instruction {
accumulatedUrl: string;
reuse: boolean;
specificity: number;
component: any;
capturedUrl: string;
child: Instruction;
params(): StringMap<string, string>;
}
const routerDirectives : List<any> ;
var routerInjectables : List<any> ;
class Route implements RouteDefinition {
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
}
class AsyncRoute implements RouteDefinition {
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
}
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
}
declare module "angular2/router" {
export = ng;
}
-689
View File
@@ -1,689 +0,0 @@
// Type definitions for Angular v2.0.0-alpha.35
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/router depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2-2.0.0-alpha.35.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ngRouter {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: Array<RouteDefinition>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Navigate via the provided instruction. Returns a promise that resolves when navigation is
* complete.
*/
navigateInstruction(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: Array<any>): Instruction;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
name: string;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: Array<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const APP_BASE_HREF : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: Array<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate], which is called by the router at the end of a
* successful route navigation.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* If `onActivate` returns a promise, the route change will wait until the promise settles to
* instantiate and activate child components.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements OnActivate {
* onActivate(next, prev) {
* this.log = 'Finished navigating from ' + prev.urlPath + ' to ' + next.urlPath;
* }
* }
* ```
*/
interface OnActivate {
onActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onDeactivate], which is called by the router before destroying
* a component as part of a route change.
*
* If `onDeactivate` returns a promise, the route change will wait until the promise settles.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnDeactivate {
onDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onReuse], which is called by the router at the end of a
* successful route navigation when [canReuse] is implemented and returns or resolves to true.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnReuse {
onReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canDeactivate], which is called by the router to determine
* if a component can be removed as part of a navigation.
*
* If `canDeactivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canDeactivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanDeactivate {
* canDeactivate(next, prev) {
* return askUserIfTheyAreSureTheyWantToQuit();
* }
* }
* ```
*/
interface CanDeactivate {
canDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canReuse], which is called by the router to determine whether a
* component should be reused across routes, or whether to destroy and instantiate a new component.
*
* If `canReuse` returns or resolves to `true`, the component instance will be reused.
*
* If `canReuse` throws or rejects, the navigation will be cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
* }
* ```
*/
interface CanReuse {
canReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canActivate], which is called by the router to determine
* if a component can be instantiated as part of a navigation.
*
* Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
* This is because [canActivate] is called before the component is instantiated.
*
* If `canActivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canActivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'control-panel-cmp'
* })
* @CanActivate(() => checkIfUserIsLoggedIn())
* class ControlPanelCmp {
* // ...
* }
* ```
*/
var CanActivate : (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) =>
ClassDecorator ;
/**
* `Instruction` is a tree of `ComponentInstructions`, with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* This is a public API.
*/
class Instruction {
component: ComponentInstruction;
child: Instruction;
auxInstruction: StringMap<string, Instruction>;
replaceChild(child: Instruction): Instruction;
}
/**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
* composed of a tree of these `ComponentInstruction`s.
*
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: Array<string>;
params: StringMap<string, any>;
componentType: void;
resolveComponentType(): Promise<Type>;
specificity: void;
terminal: void;
routeData(): Object;
}
class Url {
path: string;
child: Url;
auxiliary: Array<Url>;
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
/**
* Runtime representation of a type.
*
* In JavaScript a Type is a constructor function.
*/
interface Type extends Function {
new(args: any): any;
}
const routerDirectives : Array<any> ;
var routerInjectables : Array<any> ;
class Route implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
loader: Function;
data: any;
}
class AuxRoute implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
const ROUTE_DATA : OpaqueToken ;
var RouteConfig : (configs: Array<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
}
declare module "angular2/router" {
export = ngRouter;
}
-689
View File
@@ -1,689 +0,0 @@
// Type definitions for Angular v2.0.0-alpha.36
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/router depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2-2.0.0-alpha.36.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ngRouter {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: Array<RouteDefinition>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Navigate via the provided instruction. Returns a promise that resolves when navigation is
* complete.
*/
navigateInstruction(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): Object;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: Array<any>): Instruction;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
name: string;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: any;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: Array<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class PathLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const APP_BASE_HREF : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: Array<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate], which is called by the router at the end of a
* successful route navigation.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* If `onActivate` returns a promise, the route change will wait until the promise settles to
* instantiate and activate child components.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements OnActivate {
* onActivate(next, prev) {
* this.log = 'Finished navigating from ' + prev.urlPath + ' to ' + next.urlPath;
* }
* }
* ```
*/
interface OnActivate {
onActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onDeactivate], which is called by the router before destroying
* a component as part of a route change.
*
* If `onDeactivate` returns a promise, the route change will wait until the promise settles.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnDeactivate {
onDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onReuse], which is called by the router at the end of a
* successful route navigation when [canReuse] is implemented and returns or resolves to true.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnReuse {
onReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canDeactivate], which is called by the router to determine
* if a component can be removed as part of a navigation.
*
* If `canDeactivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canDeactivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanDeactivate {
* canDeactivate(next, prev) {
* return askUserIfTheyAreSureTheyWantToQuit();
* }
* }
* ```
*/
interface CanDeactivate {
canDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canReuse], which is called by the router to determine whether a
* component should be reused across routes, or whether to destroy and instantiate a new component.
*
* If `canReuse` returns or resolves to `true`, the component instance will be reused.
*
* If `canReuse` throws or rejects, the navigation will be cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
* }
* ```
*/
interface CanReuse {
canReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canActivate], which is called by the router to determine
* if a component can be instantiated as part of a navigation.
*
* Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
* This is because [canActivate] is called before the component is instantiated.
*
* If `canActivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canActivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'control-panel-cmp'
* })
* @CanActivate(() => checkIfUserIsLoggedIn())
* class ControlPanelCmp {
* // ...
* }
* ```
*/
var CanActivate : (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) =>
ClassDecorator ;
/**
* `Instruction` is a tree of `ComponentInstructions`, with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* This is a public API.
*/
class Instruction {
component: ComponentInstruction;
child: Instruction;
auxInstruction: StringMap<string, Instruction>;
replaceChild(child: Instruction): Instruction;
}
/**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
* composed of a tree of these `ComponentInstruction`s.
*
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: Array<string>;
params: StringMap<string, any>;
componentType: any;
resolveComponentType(): Promise<Type>;
specificity: any;
terminal: any;
routeData(): Object;
}
class Url {
path: string;
child: Url;
auxiliary: Array<Url>;
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
/**
* Runtime representation of a type.
*
* In JavaScript a Type is a constructor function.
*/
interface Type extends Function {
new(args: any): any;
}
const ROUTE_DATA : OpaqueToken ;
const ROUTER_DIRECTIVES : Array<any> ;
const ROUTER_BINDINGS : Array<any> ;
class Route implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
loader: Function;
data: any;
}
class AuxRoute implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
var RouteConfig : (configs: Array<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
}
declare module "angular2/router" {
export = ngRouter;
}
-738
View File
@@ -1,738 +0,0 @@
// Type definitions for Angular v2.0.0-alpha.37
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/router depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2-2.0.0-alpha.37.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ngRouter {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
auxRouter(hostComponent: any): Router;
/**
* Register an outlet to notified of primary route changes.
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerPrimaryOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Register an outlet to notified of auxiliary route changes.
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerAuxOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Given an instruction, returns `true` if the instruction is currently active,
* otherwise `false`.
*/
isRouteActive(instruction: Instruction): boolean;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: RouteDefinition[]): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Navigate via the provided instruction. Returns a promise that resolves when navigation is
* complete.
*/
navigateInstruction(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): Object;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: any[]): Instruction;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
name: string;
/**
* Called by the Router to instantiate a new component during the commit phase of a navigation.
* This method in turn is responsible for calling the `onActivate` hook of its child.
*/
activate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} during the commit phase of a navigation when an outlet
* reuses a component between different routes.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
reuse(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} when an outlet reuses a component across navigations.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
deactivate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If this resolves to `false`, the given navigation is cancelled.
*
* This method delegates to the child component's `canDeactivate` hook if it exists,
* and otherwise resolves to true.
*/
canDeactivate(nextInstruction: ComponentInstruction): Promise<boolean>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If the new child component has a different Type than the existing child component,
* this will resolve to `false`. You can't reuse an old component when the new component
* is of a different Type.
*
* Otherwise, this method delegates to the child component's `canReuse` hook if it exists,
* or resolves to true if the hook is not present.
*/
canReuse(nextInstruction: ComponentInstruction): Promise<boolean>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
isRouteActive: boolean;
routeParams: any;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: any[], parentComponent: any): Instruction;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class PathLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
platformStrategy: LocationStrategy;
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const APP_BASE_HREF : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: Function[];
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate], which is called by the router at the end of a
* successful route navigation.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* If `onActivate` returns a promise, the route change will wait until the promise settles to
* instantiate and activate child components.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements OnActivate {
* onActivate(next, prev) {
* this.log = 'Finished navigating from ' + prev.urlPath + ' to ' + next.urlPath;
* }
* }
* ```
*/
interface OnActivate {
onActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onDeactivate], which is called by the router before destroying
* a component as part of a route change.
*
* If `onDeactivate` returns a promise, the route change will wait until the promise settles.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnDeactivate {
onDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onReuse], which is called by the router at the end of a
* successful route navigation when [canReuse] is implemented and returns or resolves to true.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnReuse {
onReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canDeactivate], which is called by the router to determine
* if a component can be removed as part of a navigation.
*
* If `canDeactivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canDeactivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanDeactivate {
* canDeactivate(next, prev) {
* return askUserIfTheyAreSureTheyWantToQuit();
* }
* }
* ```
*/
interface CanDeactivate {
canDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canReuse], which is called by the router to determine whether a
* component should be reused across routes, or whether to destroy and instantiate a new component.
*
* If `canReuse` returns or resolves to `true`, the component instance will be reused.
*
* If `canReuse` throws or rejects, the navigation will be cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
* }
* ```
*/
interface CanReuse {
canReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canActivate], which is called by the router to determine
* if a component can be instantiated as part of a navigation.
*
* Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
* This is because [canActivate] is called before the component is instantiated.
*
* If `canActivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canActivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'control-panel-cmp'
* })
* @CanActivate(() => checkIfUserIsLoggedIn())
* class ControlPanelCmp {
* // ...
* }
* ```
*/
var CanActivate : (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) =>
ClassDecorator ;
/**
* `Instruction` is a tree of `ComponentInstructions`, with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* This is a public API.
*/
class Instruction {
component: ComponentInstruction;
child: Instruction;
auxInstruction: StringMap<string, Instruction>;
replaceChild(child: Instruction): Instruction;
}
/**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
* composed of a tree of these `ComponentInstruction`s.
*
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}.
*
* `ComponentInstruction`s are [https://en.wikipedia.org/wiki/Hash_consing](hash consed). You should
* never construct one yourself with "new." Instead, rely on {@link PathRecognizer} to construct
* `ComponentInstruction`s.
*
* You should not modify this object. It should be treated as immutable.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: string[];
params: StringMap<string, any>;
componentType: any;
resolveComponentType(): Promise<ng.Type>;
specificity: any;
terminal: any;
routeData(): Object;
}
/**
* This class represents a parsed URL
*/
class Url {
path: string;
child: Url;
auxiliary: Url[];
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
const ROUTE_DATA : OpaqueToken ;
const ROUTER_DIRECTIVES : any[] ;
const ROUTER_BINDINGS : any[] ;
class Route implements RouteDefinition {
data: any;
path: string;
component: ng.Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
loader: Function;
data: any;
}
class AuxRoute implements RouteDefinition {
data: any;
path: string;
component: ng.Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: ng.Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
var RouteConfig : (configs: RouteDefinition[]) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: ng.Type;
}
}
declare module "angular2/router" {
export = ngRouter;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-408
View File
@@ -1,408 +0,0 @@
// Type definitions for Angular v2.0.0-local_sha.f77234e
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/test_lib depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2-2.0.0-alpha.38.d.ts"/>
///<reference path="../jasmine/jasmine.d.ts"/>
declare module ngTestLib {
/**
* Allows injecting dependencies in `beforeEach()` and `it()`.
*
* Example:
*
* ```
* beforeEach(inject([Dependency, AClass], (dep, object) => {
* // some code that uses `dep` and `object`
* // ...
* }));
*
* it('...', inject([AClass, AsyncTestCompleter], (object, async) => {
* object.doSomething().then(() => {
* expect(...);
* async.done();
* });
* })
* ```
*
* Notes:
* - injecting an `AsyncTestCompleter` allow completing async tests - this is the equivalent of
* adding a `done` parameter in Jasmine,
* - inject is currently a function because of some Traceur limitation the syntax should eventually
* becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
*
* @param {Array} tokens
* @param {Function} fn
* @return {FunctionWithParamTokens}
*/
function inject(tokens: any[], fn: Function): FunctionWithParamTokens;
var proxy: ClassDecorator;
var afterEach: Function;
type SyncTestFn = () => void
interface NgMatchers extends jasmine.Matchers {
toBe(expected: any): boolean;
toEqual(expected: any): boolean;
toBePromise(): boolean;
toBeAnInstanceOf(expected: any): boolean;
toHaveText(expected: any): boolean;
toHaveCssClass(expected: any): boolean;
toImplement(expected: any): boolean;
toContainError(expected: any): boolean;
toThrowErrorWith(expectedMessage: any): boolean;
not: NgMatchers;
}
var expect: (actual: any) => NgMatchers;
class AsyncTestCompleter {
constructor(_done: Function);
done(): void;
}
function describe(...args: any[]): void;
function ddescribe(...args: any[]): void;
function xdescribe(...args: any[]): void;
function beforeEach(fn: FunctionWithParamTokens | SyncTestFn): void;
/**
* Allows overriding default bindings defined in test_injector.js.
*
* The given function must return a list of DI bindings.
*
* Example:
*
* beforeEachBindings(() => [
* bind(Compiler).toClass(MockCompiler),
* bind(SomeToken).toValue(myValue),
* ]);
*/
function beforeEachBindings(fn: any): void;
function it(name: any, fn: any, timeOut?: any): void;
function xit(name: any, fn: any, timeOut?: any): void;
function iit(name: any, fn: any, timeOut?: any): void;
interface GuinessCompatibleSpy extends jasmine.Spy {
/**
* By chaining the spy with and.returnValue, all calls to the function will return a specific
* value.
*/
andReturn(val: any): void;
/**
* By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied
* function.
*/
andCallFake(fn: Function): GuinessCompatibleSpy;
/**
* removes all recorded calls
*/
reset(): void;
}
class SpyObject {
constructor(type?: any);
static stub(object?: any, config?: any, overrides?: any): void;
noSuchMethod(args: any): void;
spy(name: any): void;
prop(name: any, value: any): void;
}
function isInInnerZone(): boolean;
interface RootTestComponent {
debugElement: ng.DebugElement;
detectChanges(): void;
destroy(): void;
}
/**
* Builds a RootTestComponent for use in component level tests.
*/
class TestComponentBuilder {
constructor(_injector: ng.Injector);
/**
* Overrides only the html of a {@link ComponentMetadata}.
* All the other properties of the component's {@link ng.ViewMetadata} are preserved.
*
* @param {ng.Type} component
* @param {string} html
*
* @return {TestComponentBuilder}
*/
overrideTemplate(componentType: ng.Type, template: string): TestComponentBuilder;
/**
* Overrides a component's {@link ng.ViewMetadata}.
*
* @param {ng.Type} component
* @param {view} View
*
* @return {TestComponentBuilder}
*/
overrideView(componentType: ng.Type, view: ng.ViewMetadata): TestComponentBuilder;
/**
* Overrides the directives from the component {@link ng.ViewMetadata}.
*
* @param {ng.Type} component
* @param {ng.Type} from
* @param {ng.Type} to
*
* @return {TestComponentBuilder}
*/
overrideDirective(componentType: ng.Type, from: ng.Type, to: ng.Type): TestComponentBuilder;
/**
* Overrides one or more injectables configured via `bindings` metadata property of a directive or
* component.
* Very useful when certain bindings need to be mocked out.
*
* The bindings specified via this method are appended to the existing `bindings` causing the
* duplicated bindings to
* be overridden.
*
* @param {ng.Type} component
* @param {any[]} bindings
*
* @return {TestComponentBuilder}
*/
overrideBindings(type: ng.Type, bindings: any[]): TestComponentBuilder;
/**
* Overrides one or more injectables configured via `bindings` metadata property of a directive or
* component.
* Very useful when certain bindings need to be mocked out.
*
* The bindings specified via this method are appended to the existing `bindings` causing the
* duplicated bindings to
* be overridden.
*
* @param {ng.Type} component
* @param {any[]} bindings
*
* @return {TestComponentBuilder}
*/
overrideViewBindings(type: ng.Type, bindings: any[]): TestComponentBuilder;
/**
* Builds and returns a RootTestComponent.
*
* @return {Promise<RootTestComponent>}
*/
createAsync(rootComponentType: ng.Type): Promise<RootTestComponent>;
}
function createTestInjector(bindings: Array<ng.Type | ng.Binding | any[]>): ng.Injector;
class FunctionWithParamTokens {
constructor(_tokens: any[], _fn: Function);
/**
* Returns the value of the executed function.
*/
execute(injector: ng.Injector): any;
hasToken(token: any): boolean;
}
/**
* Wraps a function to be executed in the fakeAsync zone:
* - microtasks are manually executed by calling `flushMicrotasks()`,
* - timers are synchronous, `tick()` simulates the asynchronous passage of time.
*
* If there are any pending timers at the end of the function, an exception will be thrown.
*
* @param fn
* @returns {Function} The function wrapped to be executed in the fakeAsync zone
*/
function fakeAsync(fn: Function): Function;
function clearPendingTimers(): void;
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* @param {number} millis Number of millisecond, defaults to 0
*/
function tick(millis?: number): void;
/**
* Flush any pending microtasks.
*/
function flushMicrotasks(): void;
class Log {
constructor();
add(value: any): void;
fn(value: any): void;
clear(): void;
result(): string;
}
class BrowserDetection {
constructor(ua: string);
isFirefox: boolean;
isAndroid: boolean;
isEdge: boolean;
isIE: boolean;
isWebkit: boolean;
isIOS7: boolean;
isSlow: boolean;
supportsIntlApi: boolean;
}
var browserDetection: BrowserDetection;
function dispatchEvent(element: any, eventType: any): void;
function el(html: string): HTMLElement;
function containsRegexp(input: string): RegExp;
function normalizeCSS(css: string): string;
function stringifyElement(el: any): string;
var RootTestComponent: ng.InjectableReference;
}
declare module "angular2/test_lib" {
export = ngTestLib;
}
-408
View File
@@ -1,408 +0,0 @@
// Type definitions for Angular v2.0.0-local_sha.7d5c3eb
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/test_lib depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2-2.0.0-alpha.39.d.ts"/>
///<reference path="../jasmine/jasmine.d.ts"/>
declare module ngTestLib {
/**
* Allows injecting dependencies in `beforeEach()` and `it()`.
*
* Example:
*
* ```
* beforeEach(inject([Dependency, AClass], (dep, object) => {
* // some code that uses `dep` and `object`
* // ...
* }));
*
* it('...', inject([AClass, AsyncTestCompleter], (object, async) => {
* object.doSomething().then(() => {
* expect(...);
* async.done();
* });
* })
* ```
*
* Notes:
* - injecting an `AsyncTestCompleter` allow completing async tests - this is the equivalent of
* adding a `done` parameter in Jasmine,
* - inject is currently a function because of some Traceur limitation the syntax should eventually
* becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
*
* @param {Array} tokens
* @param {Function} fn
* @return {FunctionWithParamTokens}
*/
function inject(tokens: any[], fn: Function): FunctionWithParamTokens;
var proxy: ClassDecorator;
var afterEach: Function;
type SyncTestFn = () => void
interface NgMatchers extends jasmine.Matchers {
toBe(expected: any): boolean;
toEqual(expected: any): boolean;
toBePromise(): boolean;
toBeAnInstanceOf(expected: any): boolean;
toHaveText(expected: any): boolean;
toHaveCssClass(expected: any): boolean;
toImplement(expected: any): boolean;
toContainError(expected: any): boolean;
toThrowErrorWith(expectedMessage: any): boolean;
not: NgMatchers;
}
var expect: (actual: any) => NgMatchers;
class AsyncTestCompleter {
constructor(_done: Function);
done(): void;
}
function describe(...args: any[]): void;
function ddescribe(...args: any[]): void;
function xdescribe(...args: any[]): void;
function beforeEach(fn: FunctionWithParamTokens | SyncTestFn): void;
/**
* Allows overriding default bindings defined in test_injector.js.
*
* The given function must return a list of DI bindings.
*
* Example:
*
* beforeEachBindings(() => [
* bind(Compiler).toClass(MockCompiler),
* bind(SomeToken).toValue(myValue),
* ]);
*/
function beforeEachBindings(fn: any): void;
function it(name: any, fn: any, timeOut?: any): void;
function xit(name: any, fn: any, timeOut?: any): void;
function iit(name: any, fn: any, timeOut?: any): void;
interface GuinessCompatibleSpy extends jasmine.Spy {
/**
* By chaining the spy with and.returnValue, all calls to the function will return a specific
* value.
*/
andReturn(val: any): void;
/**
* By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied
* function.
*/
andCallFake(fn: Function): GuinessCompatibleSpy;
/**
* removes all recorded calls
*/
reset(): void;
}
class SpyObject {
constructor(type?: any);
static stub(object?: any, config?: any, overrides?: any): void;
noSuchMethod(args: any): void;
spy(name: any): void;
prop(name: any, value: any): void;
}
function isInInnerZone(): boolean;
interface RootTestComponent {
debugElement: ng.DebugElement;
detectChanges(): void;
destroy(): void;
}
/**
* Builds a RootTestComponent for use in component level tests.
*/
class TestComponentBuilder {
constructor(_injector: ng.Injector);
/**
* Overrides only the html of a {@link ComponentMetadata}.
* All the other properties of the component's {@link ng.ViewMetadata} are preserved.
*
* @param {ng.Type} component
* @param {string} html
*
* @return {TestComponentBuilder}
*/
overrideTemplate(componentType: ng.Type, template: string): TestComponentBuilder;
/**
* Overrides a component's {@link ng.ViewMetadata}.
*
* @param {ng.Type} component
* @param {view} View
*
* @return {TestComponentBuilder}
*/
overrideView(componentType: ng.Type, view: ng.ViewMetadata): TestComponentBuilder;
/**
* Overrides the directives from the component {@link ng.ViewMetadata}.
*
* @param {ng.Type} component
* @param {ng.Type} from
* @param {ng.Type} to
*
* @return {TestComponentBuilder}
*/
overrideDirective(componentType: ng.Type, from: ng.Type, to: ng.Type): TestComponentBuilder;
/**
* Overrides one or more injectables configured via `bindings` metadata property of a directive or
* component.
* Very useful when certain bindings need to be mocked out.
*
* The bindings specified via this method are appended to the existing `bindings` causing the
* duplicated bindings to
* be overridden.
*
* @param {ng.Type} component
* @param {any[]} bindings
*
* @return {TestComponentBuilder}
*/
overrideBindings(type: ng.Type, bindings: any[]): TestComponentBuilder;
/**
* Overrides one or more injectables configured via `bindings` metadata property of a directive or
* component.
* Very useful when certain bindings need to be mocked out.
*
* The bindings specified via this method are appended to the existing `bindings` causing the
* duplicated bindings to
* be overridden.
*
* @param {ng.Type} component
* @param {any[]} bindings
*
* @return {TestComponentBuilder}
*/
overrideViewBindings(type: ng.Type, bindings: any[]): TestComponentBuilder;
/**
* Builds and returns a RootTestComponent.
*
* @return {Promise<RootTestComponent>}
*/
createAsync(rootComponentType: ng.Type): Promise<RootTestComponent>;
}
function createTestInjector(bindings: Array<ng.Type | ng.Binding | any[]>): ng.Injector;
class FunctionWithParamTokens {
constructor(_tokens: any[], _fn: Function);
/**
* Returns the value of the executed function.
*/
execute(injector: ng.Injector): any;
hasToken(token: any): boolean;
}
/**
* Wraps a function to be executed in the fakeAsync zone:
* - microtasks are manually executed by calling `flushMicrotasks()`,
* - timers are synchronous, `tick()` simulates the asynchronous passage of time.
*
* If there are any pending timers at the end of the function, an exception will be thrown.
*
* @param fn
* @returns {Function} The function wrapped to be executed in the fakeAsync zone
*/
function fakeAsync(fn: Function): Function;
function clearPendingTimers(): void;
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* @param {number} millis Number of millisecond, defaults to 0
*/
function tick(millis?: number): void;
/**
* Flush any pending microtasks.
*/
function flushMicrotasks(): void;
class Log {
constructor();
add(value: any): void;
fn(value: any): void;
clear(): void;
result(): string;
}
class BrowserDetection {
constructor(ua: string);
isFirefox: boolean;
isAndroid: boolean;
isEdge: boolean;
isIE: boolean;
isWebkit: boolean;
isIOS7: boolean;
isSlow: boolean;
supportsIntlApi: boolean;
}
var browserDetection: BrowserDetection;
function dispatchEvent(element: any, eventType: any): void;
function el(html: string): HTMLElement;
function containsRegexp(input: string): RegExp;
function normalizeCSS(css: string): string;
function stringifyElement(el: any): string;
var RootTestComponent: ng.InjectableReference;
}
declare module "angular2/test_lib" {
export = ngTestLib;
}
+230 -230
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();
}
```
-1
View File
@@ -4,7 +4,6 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="./angular.d.ts" />
/// <reference path="../es6-promise/es6-promise.d.ts" />
declare module angular {
/**
+91 -91
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;
}
}
+318 -318
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;
+25 -25
View File
@@ -63,6 +63,26 @@ declare module angular.resource {
responseType?: string;
interceptor?: any;
}
// Allow specify more resource methods
// No need to add duplicates for all four overloads.
interface IResourceMethod<T> {
(): T;
(params: Object): T;
(success: Function, error?: Function): T;
(params: Object, success: Function, error?: Function): T;
(params: Object, data: Object, success?: Function, error?: Function): T;
}
// Allow specify resource moethod which returns the array
// No need to add duplicates for all four overloads.
interface IResourceArrayMethod<T> {
(): IResourceArray<T>;
(params: Object): IResourceArray<T>;
(success: Function, error?: Function): IResourceArray<T>;
(params: Object, success: Function, error?: Function): IResourceArray<T>;
(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
}
// Baseclass for everyresource with default actions.
// If you define your new actions for the resource, you will need
@@ -83,35 +103,15 @@ declare module angular.resource {
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549
interface IResourceClass<T> {
new(dataOrParams? : any) : T;
get(): T;
get(params: Object): T;
get(success: Function, error?: Function): T;
get(params: Object, success: Function, error?: Function): T;
get(params: Object, data: Object, success?: Function, error?: Function): T;
get: IResourceMethod<T>;
query(): IResourceArray<T>;
query(params: Object): IResourceArray<T>;
query(success: Function, error?: Function): IResourceArray<T>;
query(params: Object, success: Function, error?: Function): IResourceArray<T>;
query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray<T>;
query: IResourceArrayMethod<T>;
save(): T;
save(data: Object): T;
save(success: Function, error?: Function): T;
save(data: Object, success: Function, error?: Function): T;
save(params: Object, data: Object, success?: Function, error?: Function): T;
save: IResourceMethod<T>;
remove(): T;
remove(params: Object): T;
remove(success: Function, error?: Function): T;
remove(params: Object, success: Function, error?: Function): T;
remove(params: Object, data: Object, success?: Function, error?: Function): T;
remove: IResourceMethod<T>;
delete(): T;
delete(params: Object): T;
delete(success: Function, error?: Function): T;
delete(params: Object, success: Function, error?: Function): T;
delete(params: Object, data: Object, success?: Function, error?: Function): T;
delete: IResourceMethod<T>;
}
// Instance calls always return the the promise of the request which retrieved the object
+9
View File
@@ -1,3 +1,4 @@
/// <reference path="angular.d.ts" />
/// <reference path="angular-route.d.ts" />
/**
@@ -32,6 +33,14 @@ $routeProvider
return "I return a string"
}
})
.when('/projects/:projectId/dashboard5', {
controller: ['$log',function($log:ng.ILogService){
$log.info('I am array')
}],
templateUrl: function ($routeParams?: ng.route.IRouteParamsService) {
return "I return a string"
}
})
.otherwise({ redirectTo: '/' })
.otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" });
+2 -1
View File
@@ -47,6 +47,7 @@ declare module angular.route {
}
type InlineAnnotatedFunction = Function|Array<string|Function>
/**
* see http://docs.angularjs.org/api/ngRoute/provider/$routeProvider#when for API documentation
@@ -56,7 +57,7 @@ declare module angular.route {
* {(string|function()=}
* Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
*/
controller?: string|Function;
controller?: string|InlineAnnotatedFunction;
/**
* A controller alias name. If present the controller will be published to scope under the controllerAs name.
*/
+40 -40
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;
}
}
}
+10 -1
View File
@@ -379,6 +379,15 @@ module TestDeferred {
}
}
module TestInjector {
let $injector: angular.auto.IInjectorService;
$injector.strictDi = true;
$injector.annotate(() => {});
$injector.annotate(() => {}, true);
}
// Promise signature tests
module TestPromise {
@@ -957,7 +966,7 @@ function NgModelControllerTyping() {
};
}
var $filter: angular.IFilterService;
var $filter: angular.IFilterService;
function testFilter() {

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