diff --git a/.gitignore b/.gitignore index 2a52c95e0..35dd5a667 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/Finch/Finch-tests.ts b/Finch/Finch-tests.ts index 28aeb6b66..ec15bcb88 100644 --- a/Finch/Finch-tests.ts +++ b/Finch/Finch-tests.ts @@ -1,368 +1,368 @@ -/// - -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"); -} +/// + +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"); +} diff --git a/Finch/Finch.d.ts b/Finch/Finch.d.ts index e3dd86c70..ca896570f 100644 --- a/Finch/Finch.d.ts +++ b/Finch/Finch.d.ts @@ -1,47 +1,47 @@ -// Type definitions for Finch 0.5.13 -// Project: https://github.com/stoodder/finchjs -// Definitions by: David Sichau -// 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 +// 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; +} diff --git a/README.md b/README.md index 7e1d60d87..47c56482c 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/accounting/accounting-tests.ts b/accounting/accounting-tests.ts index a00f2fefc..bc9b74eaa 100644 --- a/accounting/accounting-tests.ts +++ b/accounting/accounting-tests.ts @@ -1,107 +1,107 @@ -/// - -// 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] -}; \ No newline at end of file +/// + +// 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] +}; diff --git a/accounting/accounting.d.ts b/accounting/accounting.d.ts index ea861612b..675104047 100644 --- a/accounting/accounting.d.ts +++ b/accounting/accounting.d.ts @@ -3,28 +3,28 @@ // Definitions by: Sergey Gerasimov // 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 { - 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 { + 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; // IAccountingCurrencySettings or IAccountingCurrencySettings +interface IAccountingSettings { + currency: IAccountingCurrencySettings; // IAccountingCurrencySettings or IAccountingCurrencySettings number: IAccountingNumberSettings; } @@ -76,4 +76,4 @@ declare var accounting: IAccountingStatic; declare module "accounting" { export = accounting; -} \ No newline at end of file +} diff --git a/ace/all-tests.ts.tscparams b/ace/all-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/all-tests.ts.tscparams +++ b/ace/all-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-anchor-tests.ts.tscparams b/ace/tests/ace-anchor-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-anchor-tests.ts.tscparams +++ b/ace/tests/ace-anchor-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-background_tokenizer-tests.ts.tscparams b/ace/tests/ace-background_tokenizer-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-background_tokenizer-tests.ts.tscparams +++ b/ace/tests/ace-background_tokenizer-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-default-tests.ts.tscparams b/ace/tests/ace-default-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-default-tests.ts.tscparams +++ b/ace/tests/ace-default-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-document-tests.ts.tscparams b/ace/tests/ace-document-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-document-tests.ts.tscparams +++ b/ace/tests/ace-document-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-edit_session-tests.ts.tscparams b/ace/tests/ace-edit_session-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-edit_session-tests.ts.tscparams +++ b/ace/tests/ace-edit_session-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-editor1-tests.ts.tscparams b/ace/tests/ace-editor1-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-editor1-tests.ts.tscparams +++ b/ace/tests/ace-editor1-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-editor_highlight_selected_word-tests.ts.tscparams b/ace/tests/ace-editor_highlight_selected_word-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-editor_highlight_selected_word-tests.ts.tscparams +++ b/ace/tests/ace-editor_highlight_selected_word-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-editor_navigation-tests.ts.tscparams b/ace/tests/ace-editor_navigation-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-editor_navigation-tests.ts.tscparams +++ b/ace/tests/ace-editor_navigation-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-multi_select-tests.ts.tscparams b/ace/tests/ace-multi_select-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-multi_select-tests.ts.tscparams +++ b/ace/tests/ace-multi_select-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-placeholder-tests.ts.tscparams b/ace/tests/ace-placeholder-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-placeholder-tests.ts.tscparams +++ b/ace/tests/ace-placeholder-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-range_list-tests.ts.tscparams b/ace/tests/ace-range_list-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-range_list-tests.ts.tscparams +++ b/ace/tests/ace-range_list-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-selection-tests.ts.tscparams b/ace/tests/ace-selection-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-selection-tests.ts.tscparams +++ b/ace/tests/ace-selection-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-token_iterator-tests.ts.tscparams b/ace/tests/ace-token_iterator-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-token_iterator-tests.ts.tscparams +++ b/ace/tests/ace-token_iterator-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/ace/tests/ace-virtual_renderer-tests.ts.tscparams b/ace/tests/ace-virtual_renderer-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/ace/tests/ace-virtual_renderer-tests.ts.tscparams +++ b/ace/tests/ace-virtual_renderer-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/amcharts/AmCharts.d.ts.tscparams b/amcharts/AmCharts.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/amcharts/AmCharts.d.ts.tscparams +++ b/amcharts/AmCharts.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/amplifyjs/amplifyjs-tests.ts.tscparams b/amplifyjs/amplifyjs-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/amplifyjs/amplifyjs-tests.ts.tscparams +++ b/amplifyjs/amplifyjs-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/amqplib/amqplib.d.ts b/amqplib/amqplib.d.ts index d03c46ed7..fd74a48c0 100644 --- a/amqplib/amqplib.d.ts +++ b/amqplib/amqplib.d.ts @@ -38,6 +38,7 @@ declare module "amqplib/properties" { messageTtl?: number; expires?: number; deadLetterExchange?: string; + deadLetterRoutingKey?: string; maxLength?: number; } interface DeleteQueue { diff --git a/angular-google-analytics/angular-google-analytics-service.d.ts b/angular-google-analytics/angular-google-analytics-service.d.ts index 5f478621c..e69b63d90 100644 --- a/angular-google-analytics/angular-google-analytics-service.d.ts +++ b/angular-google-analytics/angular-google-analytics-service.d.ts @@ -1,62 +1,62 @@ -// Type definitions for angular-google-analytics v1.1.0 -// Project: https://github.com/revolunet/angular-google-analytics -// Definitions by: Matt Wheatley -// 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; - - /** - * @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; - - /** - * @summary Returns the current URL that would be sent if a `trackPage` call was made. - * @return {string} The URL - */ - getUrl: () => string; - - /** - * @summary Manually create classic analytics (ga.js) script tag - */ - createScriptTag: () => void; - - /** - * @summary Manually create universal analytics (analytics.js) script tag - */ - createAnalyticsScriptTag: () => void; - - /** - * @summary Allows for advanced configuration and definitions in univeral analytics only. This is a no-op when using classic analytics. - */ - set: (key: string, value: any, accountName?: string) => void; - - /** - * @summary Creates a new page view event - * @param {string} pageURL URL of page view - * @param {string} title Page Title - * @param {Object} dimensions Additional dimensions and metrics - */ - trackPage: (pageURL: string, title?: string, dimensions?: { [expr: string]: any }) => void; - - /** - * @summary Create a new event - */ - trackEvent: (category: string, action: string, label: string, value?: any, nonInteractionFlag?: boolean, dimensions?: { [expr: string]: any }) => void; - - trackException: (descrption: string, isFatal: boolean) => void; - - /** - * @summary While in offline mode, no calls to the ga function or pushes to the gaq array are made. - * This will queue all calls for later sending once offline mode is reset to false. - */ - offline: (offlineMode: boolean) => void; - } -} +// Type definitions for angular-google-analytics v1.1.0 +// Project: https://github.com/revolunet/angular-google-analytics +// Definitions by: Matt Wheatley +// 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; + + /** + * @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; + + /** + * @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; + } +} diff --git a/angular-growl-v2/angular-growl-v2-tests.ts b/angular-growl-v2/angular-growl-v2-tests.ts index c03e0725a..13c7cad2e 100644 --- a/angular-growl-v2/angular-growl-v2-tests.ts +++ b/angular-growl-v2/angular-growl-v2-tests.ts @@ -1,65 +1,65 @@ -/// - -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(); -}); +/// + +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(); +}); diff --git a/angular-growl-v2/angular-growl-v2.d.ts b/angular-growl-v2/angular-growl-v2.d.ts index 07c0dbe37..594e45c42 100644 --- a/angular-growl-v2/angular-growl-v2.d.ts +++ b/angular-growl-v2/angular-growl-v2.d.ts @@ -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 -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -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 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +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; + + } +} diff --git a/angular-meteor/angular-meteor-tests.ts b/angular-meteor/angular-meteor-tests.ts index 9ce0a33e9..cc2a62c8d 100644 --- a/angular-meteor/angular-meteor-tests.ts +++ b/angular-meteor/angular-meteor-tests.ts @@ -1,255 +1,255 @@ -/// - -interface ITodo { - _id?: string; - name: string; - public?: boolean; - sticky?: boolean; -} - -interface TodoAngularMeteorObject extends ITodo, angular.meteor.AngularMeteorObject {} - -interface CustomScope extends angular.meteor.IScope { - sticky: boolean; - - todos: angular.meteor.AngularMeteorCollection; - stickyTodos: angular.meteor.AngularMeteorCollection; - notAutoTodos: angular.meteor.AngularMeteorCollection; - - 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('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(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 = $meteor.object(Todos, 'TodoID', false); - $scope.todoSubscribed = $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('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'); -}]); +/// + +interface ITodo { + _id?: string; + name: string; + public?: boolean; + sticky?: boolean; +} + +interface TodoAngularMeteorObject extends ITodo, angular.meteor.AngularMeteorObject {} + +interface CustomScope extends angular.meteor.IScope { + sticky: boolean; + + todos: angular.meteor.AngularMeteorCollection; + stickyTodos: angular.meteor.AngularMeteorCollection; + notAutoTodos: angular.meteor.AngularMeteorCollection; + + 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('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(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 = $meteor.object(Todos, 'TodoID', false); + $scope.todoSubscribed = $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('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'); +}]); diff --git a/angular-meteor/angular-meteor.d.ts b/angular-meteor/angular-meteor.d.ts index e536e3203..e3e66bf34 100644 --- a/angular-meteor/angular-meteor.d.ts +++ b/angular-meteor/angular-meteor.d.ts @@ -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 -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -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; - - /** - * 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 }): 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(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection; - - /** - * 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(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection): AngularMeteorCollection2; - - /** - * 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(collection: Mongo.Collection, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject; - - /** - * 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; - - /** - * 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(name: string, ...methodArguments: any[]): angular.IPromise; - - // 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; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * Request a forgot password email. - * - * @param options.email - The email address to send a password reset link. - */ - forgotPassword(options: {email: string}): angular.IPromise; - - /** - * 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; - - /** - * 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; - - 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; - - /** - * 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; - - // <- 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(collectionName: string): Mongo.Collection; - - // <- $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; - - // <- $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 together with T and cast it, like this: - * - * interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject { } - * var todo = $meteor.object(TodoCollection, 'TodoID'); - */ - interface AngularMeteorObject { - /** - * @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; - - /** - * 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; - } - - /** - * An object that connects a Meteor Collection to an AngularJS scope variable - */ - interface AngularMeteorCollection extends AngularMeteorCollection2 { } - - /** - * An object that connects a Meteor Collection to an AngularJS scope variable, - * but can use a differen type for updates. - */ - interface AngularMeteorCollection2 extends Array { - /** - * @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; - } - - interface ILoginWithExternalService { - (options: Meteor.LoginWithExternalServiceOptions): angular.IPromise; - } - - 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 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +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; + + /** + * 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 }): 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(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection; + + /** + * 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(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection): AngularMeteorCollection2; + + /** + * 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(collection: Mongo.Collection, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject; + + /** + * 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; + + /** + * 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(name: string, ...methodArguments: any[]): angular.IPromise; + + // 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * Request a forgot password email. + * + * @param options.email - The email address to send a password reset link. + */ + forgotPassword(options: {email: string}): angular.IPromise; + + /** + * 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; + + /** + * 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; + + 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; + + /** + * 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; + + // <- 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(collectionName: string): Mongo.Collection; + + // <- $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; + + // <- $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 together with T and cast it, like this: + * + * interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject { } + * var todo = $meteor.object(TodoCollection, 'TodoID'); + */ + interface AngularMeteorObject { + /** + * @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; + + /** + * 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; + } + + /** + * An object that connects a Meteor Collection to an AngularJS scope variable + */ + interface AngularMeteorCollection extends AngularMeteorCollection2 { } + + /** + * An object that connects a Meteor Collection to an AngularJS scope variable, + * but can use a differen type for updates. + */ + interface AngularMeteorCollection2 extends Array { + /** + * @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; + } + + interface ILoginWithExternalService { + (options: Meteor.LoginWithExternalServiceOptions): angular.IPromise; + } + + interface ReactiveResult { } +} diff --git a/angular-touchspin/angular-touchspin-tests.ts b/angular-touchspin/angular-touchspin-tests.ts new file mode 100644 index 000000000..c6e229c7f --- /dev/null +++ b/angular-touchspin/angular-touchspin-tests.ts @@ -0,0 +1,29 @@ +/// +/// + +angular + .module('touchspin-tests', ['lm.touchspin']) + .config(function(touchspinConfigProvider: angularTouchSpin.ITouchSpinConfigProvider) { + touchspinConfigProvider.defaults({ + 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: '' + }); + }); diff --git a/angular-touchspin/angular-touchspin.d.ts b/angular-touchspin/angular-touchspin.d.ts new file mode 100644 index 000000000..08cc353a3 --- /dev/null +++ b/angular-touchspin/angular-touchspin.d.ts @@ -0,0 +1,43 @@ +// Type definitions for Angular Touchspin v1.0.0 +// Project: https://github.com/nkovacic/angular-touchspin +// Definitions by: Niko Kovačič +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +//// + + +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; + } +} \ No newline at end of file diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 8ebfdb6c2..5b9d09d46 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -6,7 +6,15 @@ /// // 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 { diff --git a/angularjs/README.md b/angularjs/README.md index e1256e905..cdd952454 100644 --- a/angularjs/README.md +++ b/angularjs/README.md @@ -1,230 +1,230 @@ -# AngularJS Definitions Usage Notes - -## Referencing AngularJS definition files in your code - -To do that, simply add `/// ` 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: - - /// - /// - -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 -/// -/// - -// We have the option to define arguments for a custom resource -interface IArticleParameters { - id: number; -} - -interface IArticleResource extends ng.resource.IResource { - 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 { - // 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('/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 -/// -/// - -// 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 = $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 = 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 `/// ` 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: + + /// + /// + +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 +/// +/// + +// We have the option to define arguments for a custom resource +interface IArticleParameters { + id: number; +} + +interface IArticleResource extends ng.resource.IResource { + 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 { + // 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('/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 +/// +/// + +// 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 = $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 = articles.get({id: 1}); + + // Again, default + custom action here... + article.title = 'New Title'; + article.$save(); + article.$publish(); + +} +``` diff --git a/angularjs/angular-cookies.d.ts b/angularjs/angular-cookies.d.ts index 25efc42de..3a5f53504 100644 --- a/angularjs/angular-cookies.d.ts +++ b/angularjs/angular-cookies.d.ts @@ -1,91 +1,91 @@ -// Type definitions for Angular JS 1.4 (ngCookies module) -// Project: http://angularjs.org -// Definitions by: Diego Vilar , Anthony Ciccarello -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -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(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 , Anthony Ciccarello +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +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(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; + } + +} diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index d94337273..311388186 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -1,318 +1,318 @@ -// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) -// Project: http://angularjs.org -// Definitions by: Diego Vilar , Tony Curtis -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -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 , Tony Curtis +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +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; diff --git a/angularjs/angular-route-tests.ts b/angularjs/angular-route-tests.ts index 0260359fb..ab5fba0b6 100644 --- a/angularjs/angular-route-tests.ts +++ b/angularjs/angular-route-tests.ts @@ -1,3 +1,4 @@ +/// /// /** @@ -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) => "" }); diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index eafdf714c..ec49b3cd9 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -47,6 +47,7 @@ declare module angular.route { } + type InlineAnnotatedFunction = Function|Array /** * 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. */ diff --git a/angularjs/angular-sanitize.d.ts b/angularjs/angular-sanitize.d.ts index c8ab8e266..d5d541f4e 100644 --- a/angularjs/angular-sanitize.d.ts +++ b/angularjs/angular-sanitize.d.ts @@ -1,40 +1,40 @@ -// Type definitions for Angular JS 1.3 (ngSanitize module) -// Project: http://angularjs.org -// Definitions by: Diego Vilar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -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 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +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; + } + } +} diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 67b3eb488..656e62865 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1685,7 +1685,7 @@ declare module angular { * Controller constructor function that should be associated with newly created scope or the name of a registered * controller if passed as a string. Empty function by default. */ - controller?: string | Function; + controller?: any; /** * An identifier name for a reference to the controller. If present, the controller will be published to scope under * the controllerAs name. If not present, this will default to be the same as the component name. @@ -1715,15 +1715,7 @@ declare module angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean; - /** - * Whether the new scope is isolated. Isolated by default. - */ - isolate?: boolean; - /** - * String of subset of EACM which restricts the component to specific directive declaration style. If omitted, - * this defaults to 'E'. - */ - restrict?: string; + require? : Object; $canActivate?: () => boolean; $routeConfig?: RouteDefinition[]; } @@ -1774,12 +1766,12 @@ declare module angular { name?: string; priority?: number; replace?: boolean; - require?: any; + require? : any; restrict?: string; scope?: any; - template?: any; + template?: string | Function; templateNamespace?: string; - templateUrl?: any; + templateUrl?: string | Function; terminal?: boolean; transclude?: any; } diff --git a/angularjs/legacy/angular-1.0-tests.ts.tscparams b/angularjs/legacy/angular-1.0-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/angularjs/legacy/angular-1.0-tests.ts.tscparams +++ b/angularjs/legacy/angular-1.0-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/angularjs/legacy/angular-scenario-1.0.d.ts.tscparams b/angularjs/legacy/angular-scenario-1.0.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/angularjs/legacy/angular-scenario-1.0.d.ts.tscparams +++ b/angularjs/legacy/angular-scenario-1.0.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/ansicolors/ansicolors.d.ts b/ansicolors/ansicolors.d.ts index 2f61b0435..ec5f0af85 100644 --- a/ansicolors/ansicolors.d.ts +++ b/ansicolors/ansicolors.d.ts @@ -1,9 +1,9 @@ -// Type definitions for ansicolors -// Project: https://github.com/thlorenz/ansicolors -// Definitions by: rogierschouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "ansicolors" { - var colors: {[index: string]: (s: string) => string;}; - export = colors; -} +// Type definitions for ansicolors +// Project: https://github.com/thlorenz/ansicolors +// Definitions by: rogierschouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "ansicolors" { + var colors: {[index: string]: (s: string) => string;}; + export = colors; +} diff --git a/any-db-transaction/any-db-transaction-tests.ts b/any-db-transaction/any-db-transaction-tests.ts index 55ca53bdc..8e38fe5a3 100644 --- a/any-db-transaction/any-db-transaction-tests.ts +++ b/any-db-transaction/any-db-transaction-tests.ts @@ -1,29 +1,29 @@ - -/// -/// - -"use strict"; - -import anyDB = require("any-db"); -import begin = require("any-db-transaction"); - -var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); - - -var transaction = begin(conn); -var transaction2 = begin(transaction); - -begin(conn, { autoRollback: true }); -begin(conn, (error: Error, result: begin.Transaction): void => { -}); - -transaction.query("SELECT * FROM MyTable"); - -transaction.commit(); -transaction.commit((error: Error): void => { -}); - -transaction.rollback(); -transaction.rollback((error: Error): void => { -}); - + +/// +/// + +"use strict"; + +import anyDB = require("any-db"); +import begin = require("any-db-transaction"); + +var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); + + +var transaction = begin(conn); +var transaction2 = begin(transaction); + +begin(conn, { autoRollback: true }); +begin(conn, (error: Error, result: begin.Transaction): void => { +}); + +transaction.query("SELECT * FROM MyTable"); + +transaction.commit(); +transaction.commit((error: Error): void => { +}); + +transaction.rollback(); +transaction.rollback((error: Error): void => { +}); + diff --git a/any-db-transaction/any-db-transaction.d.ts b/any-db-transaction/any-db-transaction.d.ts index ca5bc84b0..8b4bccfaf 100644 --- a/any-db-transaction/any-db-transaction.d.ts +++ b/any-db-transaction/any-db-transaction.d.ts @@ -1,94 +1,94 @@ -// Type definitions for any-db-transaction 2.2.1 -// Project: https://github.com/grncdr/node-any-db-transaction -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module "any-db-transaction" { - import anyDB = require("any-db"); - - module begin { - /** - * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, - * but guarantee that all queries take place within a single database transaction or not at all. Note that - * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you - * can simply pass a pool to it: var tx = begin(pool) - * - * By default, any queries that error during a transaction will cause an automatic rollback. If a query has - * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. - * This enables handling errors for an entire transaction in a single place. - * - * Transactions may also be nested by passing a Transaction to begin and these nested transactions can - * safely error and rollback without rolling back their parent transaction - * - * Transaction events: - * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. - * 'commit:start' - Emitted when .commit() is called. - * 'commit:complete' - Emitted after the transaction has committed. - * 'rollback:start' - Emitted when .rollback() is called. - * 'rollback:complete' - Emitted after the transaction has rolled back. - * 'close' - Emitted after rollback or commit completes. - * 'error', err - Emitted under three conditions: - * There was an error acquiring a connection. - * Any query performed in this transaction emits an error that would otherwise go unhandled. - * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. - * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. - */ - interface Transaction extends anyDB.Queryable { - - /** - * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. - * If a continuation is provided it will be called (possibly with an error) after the COMMIT - * statement completes. The transaction object itself will be unusable after calling commit(). - */ - commit(callback?: (error: Error) => void): void; - - /** - * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. - */ - rollback(callback?: (error: Error) => void): void; - } - - interface TransactionOptions { - /** - * Adapter name e.g. 'mysql' - */ - adapter?: anyDB.Adapter; - /** - * SQL statement for beginning a transaction, default 'BEGIN' - */ - begin?: string; - /** - * SQL statement for committing a transaction, default 'COMMIT' - */ - commit?: string; - /** - * SQL statement for rolling back a transaction, default 'ROLLBACK' - */ - rollback?: string; - /** - * Callback for transaction - */ - callback?: (error: Error, transaction: Transaction) => void; - /** - * Rollback automatically on error, default true - */ - autoRollback?: boolean; - } - } - - /** - * Start a transaction - */ - function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - - export = begin; -} - - - +// Type definitions for any-db-transaction 2.2.1 +// Project: https://github.com/grncdr/node-any-db-transaction +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "any-db-transaction" { + import anyDB = require("any-db"); + + module begin { + /** + * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, + * but guarantee that all queries take place within a single database transaction or not at all. Note that + * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you + * can simply pass a pool to it: var tx = begin(pool) + * + * By default, any queries that error during a transaction will cause an automatic rollback. If a query has + * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. + * This enables handling errors for an entire transaction in a single place. + * + * Transactions may also be nested by passing a Transaction to begin and these nested transactions can + * safely error and rollback without rolling back their parent transaction + * + * Transaction events: + * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. + * 'commit:start' - Emitted when .commit() is called. + * 'commit:complete' - Emitted after the transaction has committed. + * 'rollback:start' - Emitted when .rollback() is called. + * 'rollback:complete' - Emitted after the transaction has rolled back. + * 'close' - Emitted after rollback or commit completes. + * 'error', err - Emitted under three conditions: + * There was an error acquiring a connection. + * Any query performed in this transaction emits an error that would otherwise go unhandled. + * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. + * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. + */ + interface Transaction extends anyDB.Queryable { + + /** + * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. + * If a continuation is provided it will be called (possibly with an error) after the COMMIT + * statement completes. The transaction object itself will be unusable after calling commit(). + */ + commit(callback?: (error: Error) => void): void; + + /** + * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. + */ + rollback(callback?: (error: Error) => void): void; + } + + interface TransactionOptions { + /** + * Adapter name e.g. 'mysql' + */ + adapter?: anyDB.Adapter; + /** + * SQL statement for beginning a transaction, default 'BEGIN' + */ + begin?: string; + /** + * SQL statement for committing a transaction, default 'COMMIT' + */ + commit?: string; + /** + * SQL statement for rolling back a transaction, default 'ROLLBACK' + */ + rollback?: string; + /** + * Callback for transaction + */ + callback?: (error: Error, transaction: Transaction) => void; + /** + * Rollback automatically on error, default true + */ + autoRollback?: boolean; + } + } + + /** + * Start a transaction + */ + function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + + export = begin; +} + + + diff --git a/any-db/any-db-tests.ts b/any-db/any-db-tests.ts index 15dc6c7e6..41744c452 100644 --- a/any-db/any-db-tests.ts +++ b/any-db/any-db-tests.ts @@ -1,38 +1,38 @@ - -/// - -"use strict"; - -import anyDB = require("any-db"); - -var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); -var sql: string = "SELECT * FROM questions"; - -conn.query(sql, [1, "boo"]); - -conn.query(sql).on("data", (row: Object[]): void => { -// nothing -}); - -conn.query(sql, [1, "s"], (error: Error, result: anyDB.ResultSet): void => { - result.rows.length; - result.fields.length; -}); - -conn.end(); - - -var poolConfig: anyDB.PoolConfig = { - min: 1, - max: 200 -}; - -var pool: anyDB.ConnectionPool = anyDB.createPool("mysql://user:password@localhost/testdb", poolConfig); - -pool.query(sql).on("data", (row: Object[]): void => { -// nothing -}); - -pool.close((error: Error): void => { -}); - + +/// + +"use strict"; + +import anyDB = require("any-db"); + +var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); +var sql: string = "SELECT * FROM questions"; + +conn.query(sql, [1, "boo"]); + +conn.query(sql).on("data", (row: Object[]): void => { +// nothing +}); + +conn.query(sql, [1, "s"], (error: Error, result: anyDB.ResultSet): void => { + result.rows.length; + result.fields.length; +}); + +conn.end(); + + +var poolConfig: anyDB.PoolConfig = { + min: 1, + max: 200 +}; + +var pool: anyDB.ConnectionPool = anyDB.createPool("mysql://user:password@localhost/testdb", poolConfig); + +pool.query(sql).on("data", (row: Object[]): void => { +// nothing +}); + +pool.close((error: Error): void => { +}); + diff --git a/any-db/any-db.d.ts b/any-db/any-db.d.ts index f14befb20..8bdd9d706 100644 --- a/any-db/any-db.d.ts +++ b/any-db/any-db.d.ts @@ -1,303 +1,303 @@ -// Type definitions for any-db 2.1.0 -// Project: https://github.com/grncdr/node-any-db -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "any-db" { - import events = require("events"); - import stream = require("stream"); - - export interface ConnectOpts { - adapter: string; - } - - export interface Adapter { - name: string; - /** - * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. - * If a continuation is given, it must be called, either with an error or the established connection. - */ - createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; - - /** - * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, - * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract - * by synchronously returning a Query stream - */ - createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; - createQuery(query: Query): Query; - } - /** - * Other properties are driver specific - */ - export interface Field { - name: string; - } - - /** - * ResultSet objects are just plain data that collect results of a query when a continuation - * is provided to Queryable.query. The lastInsertId is optional, and currently supported by - * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. - */ - export interface ResultSet { - /** - * Affected rows. Note e.g. for INSERT queries the rows property is not filled even - * though rowCount is non-zero. - */ - rowCount: number; - /** - * Result rows - */ - rows: any[]; - /** - * Result field descriptions - */ - fields: Field[]; - - /** - * Not supported by all drivers. - */ - fieldCount?: number; - /** - * Not supported by all drivers. - */ - lastInsertId?: any; - /** - * Not supported by all drivers. - */ - affectedRows?: number; - /** - * Not supported by all drivers. - */ - changedRows?: number; - } - - /** - * Query objects are returned by the Queryable.query method, available on connections, - * pools, and transactions. Queries are instances of Readable, and as such can be piped - * through transforms and support backpressure for more efficient memory-usage on very - * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) - * - * Internally, Query instances are created by a database Adapter and may have more methods, - * properties, and events than are described here. Consult the documentation for your - * specific adapter to find out about any extensions. - * - * Events: - * - * Error event - * The 'error' event is emitted at most once per query. Note that this event will be - * emitted for errors even if a callback was provided, the callback will - * simply be subscribed to the 'error' event. - * One argument is passed to event listeners: - * error - the error object. - * - * Fields event - * A 'fields' event is emmitted before any 'data' events. - * One argument is passed to event listeners: - * fields - an array of [Field][ResultSet] objects. - * - * The following events are part of the stream.Readable interface which is implemented by Query: - * - * Data event - * A 'data' event is emitted for each row in the query result set. - * One argument is passed to event listeners: - * row contains the contents of a single row in the query result - * - * Close event - * A 'close' event is emitted when the query completes. - * No arguments are passed to event listeners. - * - * End event - * An 'end' event is emitted after all query results have been consumed. - * No arguments are passed to event listeners. - */ - export interface Query extends stream.Readable { - /** - * The SQL query as a string. If you are using MySQL this will contain - * interpolated values after the query has been enqueued by a connection. - */ - text: string; - - /** - * The array of parameter values. - */ - values: any[]; - - /** - * The callback (if any) that was provided to Queryable.query. Note that - * Query objects must not use a closed over reference to their callback, - * as other any-db libraries may rely on modifying the callback property - * of a Query they did not create. - */ - callback: (error: Error, results: ResultSet) => void; - } - - /** - * Events: - * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: - * - query: a Query object - */ - export interface Queryable extends events.EventEmitter { - /** - * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. - */ - adapter: Adapter; - - /** - * Execute a SQL statement using bound parameters (if they are provided) and return a Query object - * that is a Readable stream of the resulting rows. If a Continuation is provided the rows - * returned by the database will be aggregated into a [ResultSet][] which will be passed to the - * continuation after the query has completed. - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. - */ - query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query - - /** - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. - */ - // query(query: Query): Query; - } - - /** - * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, - * both of which delegate to the createConnection implementation of the specified adapter. - * While all Connection objects implement the Queryable interface, the implementations in - * each adapter may add additional methods or emit additional events. If you need to access a - * feature of your database that is not described here (such as Postgres' server-side prepared - * statements), consult the documentation for your adapter. - * - * Events: - * Error event - * The 'error' event is emitted when there is a connection-level error. - * No arguments are passed to event listeners. - * - * Open event - * The 'open' event is emitted when the connection has been established and is ready to query. - * No arguments are passed to event listeners. - * - * Close event - * The 'close' event is emitted when the connection has been closed. - * No arguments are passed to event listeners. - */ - export interface Connection extends Queryable { - /** - * Close the database connection. If a continuation is provided it - * will be called after the connection has closed. - */ - end(callback?: (error: Error) => void): void; - } - - export interface ConnectionStatic { - new(): Connection; - - name: string; - createConnection(): void; - createPool(): void; - } - - /** - * ConnectionPool events - * 'acquire' - emitted whenever pool.acquire is called - * 'release' - emitted whenever pool.release is called - * 'query', query - emitted immediately after .query is called on a - * connection via pool.query. The argument is a Query object. - * 'close' - emitted when the connection pool has closed all of it - * connections after a call to close(). - */ - export interface ConnectionPool extends Queryable { - /** - * Implements Queryable.query by automatically acquiring a connection - * and releasing it when the query completes. - */ - query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; - - /** - * Remove a connection from the pool. If you use this method you must - * return the connection back to the pool using ConnectionPool.release - */ - acquire(callback: (error: Error, result: Connection) => void): void; - - /** - * Return a connection to the pool. This should only be called with connections - * you've manually acquired. You must not continue to use the connection after releasing it. - */ - release(connection: Connection): void; - - /** - * Stop giving out new connections, and close all existing database connections as they - * are returned to the pool. - */ - close(callback?: (error: Error) => void): void; - } - - /** - * A PoolConfig is generally a plain object with any of the following properties (they are all optional): - */ - export interface PoolConfig { - /** - * min (default 0) The minimum number of connections to keep open in the pool. - */ - min?: number; - /** - * max (default 10) The maximum number of connections to keep open in the pool. - * When this limit is reached further requests for connections will queue waiting - * for an existing connection to be released back into the pool. - */ - max?: number; - /** - * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped - */ - idleTimeout?: number; - /** - * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. - */ - reapInterval?: number; - /** - * (default true) When this is true, the pool will reap connections that - * have been idle for more than idleTimeout milliseconds. - */ - refreshIdle?: boolean; - /** - * Called immediately after a connection is first established. Use this to do one-time setup of new connections. - * The supplied Connection will not be added to the pool until you pass it to the done continuation. - */ - onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; - /** - * Called each time a connection is returned to the pool. Use this to restore a connection to - * it's original state (e.g. rollback transactions, set the database session vars). If reset - * fails to call the done continuation the connection will be lost in limbo. - */ - reset?: (connection: Connection, done: (error: Error) => void) => void; - /** - * (default function (err) { return true }) - Called when an error is encountered - * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) - * is truthy the connection will be destroyed, otherwise it will be reset. - */ - shouldDestroyConnection?: (error: Error) => boolean; - } - - /** - * Create a database connection. - * @param url String of the form adapter://user:password@host/database - * @param callback - * @returns Connection object. - */ - export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; - - /** - * Create a database connection. - * @param opts Object with adapter name and any properties that the given adapter requires - * @param callback - * @returns Connection object. - */ - export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; - - - export function createPool(url: string, config: PoolConfig): ConnectionPool; - export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; - -} +// Type definitions for any-db 2.1.0 +// Project: https://github.com/grncdr/node-any-db +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "any-db" { + import events = require("events"); + import stream = require("stream"); + + export interface ConnectOpts { + adapter: string; + } + + export interface Adapter { + name: string; + /** + * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. + * If a continuation is given, it must be called, either with an error or the established connection. + */ + createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; + + /** + * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, + * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract + * by synchronously returning a Query stream + */ + createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; + createQuery(query: Query): Query; + } + /** + * Other properties are driver specific + */ + export interface Field { + name: string; + } + + /** + * ResultSet objects are just plain data that collect results of a query when a continuation + * is provided to Queryable.query. The lastInsertId is optional, and currently supported by + * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. + */ + export interface ResultSet { + /** + * Affected rows. Note e.g. for INSERT queries the rows property is not filled even + * though rowCount is non-zero. + */ + rowCount: number; + /** + * Result rows + */ + rows: any[]; + /** + * Result field descriptions + */ + fields: Field[]; + + /** + * Not supported by all drivers. + */ + fieldCount?: number; + /** + * Not supported by all drivers. + */ + lastInsertId?: any; + /** + * Not supported by all drivers. + */ + affectedRows?: number; + /** + * Not supported by all drivers. + */ + changedRows?: number; + } + + /** + * Query objects are returned by the Queryable.query method, available on connections, + * pools, and transactions. Queries are instances of Readable, and as such can be piped + * through transforms and support backpressure for more efficient memory-usage on very + * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) + * + * Internally, Query instances are created by a database Adapter and may have more methods, + * properties, and events than are described here. Consult the documentation for your + * specific adapter to find out about any extensions. + * + * Events: + * + * Error event + * The 'error' event is emitted at most once per query. Note that this event will be + * emitted for errors even if a callback was provided, the callback will + * simply be subscribed to the 'error' event. + * One argument is passed to event listeners: + * error - the error object. + * + * Fields event + * A 'fields' event is emmitted before any 'data' events. + * One argument is passed to event listeners: + * fields - an array of [Field][ResultSet] objects. + * + * The following events are part of the stream.Readable interface which is implemented by Query: + * + * Data event + * A 'data' event is emitted for each row in the query result set. + * One argument is passed to event listeners: + * row contains the contents of a single row in the query result + * + * Close event + * A 'close' event is emitted when the query completes. + * No arguments are passed to event listeners. + * + * End event + * An 'end' event is emitted after all query results have been consumed. + * No arguments are passed to event listeners. + */ + export interface Query extends stream.Readable { + /** + * The SQL query as a string. If you are using MySQL this will contain + * interpolated values after the query has been enqueued by a connection. + */ + text: string; + + /** + * The array of parameter values. + */ + values: any[]; + + /** + * The callback (if any) that was provided to Queryable.query. Note that + * Query objects must not use a closed over reference to their callback, + * as other any-db libraries may rely on modifying the callback property + * of a Query they did not create. + */ + callback: (error: Error, results: ResultSet) => void; + } + + /** + * Events: + * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: + * - query: a Query object + */ + export interface Queryable extends events.EventEmitter { + /** + * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. + */ + adapter: Adapter; + + /** + * Execute a SQL statement using bound parameters (if they are provided) and return a Query object + * that is a Readable stream of the resulting rows. If a Continuation is provided the rows + * returned by the database will be aggregated into a [ResultSet][] which will be passed to the + * continuation after the query has completed. + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query + + /** + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + // query(query: Query): Query; + } + + /** + * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, + * both of which delegate to the createConnection implementation of the specified adapter. + * While all Connection objects implement the Queryable interface, the implementations in + * each adapter may add additional methods or emit additional events. If you need to access a + * feature of your database that is not described here (such as Postgres' server-side prepared + * statements), consult the documentation for your adapter. + * + * Events: + * Error event + * The 'error' event is emitted when there is a connection-level error. + * No arguments are passed to event listeners. + * + * Open event + * The 'open' event is emitted when the connection has been established and is ready to query. + * No arguments are passed to event listeners. + * + * Close event + * The 'close' event is emitted when the connection has been closed. + * No arguments are passed to event listeners. + */ + export interface Connection extends Queryable { + /** + * Close the database connection. If a continuation is provided it + * will be called after the connection has closed. + */ + end(callback?: (error: Error) => void): void; + } + + export interface ConnectionStatic { + new(): Connection; + + name: string; + createConnection(): void; + createPool(): void; + } + + /** + * ConnectionPool events + * 'acquire' - emitted whenever pool.acquire is called + * 'release' - emitted whenever pool.release is called + * 'query', query - emitted immediately after .query is called on a + * connection via pool.query. The argument is a Query object. + * 'close' - emitted when the connection pool has closed all of it + * connections after a call to close(). + */ + export interface ConnectionPool extends Queryable { + /** + * Implements Queryable.query by automatically acquiring a connection + * and releasing it when the query completes. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; + + /** + * Remove a connection from the pool. If you use this method you must + * return the connection back to the pool using ConnectionPool.release + */ + acquire(callback: (error: Error, result: Connection) => void): void; + + /** + * Return a connection to the pool. This should only be called with connections + * you've manually acquired. You must not continue to use the connection after releasing it. + */ + release(connection: Connection): void; + + /** + * Stop giving out new connections, and close all existing database connections as they + * are returned to the pool. + */ + close(callback?: (error: Error) => void): void; + } + + /** + * A PoolConfig is generally a plain object with any of the following properties (they are all optional): + */ + export interface PoolConfig { + /** + * min (default 0) The minimum number of connections to keep open in the pool. + */ + min?: number; + /** + * max (default 10) The maximum number of connections to keep open in the pool. + * When this limit is reached further requests for connections will queue waiting + * for an existing connection to be released back into the pool. + */ + max?: number; + /** + * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped + */ + idleTimeout?: number; + /** + * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. + */ + reapInterval?: number; + /** + * (default true) When this is true, the pool will reap connections that + * have been idle for more than idleTimeout milliseconds. + */ + refreshIdle?: boolean; + /** + * Called immediately after a connection is first established. Use this to do one-time setup of new connections. + * The supplied Connection will not be added to the pool until you pass it to the done continuation. + */ + onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; + /** + * Called each time a connection is returned to the pool. Use this to restore a connection to + * it's original state (e.g. rollback transactions, set the database session vars). If reset + * fails to call the done continuation the connection will be lost in limbo. + */ + reset?: (connection: Connection, done: (error: Error) => void) => void; + /** + * (default function (err) { return true }) - Called when an error is encountered + * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) + * is truthy the connection will be destroyed, otherwise it will be reset. + */ + shouldDestroyConnection?: (error: Error) => boolean; + } + + /** + * Create a database connection. + * @param url String of the form adapter://user:password@host/database + * @param callback + * @returns Connection object. + */ + export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; + + /** + * Create a database connection. + * @param opts Object with adapter name and any properties that the given adapter requires + * @param callback + * @returns Connection object. + */ + export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; + + + export function createPool(url: string, config: PoolConfig): ConnectionPool; + export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; + +} diff --git a/asciify/asciify.ts.tscparams b/asciify/asciify.ts.tscparams index d68b297cb..85542607d 100644 --- a/asciify/asciify.ts.tscparams +++ b/asciify/asciify.ts.tscparams @@ -1 +1 @@ ---noImplicitAny --module commonjs +--noImplicitAny --module commonjs diff --git a/async/async-tests.ts b/async/async-tests.ts index a6dff0af8..037481b6f 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -1,443 +1,443 @@ -/// - -var fs, path; - -function callback() {} - -async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); -async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); -async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { }); - -async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); -async.select(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); - -async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); - -async.parallel([ - function () { }, - function () { } -], callback); - -async.series([ - function () { }, - function () { } -]); - -var data = []; -function asyncProcess(item, callback) { } -async.map(data, asyncProcess, function (err, results) { - console.log(results); -}); - -var openFiles = ['file1', 'file2']; -var openFilesObj = { - file1: "fileOne", - file2: "fileTwo" -} - -var saveFile = function () { } -async.each(openFiles, saveFile, function (err) { }); -async.eachSeries(openFiles, saveFile, function (err) { }); - -var documents, requestApi; -async.eachLimit(documents, 20, requestApi, function (err) { }); - -// forEachOf* functions. May accept array or object. -function forEachOfIterator(item, key, forEachOfIteratorCallback) { - console.log("ForEach: item=" + item + ", key=" + key); - forEachOfIteratorCallback(); -} -async.forEachOf(openFiles, forEachOfIterator, function (err) { }); -async.forEachOf(openFilesObj, forEachOfIterator, function (err) { }); -async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { }); -async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); -async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); -async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); - -var process; -var numArray = [1, 2, 3]; -function reducer(memo, item, callback) { - process.nextTick(function () { - callback(null, memo + item) - }); -} -async.reduce(numArray, 0, reducer, function (err, result) { }); -async.inject(numArray, 0, reducer, function (err, result) { }); -async.foldl(numArray, 0, reducer, function (err, result) { }); -async.reduceRight(numArray, 0, reducer, function (err, result) { }); -async.foldr(numArray, 0, reducer, function (err, result) { }); - -async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); - -async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { - fs.stat(file, function (err, stats) { - callback(err, stats.mtime); - }); -}, function (err, results) { }); - -async.some(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); -async.any(['file1', 'file2', 'file3'], path.exists, function (result) { }); - -async.every(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); -async.all(['file1', 'file2', 'file3'], path.exists, function (result) { }); - -async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); -async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); - - -// Control Flow // - -async.series([ - function (callback) { - callback(null, 'one'); - }, - function (callback) { - callback(null, 'two'); - }, -], -function (err, results) { }); - -async.series([ - function (callback) { - callback(null, 'one'); - }, - function (callback) { - callback(null, 'two'); - }, -], -function (err, results) { }); - -async.series({ - one: function (callback) { - setTimeout(function () { - callback(null, 1); - }, 200); - }, - two: function (callback) { - setTimeout(function () { - callback(null, 2); - }, 100); - }, -}, -function (err, results) { }); - -async.series({ - one: function (callback) { - setTimeout(function () { - callback(null, 1); - }, 200); - }, - two: function (callback) { - setTimeout(function () { - callback(null, 2); - }, 100); - }, -}, -function (err, results) { }); - -async.times(5, function(n, next) { - next(null, n) -}, function(err, results) { - console.log(results) -}) - -async.timesSeries(5, function(n, next) { - next(null, n) -}, function(err, results) { - console.log(results) -}) - -async.parallel([ - function (callback) { - setTimeout(function () { - callback(null, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(null, 'two'); - }, 100); - }, -], -function (err, results) { }); - -async.parallel([ - function (callback) { - setTimeout(function () { - callback(null, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(null, 'two'); - }, 100); - }, -], -function (err, results) { }); - - -async.parallel({ - one: function (callback) { - setTimeout(function () { - callback(null, 1); - }, 200); - }, - two: function (callback) { - setTimeout(function () { - callback(null, 2); - }, 100); - }, -}, -function (err, results) { }); - -async.parallel({ - one: function (callback) { - setTimeout(function () { - callback(null, 1); - }, 200); - }, - two: function (callback) { - setTimeout(function () { - callback(null, 2); - }, 100); - }, -}, - function (err, results) { }); - -async.parallelLimit({ - one: function (callback) { - setTimeout(function () { - callback(null, 1); - }, 200); - }, - two: function (callback) { - setTimeout(function () { - callback(null, 2); - }, 100); - }, -}, - 2, - function (err, results) { } -); - - -function whileFn(callback) { - count++; - setTimeout(callback, 1000); -} - -function whileTest() { return count < 5; } -var count = 0; -async.whilst(whileTest, whileFn, function (err) { }); -async.until(whileTest, whileFn, function (err) { }); -async.doWhilst(whileFn, whileTest, function (err) { }); -async.doUntil(whileFn, whileTest, function (err) { }); - -async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) }); -async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) }); -async.forever(function (errBack) { - errBack(new Error("Not going on forever.")); -}, - function (error) { - console.log(error); - } -); - -async.waterfall([ - function (callback) { - callback(null, 'one', 'two'); - }, - function (arg1, arg2, callback) { - callback(null, 'three'); - }, - function (arg1, callback) { - callback(null, 'done'); - } -], function (err, result) { }); - - -var q = async.queue(function (task: any, callback) { - console.log('hello ' + task.name); - callback(); -}, 2); - - -q.drain = function () { - console.log('all items have been processed'); -} - -q.push({ name: 'foo' }); - -q.push({ name: 'bar' }, function (err) { - console.log('finished processing bar'); -}); - -q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { - console.log('finished processing bar'); -}); - -q.unshift({ name: 'foo' }); - -q.unshift({ name: 'bar' }, function (err) { - console.log('finished processing bar'); -}); - -q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { - console.log('finished processing bar'); -}); - -var qLength : number = q.length(); -var qStarted : boolean = q.started; -var qPaused : boolean = q.paused; -var qProcessingCount : number = q.running(); -var qIsIdle : boolean = q.idle(); - -q.saturated = function() { - console.log('queue is saturated.'); -} - -q.empty = function() { - console.log('queue is empty.'); -} - -q.drain = function() { - console.log('queue was drained.'); -} - -q.pause(); -q.resume(); -q.kill(); - -// tests for strongly typed tasks -var q2 = async.queue(function (task: string, callback) { - console.log('Task: ' + task); - callback(); -}, 1); - -q2.push('task1'); - -q2.push('task2', function (error) { - console.log('Finished tasks'); -}); - -q2.push(['task3', 'task4', 'task5'], function (error) { - console.log('Finished tasks'); -}); - -q2.unshift('task1'); - -q2.unshift('task2', function (error) { - console.log('Finished tasks'); -}); - -q2.unshift(['task3', 'task4', 'task5'], function (error) { - console.log('Finished tasks'); -}); - -// create a cargo object with payload 2 -var cargo = async.cargo(function (tasks, callback) { - for (var i = 0; i < tasks.length; i++) { - console.log('hello ' + tasks[i].name); - } - callback(); -}, 2); - - -// add some items -cargo.push({ name: 'foo' }, function (err) { - console.log('finished processing foo'); -}); -cargo.push({ name: 'bar' }, function (err) { - console.log('finished processing bar'); -}); -cargo.push({ name: 'baz' }, function (err) { - console.log('finished processing baz'); -}); - -var filename = ''; -async.auto({ - get_data: function (callback) { }, - make_folder: function (callback) { }, - //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback) { - callback(null, filename); - }], - //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback, results) { }] -}); - -async.retry(3, function (callback, results) { }, function (err, result) { }); -async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { }); - - -async.parallel([ - function (callback) { }, - function (callback) { } -], -function (results) { - async.series([ - function (callback) { }, - function email_link(callback) { } - ]); -}); - -var sys; -var iterator = async.iterator([ - function () { sys.p('one'); }, - function () { sys.p('two'); }, - function () { sys.p('three'); } -]); - -async.parallel([ - async.apply(fs.writeFile, 'testfile1', 'test1'), - async.apply(fs.writeFile, 'testfile2', 'test2'), -]); - - -async.parallel([ - function (callback) { - fs.writeFile('testfile1', 'test1', callback); - }, - function (callback) { - fs.writeFile('testfile2', 'test2', callback); - }, -]); - -var call_order = []; -async.nextTick(function () { - call_order.push('two'); -}); -call_order.push('one'); - -var slow_fn = function (name, callback) { - callback(null, 123); -}; -var fn = async.memoize(slow_fn); -fn('some name', function () {}); -async.unmemoize(fn); -async.ensureAsync(function () { }); -async.constant(42); -async.asyncify(function () { }); - -async.log(function (name, callback) { - setTimeout(function () { - callback(null, 'hello ' + name); - }, 0); -}, "world" - ); - -async.dir(function (name, callback) { - setTimeout(function () { - callback(null, { hello: name }); - }, 1000); -}, "world"); +/// + +var fs, path; + +function callback() {} + +async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); +async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); +async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { }); + +async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); +async.select(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); + +async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); + +async.parallel([ + function () { }, + function () { } +], callback); + +async.series([ + function () { }, + function () { } +]); + +var data = []; +function asyncProcess(item, callback) { } +async.map(data, asyncProcess, function (err, results) { + console.log(results); +}); + +var openFiles = ['file1', 'file2']; +var openFilesObj = { + file1: "fileOne", + file2: "fileTwo" +} + +var saveFile = function () { } +async.each(openFiles, saveFile, function (err) { }); +async.eachSeries(openFiles, saveFile, function (err) { }); + +var documents, requestApi; +async.eachLimit(documents, 20, requestApi, function (err) { }); + +// forEachOf* functions. May accept array or object. +function forEachOfIterator(item, key, forEachOfIteratorCallback) { + console.log("ForEach: item=" + item + ", key=" + key); + forEachOfIteratorCallback(); +} +async.forEachOf(openFiles, forEachOfIterator, function (err) { }); +async.forEachOf(openFilesObj, forEachOfIterator, function (err) { }); +async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { }); +async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); +async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); +async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); + +var process; +var numArray = [1, 2, 3]; +function reducer(memo, item, callback) { + process.nextTick(function () { + callback(null, memo + item) + }); +} +async.reduce(numArray, 0, reducer, function (err, result) { }); +async.inject(numArray, 0, reducer, function (err, result) { }); +async.foldl(numArray, 0, reducer, function (err, result) { }); +async.reduceRight(numArray, 0, reducer, function (err, result) { }); +async.foldr(numArray, 0, reducer, function (err, result) { }); + +async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); + +async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { + fs.stat(file, function (err, stats) { + callback(err, stats.mtime); + }); +}, function (err, results) { }); + +async.some(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.any(['file1', 'file2', 'file3'], path.exists, function (result) { }); + +async.every(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.all(['file1', 'file2', 'file3'], path.exists, function (result) { }); + +async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); +async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); + + +// Control Flow // + +async.series([ + function (callback) { + callback(null, 'one'); + }, + function (callback) { + callback(null, 'two'); + }, +], +function (err, results) { }); + +async.series([ + function (callback) { + callback(null, 'one'); + }, + function (callback) { + callback(null, 'two'); + }, +], +function (err, results) { }); + +async.series({ + one: function (callback) { + setTimeout(function () { + callback(null, 1); + }, 200); + }, + two: function (callback) { + setTimeout(function () { + callback(null, 2); + }, 100); + }, +}, +function (err, results) { }); + +async.series({ + one: function (callback) { + setTimeout(function () { + callback(null, 1); + }, 200); + }, + two: function (callback) { + setTimeout(function () { + callback(null, 2); + }, 100); + }, +}, +function (err, results) { }); + +async.times(5, function(n, next) { + next(null, n) +}, function(err, results) { + console.log(results) +}) + +async.timesSeries(5, function(n, next) { + next(null, n) +}, function(err, results) { + console.log(results) +}) + +async.parallel([ + function (callback) { + setTimeout(function () { + callback(null, 'one'); + }, 200); + }, + function (callback) { + setTimeout(function () { + callback(null, 'two'); + }, 100); + }, +], +function (err, results) { }); + +async.parallel([ + function (callback) { + setTimeout(function () { + callback(null, 'one'); + }, 200); + }, + function (callback) { + setTimeout(function () { + callback(null, 'two'); + }, 100); + }, +], +function (err, results) { }); + + +async.parallel({ + one: function (callback) { + setTimeout(function () { + callback(null, 1); + }, 200); + }, + two: function (callback) { + setTimeout(function () { + callback(null, 2); + }, 100); + }, +}, +function (err, results) { }); + +async.parallel({ + one: function (callback) { + setTimeout(function () { + callback(null, 1); + }, 200); + }, + two: function (callback) { + setTimeout(function () { + callback(null, 2); + }, 100); + }, +}, + function (err, results) { }); + +async.parallelLimit({ + one: function (callback) { + setTimeout(function () { + callback(null, 1); + }, 200); + }, + two: function (callback) { + setTimeout(function () { + callback(null, 2); + }, 100); + }, +}, + 2, + function (err, results) { } +); + + +function whileFn(callback) { + count++; + setTimeout(callback, 1000); +} + +function whileTest() { return count < 5; } +var count = 0; +async.whilst(whileTest, whileFn, function (err) { }); +async.until(whileTest, whileFn, function (err) { }); +async.doWhilst(whileFn, whileTest, function (err) { }); +async.doUntil(whileFn, whileTest, function (err) { }); + +async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) }); +async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) }); +async.forever(function (errBack) { + errBack(new Error("Not going on forever.")); +}, + function (error) { + console.log(error); + } +); + +async.waterfall([ + function (callback) { + callback(null, 'one', 'two'); + }, + function (arg1, arg2, callback) { + callback(null, 'three'); + }, + function (arg1, callback) { + callback(null, 'done'); + } +], function (err, result) { }); + + +var q = async.queue(function (task: any, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +q.drain = function () { + console.log('all items have been processed'); +} + +q.push({ name: 'foo' }); + +q.push({ name: 'bar' }, function (err) { + console.log('finished processing bar'); +}); + +q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { + console.log('finished processing bar'); +}); + +q.unshift({ name: 'foo' }); + +q.unshift({ name: 'bar' }, function (err) { + console.log('finished processing bar'); +}); + +q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { + console.log('finished processing bar'); +}); + +var qLength : number = q.length(); +var qStarted : boolean = q.started; +var qPaused : boolean = q.paused; +var qProcessingCount : number = q.running(); +var qIsIdle : boolean = q.idle(); + +q.saturated = function() { + console.log('queue is saturated.'); +} + +q.empty = function() { + console.log('queue is empty.'); +} + +q.drain = function() { + console.log('queue was drained.'); +} + +q.pause(); +q.resume(); +q.kill(); + +// tests for strongly typed tasks +var q2 = async.queue(function (task: string, callback) { + console.log('Task: ' + task); + callback(); +}, 1); + +q2.push('task1'); + +q2.push('task2', function (error) { + console.log('Finished tasks'); +}); + +q2.push(['task3', 'task4', 'task5'], function (error) { + console.log('Finished tasks'); +}); + +q2.unshift('task1'); + +q2.unshift('task2', function (error) { + console.log('Finished tasks'); +}); + +q2.unshift(['task3', 'task4', 'task5'], function (error) { + console.log('Finished tasks'); +}); + +// create a cargo object with payload 2 +var cargo = async.cargo(function (tasks, callback) { + for (var i = 0; i < tasks.length; i++) { + console.log('hello ' + tasks[i].name); + } + callback(); +}, 2); + + +// add some items +cargo.push({ name: 'foo' }, function (err) { + console.log('finished processing foo'); +}); +cargo.push({ name: 'bar' }, function (err) { + console.log('finished processing bar'); +}); +cargo.push({ name: 'baz' }, function (err) { + console.log('finished processing baz'); +}); + +var filename = ''; +async.auto({ + get_data: function (callback) { }, + make_folder: function (callback) { }, + //arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', function (callback) { + callback(null, filename); + }], + //arrays with different types are not accepted by TypeScript. + email_link: ['write_file', function (callback, results) { }] +}); + +async.retry(3, function (callback, results) { }, function (err, result) { }); +async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { }); + + +async.parallel([ + function (callback) { }, + function (callback) { } +], +function (results) { + async.series([ + function (callback) { }, + function email_link(callback) { } + ]); +}); + +var sys; +var iterator = async.iterator([ + function () { sys.p('one'); }, + function () { sys.p('two'); }, + function () { sys.p('three'); } +]); + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +async.parallel([ + function (callback) { + fs.writeFile('testfile1', 'test1', callback); + }, + function (callback) { + fs.writeFile('testfile2', 'test2', callback); + }, +]); + +var call_order = []; +async.nextTick(function () { + call_order.push('two'); +}); +call_order.push('one'); + +var slow_fn = function (name, callback) { + callback(null, 123); +}; +var fn = async.memoize(slow_fn); +fn('some name', function () {}); +async.unmemoize(fn); +async.ensureAsync(function () { }); +async.constant(42); +async.asyncify(function () { }); + +async.log(function (name, callback) { + setTimeout(function () { + callback(null, 'hello ' + name); + }, 0); +}, "world" + ); + +async.dir(function (name, callback) { + setTimeout(function () { + callback(null, { hello: name }); + }, 1000); +}, "world"); diff --git a/async/async-tests.ts.tscparams b/async/async-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/async/async-tests.ts.tscparams +++ b/async/async-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/async/async.d.ts b/async/async.d.ts index 418f5539b..543b3751d 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -1,165 +1,165 @@ -// Type definitions for Async 1.4.2 -// Project: https://github.com/caolan/async -// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Dictionary { [key: string]: T; } - -interface ErrorCallback { (err?: Error): void; } -interface AsyncResultCallback { (err: Error, result: T): void; } -interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } -interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } - -interface AsyncFunction { (callback: (err?: Error, result?: T) => void): void; } -interface AsyncIterator { (item: T, callback: ErrorCallback): void; } -interface AsyncForEachOfIterator { (item: T, key: number, callback: ErrorCallback): void; } -interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } -interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } -interface AsyncBooleanIterator { (item: T, callback: (truthValue: boolean) => void): void; } - -interface AsyncWorker { (task: T, callback: ErrorCallback): void; } -interface AsyncVoidFunction { (callback: ErrorCallback): void; } - -interface AsyncQueue { - length(): number; - started: boolean; - running(): number; - idle(): boolean; - concurrency: number; - push(task: T, callback?: ErrorCallback): void; - push(task: T[], callback?: ErrorCallback): void; - unshift(task: T, callback?: ErrorCallback): void; - unshift(task: T[], callback?: ErrorCallback): void; - saturated: () => any; - empty: () => any; - drain: () => any; - paused: boolean; - pause(): void - resume(): void; - kill(): void; -} - -interface AsyncPriorityQueue { - length(): number; - concurrency: number; - started: boolean; - paused: boolean; - push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; - push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; - saturated: () => any; - empty: () => any; - drain: () => any; - running(): number; - idle(): boolean; - pause(): void; - resume(): void; - kill(): void; -} - -interface AsyncCargo { - length(): number; - payload: number; - push(task: any, callback? : Function): void; - push(task: any[], callback? : Function): void; - saturated(): void; - empty(): void; - drain(): void; - idle(): boolean; - pause(): void; - resume(): void; - kill(): void; -} - -interface Async { - - // Collections - each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; - eachSeries(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; - eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; - forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; - forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOfSeries(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; - forEachOfSeries(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; - forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - filter(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - select(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - selectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - selectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - reject(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - rejectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - rejectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - detect(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; - detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; - detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; - sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - all(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - concatSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - - // Control Flow - series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; - series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; - parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; - parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; - whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void; - forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void; - waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void; - compose(...fns: Function[]): void; - seq(...fns: Function[]): void; - applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. - applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. - queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; - priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; - cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; - auto(tasks: any, callback?: (error: Error, results: any) => void): void; - retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; - retry(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; - iterator(tasks: Function[]): Function; - apply(fn: Function, ...arguments: any[]): AsyncFunction; - nextTick(callback: Function): void; - setImmediate(callback: Function): void; - - times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - - // Utils - memoize(fn: Function, hasher?: Function): Function; - unmemoize(fn: Function): Function; - ensureAsync(fn: (... argsAndCallback: any[]) => void): Function; - constant(...values: any[]): Function; - asyncify(fn: Function): Function; - wrapSync(fn: Function): Function; - log(fn: Function, ...arguments: any[]): void; - dir(fn: Function, ...arguments: any[]): void; - noConflict(): Async; -} - -declare var async: Async; - -declare module "async" { - export = async; -} +// Type definitions for Async 1.4.2 +// Project: https://github.com/caolan/async +// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Dictionary { [key: string]: T; } + +interface ErrorCallback { (err?: Error): void; } +interface AsyncResultCallback { (err: Error, result: T): void; } +interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } +interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } + +interface AsyncFunction { (callback: (err?: Error, result?: T) => void): void; } +interface AsyncIterator { (item: T, callback: ErrorCallback): void; } +interface AsyncForEachOfIterator { (item: T, key: number, callback: ErrorCallback): void; } +interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } +interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } +interface AsyncBooleanIterator { (item: T, callback: (truthValue: boolean) => void): void; } + +interface AsyncWorker { (task: T, callback: ErrorCallback): void; } +interface AsyncVoidFunction { (callback: ErrorCallback): void; } + +interface AsyncQueue { + length(): number; + started: boolean; + running(): number; + idle(): boolean; + concurrency: number; + push(task: T, callback?: ErrorCallback): void; + push(task: T[], callback?: ErrorCallback): void; + unshift(task: T, callback?: ErrorCallback): void; + unshift(task: T[], callback?: ErrorCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + paused: boolean; + pause(): void + resume(): void; + kill(): void; +} + +interface AsyncPriorityQueue { + length(): number; + concurrency: number; + started: boolean; + paused: boolean; + push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + running(): number; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; +} + +interface AsyncCargo { + length(): number; + payload: number; + push(task: any, callback? : Function): void; + push(task: any[], callback? : Function): void; + saturated(): void; + empty(): void; + drain(): void; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; +} + +interface Async { + + // Collections + each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + eachSeries(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfSeries(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOfSeries(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + filter(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + select(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + selectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + selectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + reject(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + rejectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + rejectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (results: T[]) => any): any; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + detect(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + all(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + concatSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + + // Control Flow + series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; + series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; + parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; + parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; + whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; + until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; + during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void; + forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void; + waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void; + compose(...fns: Function[]): void; + seq(...fns: Function[]): void; + applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. + applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. + queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; + priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; + cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; + auto(tasks: any, callback?: (error: Error, results: any) => void): void; + retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; + retry(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; + iterator(tasks: Function[]): Function; + apply(fn: Function, ...arguments: any[]): AsyncFunction; + nextTick(callback: Function): void; + setImmediate(callback: Function): void; + + times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + + // Utils + memoize(fn: Function, hasher?: Function): Function; + unmemoize(fn: Function): Function; + ensureAsync(fn: (... argsAndCallback: any[]) => void): Function; + constant(...values: any[]): Function; + asyncify(fn: Function): Function; + wrapSync(fn: Function): Function; + log(fn: Function, ...arguments: any[]): void; + dir(fn: Function, ...arguments: any[]): void; + noConflict(): Async; +} + +declare var async: Async; + +declare module "async" { + export = async; +} diff --git a/async/asyncamd-tests.ts b/async/asyncamd-tests.ts index fc1c25460..3aa8ab92b 100644 --- a/async/asyncamd-tests.ts +++ b/async/asyncamd-tests.ts @@ -1,5 +1,5 @@ -/// - -import async = require("async"); - -async.map(["a", "b", "c"], (item, cb) => cb(null, [item.toUpperCase()]), (err, results) => { }); +/// + +import async = require("async"); + +async.map(["a", "b", "c"], (item, cb) => cb(null, [item.toUpperCase()]), (err, results) => { }); diff --git a/asyncblock/asyncblock.d.ts b/asyncblock/asyncblock.d.ts index ef49640c3..a99eb98a1 100644 --- a/asyncblock/asyncblock.d.ts +++ b/asyncblock/asyncblock.d.ts @@ -1,73 +1,73 @@ -// Type definitions for asyncblock 2.1.23 -// Project: https://github.com/scriby/asyncblock -// Definitions by: Hiroki Horiuchi -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -declare module "asyncblock" { - function asyncblock(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; - - module asyncblock { - export function nostack(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; - - export interface IFlow { - add(responseFormat?: string[]): IExecuteFunction; - add(key: string, responseFormat?: string[]): IExecuteFunction; - add(key: number, responseFormat?: string[]): IExecuteFunction; - add(options: IFlowOptions): IExecuteFunction; - callback(responseFormat?: string[]): IExecuteFunction; - callback(key: string, responseFormat?: string[]): IExecuteFunction; - callback(key: number, responseFormat?: string[]): IExecuteFunction; - callback(options: IFlowOptions): IExecuteFunction; - wait(key?: string): T; - wait(key?: number): T; - - get(key: string): T; - set(key: string, responseFormat?: string[]): IExecuteFunction; - set(options: IFlowOptions): IExecuteFunction; - del(key: string): void; - - sync(task: any): T; - queue(toExecute: IExecuteFunction): void; - queue(key: string, toExecute: IExecuteFunction): void; - queue(key: number, toExecute: IExecuteFunction): void; - queue(responseFormat: string[], toExecute: IExecuteFunction): void; - queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void; - queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void; - queue(options: IFlowOptions, toExecute: IExecuteFunction): void; - doneAdding(): void; - forceWait(): T; - - maxParallel: number; - errorCallback: (err: any) => void; - taskTimeout: number; - timeoutIsError: boolean; - } - - export interface IFlowOptions { - ignoreError?: boolean; // default false - key?: string; // string | number - responseFormat?: string[]; - timeout?: number; - timeoutIsError?: boolean; - dontWait?: boolean; - firstArgIsError?: boolean; // default true - } - - export interface IExecuteFunction { - (err: any, res1: T1, res2: T2, res3: T3): any; - (err: any, res1: T1, res2: T2): any; - (err: any, res: T): any; - (err: any): any; - - // firstArgIsError === false - (res1: T1, res2: T2, res3: T3): any; - (res1: T1, res2: T2): any; - (res: T): any; - } - - } - - export = asyncblock; -} - +// Type definitions for asyncblock 2.1.23 +// Project: https://github.com/scriby/asyncblock +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "asyncblock" { + function asyncblock(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; + + module asyncblock { + export function nostack(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; + + export interface IFlow { + add(responseFormat?: string[]): IExecuteFunction; + add(key: string, responseFormat?: string[]): IExecuteFunction; + add(key: number, responseFormat?: string[]): IExecuteFunction; + add(options: IFlowOptions): IExecuteFunction; + callback(responseFormat?: string[]): IExecuteFunction; + callback(key: string, responseFormat?: string[]): IExecuteFunction; + callback(key: number, responseFormat?: string[]): IExecuteFunction; + callback(options: IFlowOptions): IExecuteFunction; + wait(key?: string): T; + wait(key?: number): T; + + get(key: string): T; + set(key: string, responseFormat?: string[]): IExecuteFunction; + set(options: IFlowOptions): IExecuteFunction; + del(key: string): void; + + sync(task: any): T; + queue(toExecute: IExecuteFunction): void; + queue(key: string, toExecute: IExecuteFunction): void; + queue(key: number, toExecute: IExecuteFunction): void; + queue(responseFormat: string[], toExecute: IExecuteFunction): void; + queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void; + queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void; + queue(options: IFlowOptions, toExecute: IExecuteFunction): void; + doneAdding(): void; + forceWait(): T; + + maxParallel: number; + errorCallback: (err: any) => void; + taskTimeout: number; + timeoutIsError: boolean; + } + + export interface IFlowOptions { + ignoreError?: boolean; // default false + key?: string; // string | number + responseFormat?: string[]; + timeout?: number; + timeoutIsError?: boolean; + dontWait?: boolean; + firstArgIsError?: boolean; // default true + } + + export interface IExecuteFunction { + (err: any, res1: T1, res2: T2, res3: T3): any; + (err: any, res1: T1, res2: T2): any; + (err: any, res: T): any; + (err: any): any; + + // firstArgIsError === false + (res1: T1, res2: T2, res3: T3): any; + (res1: T1, res2: T2): any; + (res: T): any; + } + + } + + export = asyncblock; +} + diff --git a/autolinker/autolinker-tests.ts b/autolinker/autolinker-tests.ts new file mode 100644 index 000000000..c25bedbbc --- /dev/null +++ b/autolinker/autolinker-tests.ts @@ -0,0 +1,153 @@ +/// + +import AutolinkerCJS = require('autolinker'); + +() => { + let linkedText1 = Autolinker.link( "Check out google.com" ); + + new Autolinker(); + let autolinker1 = new Autolinker( { className: "myLink" } ); + let textToAutoLink = 'text'; + let linkedText2 = autolinker1.link( textToAutoLink ); + + let linkedText3 = Autolinker.link( "Check out google.com", { className: "myLink" } ); + let linkedText4 = Autolinker.link( "Check out google.com", { newWindow: false } ); + let linkedText5 = Autolinker.link( "http://www.yahoo.com/some/long/path/to/a/file", { truncate: 25, newWindow: false } ); + let myTextEl = document.getElementById( 'text' ); + myTextEl.innerHTML = Autolinker.link( myTextEl.innerHTML ); + let autolinker2 = new Autolinker( { newWindow: false, truncate: 25 } ); + + autolinker2.link( "Check out http://www.yahoo.com/some/long/path/to/a/file" ); + // Produces: "Check out yahoo.com/some/long/pat.." + + autolinker2.link( "Go to www.google.com" ); + // Produces: "Go to google.com" + + let input = "..."; // string with URLs, Email Addresses, Twitter Handles, and Hashtags + + let linkedText6 = Autolinker.link( input, { + replaceFn : function( autolinker, match ) { + console.log( "href = ", match.getAnchorHref() ); + console.log( "text = ", match.getAnchorText() ); + + switch( match.getType() ) { + case 'url' : + console.log( "url: ", match.getUrl() ); + + if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) { + let tag = autolinker.getTagBuilder().build( match ); // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes + tag.setAttr( 'rel', 'nofollow' ); + tag.addClass( 'external-link' ); + + return tag; + + } else { + return true; // let Autolinker perform its normal anchor tag replacement + } + + case 'email' : + let email = match.getEmail(); + console.log( "email: ", email ); + + if( email === "my@own.address" ) { + return false; // don't auto-link this particular email address; leave as-is + } else { + return; // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`) + } + + case 'phone' : + let phoneNumber = match.getPhoneNumber(); + console.log( phoneNumber ); + + return '' + phoneNumber + ''; + + case 'twitter' : + let twitterHandle = match.getTwitterHandle(); + console.log( twitterHandle ); + + return '' + twitterHandle + ''; + + case 'hashtag' : + let hashtag = match.getHashtag(); + console.log( hashtag ); + + return '' + hashtag + ''; + } + } + } ); +} + +() => { + let linkedText1 = AutolinkerCJS.link( "Check out google.com" ); + + new AutolinkerCJS(); + let autolinker1 = new AutolinkerCJS( { className: "myLink" } ); + let textToAutoLink = 'text'; + let linkedText2 = autolinker1.link( textToAutoLink ); + + let linkedText3 = AutolinkerCJS.link( "Check out google.com", { className: "myLink" } ); + let linkedText4 = AutolinkerCJS.link( "Check out google.com", { newWindow: false } ); + let linkedText5 = AutolinkerCJS.link( "http://www.yahoo.com/some/long/path/to/a/file", { truncate: 25, newWindow: false } ); + let myTextEl = document.getElementById( 'text' ); + myTextEl.innerHTML = AutolinkerCJS.link( myTextEl.innerHTML ); + let autolinker2 = new AutolinkerCJS( { newWindow: false, truncate: 25 } ); + + autolinker2.link( "Check out http://www.yahoo.com/some/long/path/to/a/file" ); + // Produces: "Check out yahoo.com/some/long/pat.." + + autolinker2.link( "Go to www.google.com" ); + // Produces: "Go to google.com" + + let input = "..."; // string with URLs, Email Addresses, Twitter Handles, and Hashtags + + let linkedText6 = AutolinkerCJS.link( input, { + replaceFn : function( autolinker, match ) { + console.log( "href = ", match.getAnchorHref() ); + console.log( "text = ", match.getAnchorText() ); + + switch( match.getType() ) { + case 'url' : + console.log( "url: ", match.getUrl() ); + + if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) { + let tag = autolinker.getTagBuilder().build( match ); // returns an `AutolinkerCJS.HtmlTag` instance, which provides mutator methods for easy changes + tag.setAttr( 'rel', 'nofollow' ); + tag.addClass( 'external-link' ); + + return tag; + + } else { + return true; // let AutolinkerCJS perform its normal anchor tag replacement + } + + case 'email' : + let email = match.getEmail(); + console.log( "email: ", email ); + + if( email === "my@own.address" ) { + return false; // don't auto-link this particular email address; leave as-is + } else { + return; // no return value will have AutolinkerCJS perform its normal anchor tag replacement (same as returning `true`) + } + + case 'phone' : + let phoneNumber = match.getPhoneNumber(); + console.log( phoneNumber ); + + return '' + phoneNumber + ''; + + case 'twitter' : + let twitterHandle = match.getTwitterHandle(); + console.log( twitterHandle ); + + return '' + twitterHandle + ''; + + case 'hashtag' : + let hashtag = match.getHashtag(); + console.log( hashtag ); + + return '' + hashtag + ''; + } + } + } ); +} diff --git a/autolinker/autolinker.d.ts b/autolinker/autolinker.d.ts new file mode 100644 index 000000000..577f670a2 --- /dev/null +++ b/autolinker/autolinker.d.ts @@ -0,0 +1,45 @@ +// Type definitions for autolinker v0.24.0 +// Project: https://github.com/gregjacobs/Autolinker.js +// Definitions by: Leon Yu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace __Autolinker { + interface ConfigOptions { + className?: string; + email?: boolean; + hashtag?: boolean | string; + newWindow?: boolean; + phone?: boolean; + replaceFn?: (autolinker: Autolinker, match: any) => string; + stripPrefix?: boolean; + truncate?: number | { length?: number; location?: string; }; + twitter?: boolean; + urls?: boolean | { schemeMatches: boolean; wwwMatches: boolean; tldMatches: boolean; } + } + + interface Autolinker { + getTagBuilder(): any; + /** + * Automatically links URLs, Email addresses, Phone numbers, Twitter handles, and Hashtags found in the given chunk of HTML. Does not link URLs found within HTML tags. + */ + link(textOrHtml: string): string; + /** + * Parses the input textOrHtml looking for URLs, email addresses, phone numbers, username handles, and hashtags (depending on the configuration of the Autolinker instance), and returns an array of Autolinker.match.Match objects describing those matches. + */ + parse(textOrHtml: string): any[]; + } + + interface Static { + new(cfg?: ConfigOptions): Autolinker; + /** + * Automatically links URLs, Email addresses, Phone Numbers, Twitter handles, and Hashtags found in the given chunk of HTML. Does not link URLs found within HTML tags. + */ + link(textOrHtml: string, options?: ConfigOptions): string + } +} + +declare var Autolinker: __Autolinker.Static; + +declare module "autolinker" { + export = Autolinker; +} diff --git a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts.tscparams b/azure-mobile-services-client/AzureMobileServicesClient-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts.tscparams +++ b/azure-mobile-services-client/AzureMobileServicesClient-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/backbone-relational/backbone-relational-tests.ts.tscparams b/backbone-relational/backbone-relational-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/backbone-relational/backbone-relational-tests.ts.tscparams +++ b/backbone-relational/backbone-relational-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/backbone-relational/backbone-relational.d.ts.tscparams b/backbone-relational/backbone-relational.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/backbone-relational/backbone-relational.d.ts.tscparams +++ b/backbone-relational/backbone-relational.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/backbone/backbone-global.d.ts.tscparams b/backbone/backbone-global.d.ts.tscparams index 7a0dec307..99e26e8cb 100644 --- a/backbone/backbone-global.d.ts.tscparams +++ b/backbone/backbone-global.d.ts.tscparams @@ -1 +1 @@ ---noImplicitAny ./underscore/underscore.d.ts +--noImplicitAny ./underscore/underscore.d.ts diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 506fd7bb6..017546642 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -1,313 +1,313 @@ -/// -/// - -function test_events() { - - var object = new Backbone.Events(); - object.on("alert", (eventName: string) => alert("Triggered " + eventName)); - - object.trigger("alert", "an event"); - - var onChange = () => alert('whatever'); - var context: any; - - object.off("change", onChange); - object.off("change"); - object.off(null, onChange); - object.off(null, null, context); - object.off(); -} - -class SettingDefaults extends Backbone.Model { - - // 'defaults' could be set in one of the following ways: - - defaults() { - return { - name: "Joe" - } - } - - constructor(attributes?: any, options?: any) { - this.defaults = { - name: "Joe" - } - // super has to come last - super(attributes, options); - } - - // or set it like this - initialize() { - this.defaults = { - name: "Joe" - } - - } - - // same patterns could be used for setting 'Router.routes' and 'View.events' -} - -class Sidebar extends Backbone.Model { - - promptColor() { - var cssColor = prompt("Please enter a CSS color:"); - this.set({ color: cssColor }); - } -} - -class Note extends Backbone.Model { - initialize() { } - author() { } - coordinates() { } - allowedToEdit(account: any) { - return true; - } -} - -class PrivateNote extends Note { - allowedToEdit(account: any) { - return account.owns(this); - } - - set(attributes: any, options?: any): Backbone.Model { - return Backbone.Model.prototype.set.call(this, attributes, options); - } -} - -function test_models() { - - var sidebar = new Sidebar(); - sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color })); - sidebar.set({ color: 'white' }); - sidebar.promptColor(); - - ////////// - - var note = new PrivateNote(); - - note.get("title"); - - note.set({ title: "March 20", content: "In his eyes she eclipses..." }); - - note.set("title", "A Scandal in Bohemia"); -} - -class Employee extends Backbone.Model { - reports: EmployeeCollection; - - constructor(attributes?: any, options?: any) { - super(options); - this.reports = new EmployeeCollection(); - this.reports.url = '../api/employees/' + this.id + '/reports'; - } - - more() { - this.reports.reset(); - } -} - -class EmployeeCollection extends Backbone.Collection { - findByName(key: any) { } -} - -class Book extends Backbone.Model { - title: string; - author: string; - published: boolean; -} - -class Library extends Backbone.Collection { - // This model definition is here only to test type compatibility of the model, but it - // is not necessary in working code as it is automatically inferred through generics. - model: typeof Book; -} - -class Books extends Backbone.Collection { } - -function test_collection() { - - var books = new Books(); - - var book1: Book = new Book({ title: "Title 1", author: "Mike" }); - books.add(book1); - - // Objects can be added to collection by casting to model type. - // Compiler will check if object properties are valid for the cast. - // This gives better type checking than declaring an `any` overload. - books.add({ title: "Title 2", author: "Mikey" }); - - var model: Book = book1.collection.first(); - if (model !== book1) { - throw new Error("Error"); - } - - books.each(book => - book.get("title")); - - var titles = books.map(book => - book.get("title")); - - var publishedBooks = books.filter(book => - book.get("published") === true); - - var alphabetical = books.sortBy((book: Book): number => null); -} - -////////// - -Backbone.history.start(); - -module v1Changes { - module events { - function test_once() { - var model = new Employee; - model.once('invalid', () => { }, this); - model.once('invalid', () => { }); - } - - function test_listenTo() { - var model = new Employee; - var view = new Backbone.View(); - view.listenTo(model, 'invalid', () => { }); - } - - function test_listenToOnce() { - var model = new Employee; - var view = new Backbone.View(); - view.listenToOnce(model, 'invalid', () => { }); - } - - function test_stopListening() { - var model = new Employee; - var view = new Backbone.View(); - view.stopListening(model, 'invalid', () => { }); - view.stopListening(model, 'invalid'); - view.stopListening(model); - } - } - - module ModelAndCollection { - function test_url() { - Employee.prototype.url = () => '/employees'; - EmployeeCollection.prototype.url = () => '/employees'; - } - - function test_parse() { - var model = new Employee(); - model.parse('{}', {}); - var collection = new EmployeeCollection; - collection.parse('{}', {}); - } - - function test_toJSON() { - var model = new Employee(); - model.toJSON({}); - var collection = new EmployeeCollection; - collection.toJSON({}); - } - - function test_sync() { - var model = new Employee(); - model.sync(); - var collection = new EmployeeCollection; - collection.sync(); - } - } - - module Model { - function test_validationError() { - var model = new Employee; - if (model.validationError) { - console.log('has validation errors'); - } - } - - function test_fetch() { - var model = new Employee({ id: 1 }); - model.fetch({ - success: () => { }, - error: () => { } - }); - } - - function test_set() { - var model = new Employee; - model.set({ name: 'JoeDoe', age: 21 }, { validate: false }); - model.set('name', 'JoeDoes', { validate: false }); - } - - function test_destroy() { - var model = new Employee; - model.destroy({ - wait: true, - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?, options?) => { } - }); - - model.destroy({ - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?) => { } - }); - - model.destroy({ - success: () => { }, - error: (m?, jqxhr?) => { } - }); - } - - function test_save() { - var model = new Employee; - - model.save({ - name: 'Joe Doe', - age: 21 - }, - { - wait: true, - validate: false, - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?, options?) => { } - }); - - model.save({ - name: 'Joe Doe', - age: 21 - }, - { - success: () => { }, - error: (m?, jqxhr?) => { } - }); - } - - function test_validate() { - var model = new Employee; - - model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false }) - } - } - - module Collection { - function test_fetch() { - var collection = new EmployeeCollection; - collection.fetch({ reset: true }); - } - - function test_create() { - var collection = new EmployeeCollection; - var model = new Employee; - - collection.create(model, { - validate: false - }); - } - } - - module Router { - function test_navigate() { - var router = new Backbone.Router; - - router.navigate('/employees', { trigger: true }); - router.navigate('/employees', true); - } - } -} +/// +/// + +function test_events() { + + var object = new Backbone.Events(); + object.on("alert", (eventName: string) => alert("Triggered " + eventName)); + + object.trigger("alert", "an event"); + + var onChange = () => alert('whatever'); + var context: any; + + object.off("change", onChange); + object.off("change"); + object.off(null, onChange); + object.off(null, null, context); + object.off(); +} + +class SettingDefaults extends Backbone.Model { + + // 'defaults' could be set in one of the following ways: + + defaults() { + return { + name: "Joe" + } + } + + constructor(attributes?: any, options?: any) { + this.defaults = { + name: "Joe" + } + // super has to come last + super(attributes, options); + } + + // or set it like this + initialize() { + this.defaults = { + name: "Joe" + } + + } + + // same patterns could be used for setting 'Router.routes' and 'View.events' +} + +class Sidebar extends Backbone.Model { + + promptColor() { + var cssColor = prompt("Please enter a CSS color:"); + this.set({ color: cssColor }); + } +} + +class Note extends Backbone.Model { + initialize() { } + author() { } + coordinates() { } + allowedToEdit(account: any) { + return true; + } +} + +class PrivateNote extends Note { + allowedToEdit(account: any) { + return account.owns(this); + } + + set(attributes: any, options?: any): Backbone.Model { + return Backbone.Model.prototype.set.call(this, attributes, options); + } +} + +function test_models() { + + var sidebar = new Sidebar(); + sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color })); + sidebar.set({ color: 'white' }); + sidebar.promptColor(); + + ////////// + + var note = new PrivateNote(); + + note.get("title"); + + note.set({ title: "March 20", content: "In his eyes she eclipses..." }); + + note.set("title", "A Scandal in Bohemia"); +} + +class Employee extends Backbone.Model { + reports: EmployeeCollection; + + constructor(attributes?: any, options?: any) { + super(options); + this.reports = new EmployeeCollection(); + this.reports.url = '../api/employees/' + this.id + '/reports'; + } + + more() { + this.reports.reset(); + } +} + +class EmployeeCollection extends Backbone.Collection { + findByName(key: any) { } +} + +class Book extends Backbone.Model { + title: string; + author: string; + published: boolean; +} + +class Library extends Backbone.Collection { + // This model definition is here only to test type compatibility of the model, but it + // is not necessary in working code as it is automatically inferred through generics. + model: typeof Book; +} + +class Books extends Backbone.Collection { } + +function test_collection() { + + var books = new Books(); + + var book1: Book = new Book({ title: "Title 1", author: "Mike" }); + books.add(book1); + + // Objects can be added to collection by casting to model type. + // Compiler will check if object properties are valid for the cast. + // This gives better type checking than declaring an `any` overload. + books.add({ title: "Title 2", author: "Mikey" }); + + var model: Book = book1.collection.first(); + if (model !== book1) { + throw new Error("Error"); + } + + books.each(book => + book.get("title")); + + var titles = books.map(book => + book.get("title")); + + var publishedBooks = books.filter(book => + book.get("published") === true); + + var alphabetical = books.sortBy((book: Book): number => null); +} + +////////// + +Backbone.history.start(); + +module v1Changes { + module events { + function test_once() { + var model = new Employee; + model.once('invalid', () => { }, this); + model.once('invalid', () => { }); + } + + function test_listenTo() { + var model = new Employee; + var view = new Backbone.View(); + view.listenTo(model, 'invalid', () => { }); + } + + function test_listenToOnce() { + var model = new Employee; + var view = new Backbone.View(); + view.listenToOnce(model, 'invalid', () => { }); + } + + function test_stopListening() { + var model = new Employee; + var view = new Backbone.View(); + view.stopListening(model, 'invalid', () => { }); + view.stopListening(model, 'invalid'); + view.stopListening(model); + } + } + + module ModelAndCollection { + function test_url() { + Employee.prototype.url = () => '/employees'; + EmployeeCollection.prototype.url = () => '/employees'; + } + + function test_parse() { + var model = new Employee(); + model.parse('{}', {}); + var collection = new EmployeeCollection; + collection.parse('{}', {}); + } + + function test_toJSON() { + var model = new Employee(); + model.toJSON({}); + var collection = new EmployeeCollection; + collection.toJSON({}); + } + + function test_sync() { + var model = new Employee(); + model.sync(); + var collection = new EmployeeCollection; + collection.sync(); + } + } + + module Model { + function test_validationError() { + var model = new Employee; + if (model.validationError) { + console.log('has validation errors'); + } + } + + function test_fetch() { + var model = new Employee({ id: 1 }); + model.fetch({ + success: () => { }, + error: () => { } + }); + } + + function test_set() { + var model = new Employee; + model.set({ name: 'JoeDoe', age: 21 }, { validate: false }); + model.set('name', 'JoeDoes', { validate: false }); + } + + function test_destroy() { + var model = new Employee; + model.destroy({ + wait: true, + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?, options?) => { } + }); + + model.destroy({ + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?) => { } + }); + + model.destroy({ + success: () => { }, + error: (m?, jqxhr?) => { } + }); + } + + function test_save() { + var model = new Employee; + + model.save({ + name: 'Joe Doe', + age: 21 + }, + { + wait: true, + validate: false, + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?, options?) => { } + }); + + model.save({ + name: 'Joe Doe', + age: 21 + }, + { + success: () => { }, + error: (m?, jqxhr?) => { } + }); + } + + function test_validate() { + var model = new Employee; + + model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false }) + } + } + + module Collection { + function test_fetch() { + var collection = new EmployeeCollection; + collection.fetch({ reset: true }); + } + + function test_create() { + var collection = new EmployeeCollection; + var model = new Employee; + + collection.create(model, { + validate: false + }); + } + } + + module Router { + function test_navigate() { + var router = new Backbone.Router; + + router.navigate('/employees', { trigger: true }); + router.navigate('/employees', true); + } + } +} diff --git a/backbone/backbone-with-lodash-tests.ts b/backbone/backbone-with-lodash-tests.ts index dc7ebd2de..0138b2603 100644 --- a/backbone/backbone-with-lodash-tests.ts +++ b/backbone/backbone-with-lodash-tests.ts @@ -1,314 +1,314 @@ -/// +/// /// -/// - -function test_events() { - - var object = new Backbone.Events(); - object.on("alert", (eventName: string) => alert("Triggered " + eventName)); - - object.trigger("alert", "an event"); - - var onChange = () => alert('whatever'); - var context: any; - - object.off("change", onChange); - object.off("change"); - object.off(null, onChange); - object.off(null, null, context); - object.off(); -} - -class SettingDefaults extends Backbone.Model { - - // 'defaults' could be set in one of the following ways: - - defaults() { - return { - name: "Joe" - } - } - - constructor(attributes?: any, options?: any) { - this.defaults = { - name: "Joe" - } - // super has to come last - super(attributes, options); - } - - // or set it like this - initialize() { - this.defaults = { - name: "Joe" - } - - } - - // same patterns could be used for setting 'Router.routes' and 'View.events' -} - -class Sidebar extends Backbone.Model { - - promptColor() { - var cssColor = prompt("Please enter a CSS color:"); - this.set({ color: cssColor }); - } -} - -class Note extends Backbone.Model { - initialize() { } - author() { } - coordinates() { } - allowedToEdit(account: any) { - return true; - } -} - -class PrivateNote extends Note { - allowedToEdit(account: any) { - return account.owns(this); - } - - set(attributes: any, options?: any): Backbone.Model { - return Backbone.Model.prototype.set.call(this, attributes, options); - } -} - -function test_models() { - - var sidebar = new Sidebar(); - sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color })); - sidebar.set({ color: 'white' }); - sidebar.promptColor(); - - ////////// - - var note = new PrivateNote(); - - note.get("title"); - - note.set({ title: "March 20", content: "In his eyes she eclipses..." }); - - note.set("title", "A Scandal in Bohemia"); -} - -class Employee extends Backbone.Model { - reports: EmployeeCollection; - - constructor(attributes?: any, options?: any) { - super(options); - this.reports = new EmployeeCollection(); - this.reports.url = '../api/employees/' + this.id + '/reports'; - } - - more() { - this.reports.reset(); - } -} - -class EmployeeCollection extends Backbone.Collection { - findByName(key: any) { } -} - -class Book extends Backbone.Model { - title: string; - author: string; - published: boolean; -} - -class Library extends Backbone.Collection { - // This model definition is here only to test type compatibility of the model, but it - // is not necessary in working code as it is automatically inferred through generics. - model: typeof Book; -} - -class Books extends Backbone.Collection { } - -function test_collection() { - - var books = new Books(); - - var book1: Book = new Book({ title: "Title 1", author: "Mike" }); - books.add(book1); - - // Objects can be added to collection by casting to model type. - // Compiler will check if object properties are valid for the cast. - // This gives better type checking than declaring an `any` overload. - books.add({ title: "Title 2", author: "Mikey" }); - - var model: Book = book1.collection.first(); - if (model !== book1) { - throw new Error("Error"); - } - - books.each(book => - book.get("title")); - - var titles = books.map(book => - book.get("title")); - - var publishedBooks = books.filter(book => - book.get("published") === true); - - var alphabetical = books.sortBy((book: Book): number => null); -} - -////////// - -Backbone.history.start(); - -module v1Changes { - module events { - function test_once() { - var model = new Employee; - model.once('invalid', () => { }, this); - model.once('invalid', () => { }); - } - - function test_listenTo() { - var model = new Employee; - var view = new Backbone.View(); - view.listenTo(model, 'invalid', () => { }); - } - - function test_listenToOnce() { - var model = new Employee; - var view = new Backbone.View(); - view.listenToOnce(model, 'invalid', () => { }); - } - - function test_stopListening() { - var model = new Employee; - var view = new Backbone.View(); - view.stopListening(model, 'invalid', () => { }); - view.stopListening(model, 'invalid'); - view.stopListening(model); - } - } - - module ModelAndCollection { - function test_url() { - Employee.prototype.url = () => '/employees'; - EmployeeCollection.prototype.url = () => '/employees'; - } - - function test_parse() { - var model = new Employee(); - model.parse('{}', {}); - var collection = new EmployeeCollection; - collection.parse('{}', {}); - } - - function test_toJSON() { - var model = new Employee(); - model.toJSON({}); - var collection = new EmployeeCollection; - collection.toJSON({}); - } - - function test_sync() { - var model = new Employee(); - model.sync(); - var collection = new EmployeeCollection; - collection.sync(); - } - } - - module Model { - function test_validationError() { - var model = new Employee; - if (model.validationError) { - console.log('has validation errors'); - } - } - - function test_fetch() { - var model = new Employee({ id: 1 }); - model.fetch({ - success: () => { }, - error: () => { } - }); - } - - function test_set() { - var model = new Employee; - model.set({ name: 'JoeDoe', age: 21 }, { validate: false }); - model.set('name', 'JoeDoes', { validate: false }); - } - - function test_destroy() { - var model = new Employee; - model.destroy({ - wait: true, - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?, options?) => { } - }); - - model.destroy({ - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?) => { } - }); - - model.destroy({ - success: () => { }, - error: (m?, jqxhr?) => { } - }); - } - - function test_save() { - var model = new Employee; - - model.save({ - name: 'Joe Doe', - age: 21 - }, - { - wait: true, - validate: false, - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?, options?) => { } - }); - - model.save({ - name: 'Joe Doe', - age: 21 - }, - { - success: () => { }, - error: (m?, jqxhr?) => { } - }); - } - - function test_validate() { - var model = new Employee; - - model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false }) - } - } - - module Collection { - function test_fetch() { - var collection = new EmployeeCollection; - collection.fetch({ reset: true }); - } - - function test_create() { - var collection = new EmployeeCollection; - var model = new Employee; - - collection.create(model, { - validate: false - }); - } - } - - module Router { - function test_navigate() { - var router = new Backbone.Router; - - router.navigate('/employees', { trigger: true }); - router.navigate('/employees', true); - } - } -} +/// + +function test_events() { + + var object = new Backbone.Events(); + object.on("alert", (eventName: string) => alert("Triggered " + eventName)); + + object.trigger("alert", "an event"); + + var onChange = () => alert('whatever'); + var context: any; + + object.off("change", onChange); + object.off("change"); + object.off(null, onChange); + object.off(null, null, context); + object.off(); +} + +class SettingDefaults extends Backbone.Model { + + // 'defaults' could be set in one of the following ways: + + defaults() { + return { + name: "Joe" + } + } + + constructor(attributes?: any, options?: any) { + this.defaults = { + name: "Joe" + } + // super has to come last + super(attributes, options); + } + + // or set it like this + initialize() { + this.defaults = { + name: "Joe" + } + + } + + // same patterns could be used for setting 'Router.routes' and 'View.events' +} + +class Sidebar extends Backbone.Model { + + promptColor() { + var cssColor = prompt("Please enter a CSS color:"); + this.set({ color: cssColor }); + } +} + +class Note extends Backbone.Model { + initialize() { } + author() { } + coordinates() { } + allowedToEdit(account: any) { + return true; + } +} + +class PrivateNote extends Note { + allowedToEdit(account: any) { + return account.owns(this); + } + + set(attributes: any, options?: any): Backbone.Model { + return Backbone.Model.prototype.set.call(this, attributes, options); + } +} + +function test_models() { + + var sidebar = new Sidebar(); + sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color })); + sidebar.set({ color: 'white' }); + sidebar.promptColor(); + + ////////// + + var note = new PrivateNote(); + + note.get("title"); + + note.set({ title: "March 20", content: "In his eyes she eclipses..." }); + + note.set("title", "A Scandal in Bohemia"); +} + +class Employee extends Backbone.Model { + reports: EmployeeCollection; + + constructor(attributes?: any, options?: any) { + super(options); + this.reports = new EmployeeCollection(); + this.reports.url = '../api/employees/' + this.id + '/reports'; + } + + more() { + this.reports.reset(); + } +} + +class EmployeeCollection extends Backbone.Collection { + findByName(key: any) { } +} + +class Book extends Backbone.Model { + title: string; + author: string; + published: boolean; +} + +class Library extends Backbone.Collection { + // This model definition is here only to test type compatibility of the model, but it + // is not necessary in working code as it is automatically inferred through generics. + model: typeof Book; +} + +class Books extends Backbone.Collection { } + +function test_collection() { + + var books = new Books(); + + var book1: Book = new Book({ title: "Title 1", author: "Mike" }); + books.add(book1); + + // Objects can be added to collection by casting to model type. + // Compiler will check if object properties are valid for the cast. + // This gives better type checking than declaring an `any` overload. + books.add({ title: "Title 2", author: "Mikey" }); + + var model: Book = book1.collection.first(); + if (model !== book1) { + throw new Error("Error"); + } + + books.each(book => + book.get("title")); + + var titles = books.map(book => + book.get("title")); + + var publishedBooks = books.filter(book => + book.get("published") === true); + + var alphabetical = books.sortBy((book: Book): number => null); +} + +////////// + +Backbone.history.start(); + +module v1Changes { + module events { + function test_once() { + var model = new Employee; + model.once('invalid', () => { }, this); + model.once('invalid', () => { }); + } + + function test_listenTo() { + var model = new Employee; + var view = new Backbone.View(); + view.listenTo(model, 'invalid', () => { }); + } + + function test_listenToOnce() { + var model = new Employee; + var view = new Backbone.View(); + view.listenToOnce(model, 'invalid', () => { }); + } + + function test_stopListening() { + var model = new Employee; + var view = new Backbone.View(); + view.stopListening(model, 'invalid', () => { }); + view.stopListening(model, 'invalid'); + view.stopListening(model); + } + } + + module ModelAndCollection { + function test_url() { + Employee.prototype.url = () => '/employees'; + EmployeeCollection.prototype.url = () => '/employees'; + } + + function test_parse() { + var model = new Employee(); + model.parse('{}', {}); + var collection = new EmployeeCollection; + collection.parse('{}', {}); + } + + function test_toJSON() { + var model = new Employee(); + model.toJSON({}); + var collection = new EmployeeCollection; + collection.toJSON({}); + } + + function test_sync() { + var model = new Employee(); + model.sync(); + var collection = new EmployeeCollection; + collection.sync(); + } + } + + module Model { + function test_validationError() { + var model = new Employee; + if (model.validationError) { + console.log('has validation errors'); + } + } + + function test_fetch() { + var model = new Employee({ id: 1 }); + model.fetch({ + success: () => { }, + error: () => { } + }); + } + + function test_set() { + var model = new Employee; + model.set({ name: 'JoeDoe', age: 21 }, { validate: false }); + model.set('name', 'JoeDoes', { validate: false }); + } + + function test_destroy() { + var model = new Employee; + model.destroy({ + wait: true, + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?, options?) => { } + }); + + model.destroy({ + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?) => { } + }); + + model.destroy({ + success: () => { }, + error: (m?, jqxhr?) => { } + }); + } + + function test_save() { + var model = new Employee; + + model.save({ + name: 'Joe Doe', + age: 21 + }, + { + wait: true, + validate: false, + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?, options?) => { } + }); + + model.save({ + name: 'Joe Doe', + age: 21 + }, + { + success: () => { }, + error: (m?, jqxhr?) => { } + }); + } + + function test_validate() { + var model = new Employee; + + model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false }) + } + } + + module Collection { + function test_fetch() { + var collection = new EmployeeCollection; + collection.fetch({ reset: true }); + } + + function test_create() { + var collection = new EmployeeCollection; + var model = new Employee; + + collection.create(model, { + validate: false + }); + } + } + + module Router { + function test_navigate() { + var router = new Backbone.Router; + + router.navigate('/employees', { trigger: true }); + router.navigate('/employees', true); + } + } +} diff --git a/backgrid/backgrid-tests.ts.tscparams b/backgrid/backgrid-tests.ts.tscparams index d45eb7650..3af0fcfed 100644 --- a/backgrid/backgrid-tests.ts.tscparams +++ b/backgrid/backgrid-tests.ts.tscparams @@ -1 +1 @@ ---target ES5 +--target ES5 diff --git a/backgrid/backgrid.d.ts.tscparams b/backgrid/backgrid.d.ts.tscparams index aa5e71c8a..5d4a276bc 100644 --- a/backgrid/backgrid.d.ts.tscparams +++ b/backgrid/backgrid.d.ts.tscparams @@ -1 +1 @@ ---target es5 +--target es5 diff --git a/bitwise-xor/bitwise-xor-tests.ts b/bitwise-xor/bitwise-xor-tests.ts index 66b67a7b5..e55670b85 100644 --- a/bitwise-xor/bitwise-xor-tests.ts +++ b/bitwise-xor/bitwise-xor-tests.ts @@ -1,11 +1,11 @@ - -/// - -"use strict"; - -import xor = require("bitwise-xor"); - -var b: Buffer; - -b = xor("a", "b"); -b = xor(new Buffer("a"), new Buffer("b")); + +/// + +"use strict"; + +import xor = require("bitwise-xor"); + +var b: Buffer; + +b = xor("a", "b"); +b = xor(new Buffer("a"), new Buffer("b")); diff --git a/bitwise-xor/bitwise-xor.d.ts b/bitwise-xor/bitwise-xor.d.ts index 0db872f91..1ea6865c7 100644 --- a/bitwise-xor/bitwise-xor.d.ts +++ b/bitwise-xor/bitwise-xor.d.ts @@ -1,17 +1,17 @@ // Type definitions for bitwise-xor 0.0.0 // Project: https://github.com/czzarr/node-bitwise-xor // Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// -declare module "bitwise-xor" { - - /** - * Bitwise XOR between two Buffers or Strings, returns a Buffer - */ - function xor(b1: Buffer, b2: Buffer): Buffer; - function xor(s1: string, s2: string): Buffer; - - export = xor; -} - +declare module "bitwise-xor" { + + /** + * Bitwise XOR between two Buffers or Strings, returns a Buffer + */ + function xor(b1: Buffer, b2: Buffer): Buffer; + function xor(s1: string, s2: string): Buffer; + + export = xor; +} + diff --git a/bootbox/bootbox-tests.ts b/bootbox/bootbox-tests.ts index 463170cd7..5b3a26edd 100644 --- a/bootbox/bootbox-tests.ts +++ b/bootbox/bootbox-tests.ts @@ -1,106 +1,106 @@ -// QUnit Tests for Bootbox 4.4.0 -/// - -bootbox.alert("Are we ok?"); -bootbox.alert("Are we ok with callback?", function () { - console.log("Callback called!"); -}); -bootbox.alert({ - size: "medium", - message: "Are we ok with callback and custom button?", - callback: function () { - console.log("Callback called!"); - } -}); - -bootbox.confirm("Click cancel to pass test", function (result) { - console.log(!result); -}); -bootbox.confirm({ - message: "Click confirm to pass test", - callback: function (result) { - console.log(result); - } -}); - -bootbox.prompt("Enter 'ok' to pass test", function (result) { - console.log(result); -}); -bootbox.prompt({ - message: "Enter 'ok' to pass test", callback: function (result) { - console.log(result); - } -}); -bootbox.prompt({ - size: "large", - message: "Enter 'ok' to pass test", callback: function (result) { - console.log(result); - } -}); - - -bootbox.dialog({ - title: "Wassup?", - message: "Test Dialog", - callback: function (result) { } -}); - -// Testing the return object of the call. Using the pointer to disable the animation on success callback. -var bBox : JQuery; - -bBox = bootbox.dialog({ - message: "Test Dialog", - buttons: { - cancel: { - label: "Cancel" - }, - confirm: { - label: "Continue", - callback: function () { - bBox.removeClass("fade"); - console.log("Outer callback."); - } - } - }, - animate: true, -}); - -var bdo: BootboxDialogOptions; -var sampleButton: BootboxButton = { - label: 'ButtonLabelToUse', - callback: function () { - return 'callback of button click' - }, - className: 'additionalButtonClassName' -}; - -bdo = { - message: '', - className: 'callName', - buttons: { - 'ButtonTextLabel': sampleButton - } -}; - -bootbox.dialog(bdo); - -bootbox.setDefaults({ - locale: 'en_US', - animate: false, - backdrop: false, - className: 'newClassName', - closeButton: true, - show: true -}) - -bootbox.hideAll(); - -var localeOptions: BootboxLocaleValues = { - OK: 'Hus', - CANCEL: 'Nai', - CONFIRM: 'Pakka' -} - -bootbox.addLocale("Nepali", localeOptions); -bootbox.setLocale("Nepali"); +// QUnit Tests for Bootbox 4.4.0 +/// + +bootbox.alert("Are we ok?"); +bootbox.alert("Are we ok with callback?", function () { + console.log("Callback called!"); +}); +bootbox.alert({ + size: "medium", + message: "Are we ok with callback and custom button?", + callback: function () { + console.log("Callback called!"); + } +}); + +bootbox.confirm("Click cancel to pass test", function (result) { + console.log(!result); +}); +bootbox.confirm({ + message: "Click confirm to pass test", + callback: function (result) { + console.log(result); + } +}); + +bootbox.prompt("Enter 'ok' to pass test", function (result) { + console.log(result); +}); +bootbox.prompt({ + message: "Enter 'ok' to pass test", callback: function (result) { + console.log(result); + } +}); +bootbox.prompt({ + size: "large", + message: "Enter 'ok' to pass test", callback: function (result) { + console.log(result); + } +}); + + +bootbox.dialog({ + title: "Wassup?", + message: "Test Dialog", + callback: function (result) { } +}); + +// Testing the return object of the call. Using the pointer to disable the animation on success callback. +var bBox : JQuery; + +bBox = bootbox.dialog({ + message: "Test Dialog", + buttons: { + cancel: { + label: "Cancel" + }, + confirm: { + label: "Continue", + callback: function () { + bBox.removeClass("fade"); + console.log("Outer callback."); + } + } + }, + animate: true, +}); + +var bdo: BootboxDialogOptions; +var sampleButton: BootboxButton = { + label: 'ButtonLabelToUse', + callback: function () { + return 'callback of button click' + }, + className: 'additionalButtonClassName' +}; + +bdo = { + message: '', + className: 'callName', + buttons: { + 'ButtonTextLabel': sampleButton + } +}; + +bootbox.dialog(bdo); + +bootbox.setDefaults({ + locale: 'en_US', + animate: false, + backdrop: false, + className: 'newClassName', + closeButton: true, + show: true +}) + +bootbox.hideAll(); + +var localeOptions: BootboxLocaleValues = { + OK: 'Hus', + CANCEL: 'Nai', + CONFIRM: 'Pakka' +} + +bootbox.addLocale("Nepali", localeOptions); +bootbox.setLocale("Nepali"); bootbox.removeLocale("Nepali"); \ No newline at end of file diff --git a/bootbox/bootbox.d.ts b/bootbox/bootbox.d.ts index 5ec2a7abd..7e0ed9b40 100644 --- a/bootbox/bootbox.d.ts +++ b/bootbox/bootbox.d.ts @@ -1,82 +1,82 @@ -// Type definitions for Bootbox 4.4.0 -// Project: https://github.com/makeusabrew/bootbox -// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -interface BootboxAlertOptions { - size?: string; - message: string; - callback?: () => any; -} - -interface BootboxConfirmOptions { - size?: string; - message: string; - callback: (result: boolean) => any; -} - -interface BootboxPromptOptions { - size?: string; - message?: string; - callback: (result: string) => any; -} - -interface BootboxButton { - label?: string; - className?: string; - callback?: () => any; -} - -interface BootboxButtonMap { - [key: string]: BootboxButton | Function; -} - -interface BootboxDialogOptions { - message: string | Element; - title?: string | Element; - locale?: string; - callback?: (result: boolean) => any; - onEscape?: () => any | boolean; - show?: boolean; - backdrop?: boolean; - closeButton?: boolean; - animate?: boolean; - className?: string; - size?: string; - buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton -} - -interface BootboxDefaultOptions { - locale?: string; - show?: boolean; - backdrop?: boolean; - closeButton?: boolean; - animate?: boolean; - className?: string; -} - -interface BootboxLocaleValues { - OK: string; - CANCEL: string; - CONFIRM: string; -} - -interface BootboxStatic { - alert(message: string, callback?: () => void): JQuery; - alert(options: BootboxAlertOptions): JQuery; - confirm(message: string, callback: (result: boolean) => void): JQuery; - confirm(options: BootboxConfirmOptions): JQuery; - prompt(message: string, callback: (result: string) => void): JQuery; - prompt(options: BootboxPromptOptions): JQuery; - dialog(message: string, callback?: (result: string) => void): JQuery; - dialog(options: BootboxDialogOptions): JQuery; - setDefaults(options: BootboxDefaultOptions): void; - hideAll(): void; - - addLocale(name: string, values: BootboxLocaleValues): void; - removeLocale(name: string): void; - setLocale(name: string): void; -} - -declare var bootbox: BootboxStatic; +// Type definitions for Bootbox 4.4.0 +// Project: https://github.com/makeusabrew/bootbox +// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +interface BootboxAlertOptions { + size?: string; + message: string; + callback?: () => any; +} + +interface BootboxConfirmOptions { + size?: string; + message: string; + callback: (result: boolean) => any; +} + +interface BootboxPromptOptions { + size?: string; + message?: string; + callback: (result: string) => any; +} + +interface BootboxButton { + label?: string; + className?: string; + callback?: () => any; +} + +interface BootboxButtonMap { + [key: string]: BootboxButton | Function; +} + +interface BootboxDialogOptions { + message: string | Element; + title?: string | Element; + locale?: string; + callback?: (result: boolean) => any; + onEscape?: () => any | boolean; + show?: boolean; + backdrop?: boolean; + closeButton?: boolean; + animate?: boolean; + className?: string; + size?: string; + buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton +} + +interface BootboxDefaultOptions { + locale?: string; + show?: boolean; + backdrop?: boolean; + closeButton?: boolean; + animate?: boolean; + className?: string; +} + +interface BootboxLocaleValues { + OK: string; + CANCEL: string; + CONFIRM: string; +} + +interface BootboxStatic { + alert(message: string, callback?: () => void): JQuery; + alert(options: BootboxAlertOptions): JQuery; + confirm(message: string, callback: (result: boolean) => void): JQuery; + confirm(options: BootboxConfirmOptions): JQuery; + prompt(message: string, callback: (result: string) => void): JQuery; + prompt(options: BootboxPromptOptions): JQuery; + dialog(message: string, callback?: (result: string) => void): JQuery; + dialog(options: BootboxDialogOptions): JQuery; + setDefaults(options: BootboxDefaultOptions): void; + hideAll(): void; + + addLocale(name: string, values: BootboxLocaleValues): void; + removeLocale(name: string): void; + setLocale(name: string): void; +} + +declare var bootbox: BootboxStatic; diff --git a/bootstrap.datepicker/bootstrap.datepicker-tests.ts b/bootstrap.datepicker/bootstrap.datepicker-tests.ts index 0bbf2c650..b275ee25a 100644 --- a/bootstrap.datepicker/bootstrap.datepicker-tests.ts +++ b/bootstrap.datepicker/bootstrap.datepicker-tests.ts @@ -1,82 +1,82 @@ -/// - -function tests_simple() { - $('#datepicker').datepicker(); - $('#datepicker').datepicker({ - format: 'mm-dd-yyyy' - }); - $('#datepicker').datepicker('setStartDate'); - $('#datepicker').datepicker('setStartDate', null); - $('#datepicker').datepicker('setEndDate', '2012-12-31'); - $('#date-end') - .datepicker() - .on('changeDate', function (ev) { ev; }); - - var startDate = new Date(2012, 1, 20); - var endDate = new Date(2012, 1, 25); - $('#date-start') - .datepicker() - //.on("changeDate", function (ev) { // bug https://typescript.codeplex.com/workitem/1976 - .on("changeDate", function (ev: DatepickerEventObject) { - if (ev.date.valueOf() > endDate.valueOf()) { - $('#alert').show().find('strong').text('The start date must be before the end date.'); - } else { - $('#alert').hide(); - startDate = ev.date; - $('#date-start-display').text($('#date-start').data('date')); - } - $('#date-start').datepicker('hide'); - }); - $('#date-end') - .datepicker() - //.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976 - .on('changeDate', function (ev: DatepickerEventObject) { - if (ev.date.valueOf() < startDate.valueOf()) { - $('#alert').show().find('strong').text('The end date must be after the start date.'); - } else { - $('#alert').hide(); - endDate = ev.date; - $('#date-end-display').text($('#date-end').data('date')); - } - $('#date-end').datepicker('hide'); - }); -} - -$(function () { - $('#dp1').datepicker({ - format: 'mm-dd-yyyy' - }); - $('#dp2').datepicker(); - $('#dp3').datepicker(); - $('#dp3').datepicker(); - $('#dpYears').datepicker(); - $('#dpMonths').datepicker(); - - - var startDate = new Date(2012, 1, 20); - var endDate = new Date(2012, 1, 25); - $('#dp4').datepicker() - //.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976 - .on('changeDate', function (ev: DatepickerEventObject) { - if (ev.date.valueOf() > endDate.valueOf()) { - $('#alert').show().find('strong').text('The start date can not be greater then the end date'); - } else { - $('#alert').hide(); - startDate = ev.date; - $('#startDate').text($('#dp4').data('date')); - } - $('#dp4').datepicker('hide'); - }); - $('#dp5').datepicker() - //.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976 - .on('changeDate', function (ev: DatepickerEventObject) { - if (ev.date.valueOf() < startDate.valueOf()) { - $('#alert').show().find('strong').text('The end date can not be less then the start date'); - } else { - $('#alert').hide(); - endDate = ev.date; - $('#endDate').text($('#dp5').data('date')); - } - $('#dp5').datepicker('hide'); - }); -}); +/// + +function tests_simple() { + $('#datepicker').datepicker(); + $('#datepicker').datepicker({ + format: 'mm-dd-yyyy' + }); + $('#datepicker').datepicker('setStartDate'); + $('#datepicker').datepicker('setStartDate', null); + $('#datepicker').datepicker('setEndDate', '2012-12-31'); + $('#date-end') + .datepicker() + .on('changeDate', function (ev) { ev; }); + + var startDate = new Date(2012, 1, 20); + var endDate = new Date(2012, 1, 25); + $('#date-start') + .datepicker() + //.on("changeDate", function (ev) { // bug https://typescript.codeplex.com/workitem/1976 + .on("changeDate", function (ev: DatepickerEventObject) { + if (ev.date.valueOf() > endDate.valueOf()) { + $('#alert').show().find('strong').text('The start date must be before the end date.'); + } else { + $('#alert').hide(); + startDate = ev.date; + $('#date-start-display').text($('#date-start').data('date')); + } + $('#date-start').datepicker('hide'); + }); + $('#date-end') + .datepicker() + //.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976 + .on('changeDate', function (ev: DatepickerEventObject) { + if (ev.date.valueOf() < startDate.valueOf()) { + $('#alert').show().find('strong').text('The end date must be after the start date.'); + } else { + $('#alert').hide(); + endDate = ev.date; + $('#date-end-display').text($('#date-end').data('date')); + } + $('#date-end').datepicker('hide'); + }); +} + +$(function () { + $('#dp1').datepicker({ + format: 'mm-dd-yyyy' + }); + $('#dp2').datepicker(); + $('#dp3').datepicker(); + $('#dp3').datepicker(); + $('#dpYears').datepicker(); + $('#dpMonths').datepicker(); + + + var startDate = new Date(2012, 1, 20); + var endDate = new Date(2012, 1, 25); + $('#dp4').datepicker() + //.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976 + .on('changeDate', function (ev: DatepickerEventObject) { + if (ev.date.valueOf() > endDate.valueOf()) { + $('#alert').show().find('strong').text('The start date can not be greater then the end date'); + } else { + $('#alert').hide(); + startDate = ev.date; + $('#startDate').text($('#dp4').data('date')); + } + $('#dp4').datepicker('hide'); + }); + $('#dp5').datepicker() + //.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976 + .on('changeDate', function (ev: DatepickerEventObject) { + if (ev.date.valueOf() < startDate.valueOf()) { + $('#alert').show().find('strong').text('The end date can not be less then the start date'); + } else { + $('#alert').hide(); + endDate = ev.date; + $('#endDate').text($('#dp5').data('date')); + } + $('#dp5').datepicker('hide'); + }); +}); diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts index 23f51cb43..e9ca0159d 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap.datepicker/bootstrap.datepicker.d.ts @@ -1,57 +1,57 @@ -// Type definitions for bootstrap.datepicker -// Project: https://github.com/eternicode/bootstrap-datepicker -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -/** - * All options that take a “Date” can handle a Date object; a String - * formatted according to the given format; or a timedelta relative - * to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day), - * “w” (week), “m” (month), and “y” (year). - * - * See online docs for more info: - * http://bootstrap-datepicker.readthedocs.org/en/release/options.html - */ -interface DatepickerOptions { - format?: string; - weekStart?: number; - startDate?: any; - endDate?: any; - autoclose?: boolean; - startView?: number; - todayBtn?: any; - todayHighlight?: boolean; - keyboardNavigation?: boolean; - language?: string; - beforeShowDay?: (date: any) => any; - calendarWeeks?: boolean; - clearBtn?: boolean; - daysOfWeekDisabled?: number[]; - forceParse?: boolean; - inputs?: any[]; - minViewMode?: any; - multidate?: any; - multidateSeparator?: string; - orientation?: string; -} - -interface DatepickerEventObject extends JQueryEventObject { - date: Date; - format(format?: string): string; -} - -interface JQuery { - datepicker(): JQuery; - datepicker(methodName: string): any; - datepicker(methodName: string, params: any): any; - datepicker(options: DatepickerOptions): JQuery; - - off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery; - off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery; - - on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery; - on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery; - on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery; -} +// Type definitions for bootstrap.datepicker +// Project: https://github.com/eternicode/bootstrap-datepicker +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * All options that take a “Date” can handle a Date object; a String + * formatted according to the given format; or a timedelta relative + * to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day), + * “w” (week), “m” (month), and “y” (year). + * + * See online docs for more info: + * http://bootstrap-datepicker.readthedocs.org/en/release/options.html + */ +interface DatepickerOptions { + format?: string; + weekStart?: number; + startDate?: any; + endDate?: any; + autoclose?: boolean; + startView?: number; + todayBtn?: any; + todayHighlight?: boolean; + keyboardNavigation?: boolean; + language?: string; + beforeShowDay?: (date: any) => any; + calendarWeeks?: boolean; + clearBtn?: boolean; + daysOfWeekDisabled?: number[]; + forceParse?: boolean; + inputs?: any[]; + minViewMode?: any; + multidate?: any; + multidateSeparator?: string; + orientation?: string; +} + +interface DatepickerEventObject extends JQueryEventObject { + date: Date; + format(format?: string): string; +} + +interface JQuery { + datepicker(): JQuery; + datepicker(methodName: string): any; + datepicker(methodName: string, params: any): any; + datepicker(options: DatepickerOptions): JQuery; + + off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery; + off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery; + + on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery; + on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery; + on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery; +} diff --git a/bootstrap.paginator/bootstrap.paginator.d.ts.tscparams b/bootstrap.paginator/bootstrap.paginator.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/bootstrap.paginator/bootstrap.paginator.d.ts.tscparams +++ b/bootstrap.paginator/bootstrap.paginator.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/bootstrap/bootstrap-tests.ts b/bootstrap/bootstrap-tests.ts index fa4409fe3..c497e0abc 100644 --- a/bootstrap/bootstrap-tests.ts +++ b/bootstrap/bootstrap-tests.ts @@ -1,46 +1,46 @@ -/// -/// - -$('body').off('.data-api'); -$('body').off('.alert.data-api'); - -$(".btn.danger").button("toggle").addClass("fat"); -$("#myModal").modal(); -$("#myModal").modal({ keyboard: false }); -$("#myModal").modal('show'); - -$('#myModal').on('show', (e) => e.preventDefault()); - -$('#myModal').modal({ keyboard: false }); -$('#myModal').modal('toggle'); - -$('.dropdown-toggle').dropdown(); - -$('#navbar').scrollspy(); -$('body').scrollspy({ target: '#navbar-example' }); - -$('#element').tooltip('show'); - -$('#element').popover('show'); - -$(".alert").alert(); -$(".alert").alert('close'); - -$('.nav-tabs').button(); -$().button('toggle'); - -$(".collapse").collapse(); - -$('#myCollapsible').collapse({ toggle: false }); - -$('.carousel').carousel(); -$('.carousel').carousel({ interval: 2000 }); - -$('.typeahead').typeahead({ - matcher: item => true, - sorter: (items: any[]) => items, - updater: item => item, - highlighter: item => "" -}); - -$('#navbar').affix(); +/// +/// + +$('body').off('.data-api'); +$('body').off('.alert.data-api'); + +$(".btn.danger").button("toggle").addClass("fat"); +$("#myModal").modal(); +$("#myModal").modal({ keyboard: false }); +$("#myModal").modal('show'); + +$('#myModal').on('show', (e) => e.preventDefault()); + +$('#myModal').modal({ keyboard: false }); +$('#myModal').modal('toggle'); + +$('.dropdown-toggle').dropdown(); + +$('#navbar').scrollspy(); +$('body').scrollspy({ target: '#navbar-example' }); + +$('#element').tooltip('show'); + +$('#element').popover('show'); + +$(".alert").alert(); +$(".alert").alert('close'); + +$('.nav-tabs').button(); +$().button('toggle'); + +$(".collapse").collapse(); + +$('#myCollapsible').collapse({ toggle: false }); + +$('.carousel').carousel(); +$('.carousel').carousel({ interval: 2000 }); + +$('.typeahead').typeahead({ + matcher: item => true, + sorter: (items: any[]) => items, + updater: item => item, + highlighter: item => "" +}); + +$('#navbar').affix(); diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts index 491eb3045..8037cad6c 100644 --- a/bootstrap/bootstrap.d.ts +++ b/bootstrap/bootstrap.d.ts @@ -1,120 +1,120 @@ -// Type definitions for Bootstrap 3.3.5 -// Project: http://twitter.github.com/bootstrap/ -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -interface ModalOptions { - backdrop?: boolean|string; - keyboard?: boolean; - show?: boolean; - remote?: string; -} - -interface ModalOptionsBackdropString { - backdrop?: string; // for "static" - keyboard?: boolean; - show?: boolean; - remote?: string; -} - -interface ScrollSpyOptions { - offset?: number; - target?: string; -} - -interface TooltipOptions { - animation?: boolean; - html?: boolean; - placement?: string | Function; - selector?: string; - title?: string | Function; - trigger?: string; - template?: string; - delay?: number | Object; - container?: string | boolean; - viewport?: string | Function | Object; -} - -interface PopoverOptions { - animation?: boolean; - html?: boolean; - placement?: string | Function; - selector?: string; - trigger?: string; - title?: string | Function; - template?: string; - content?: any; - delay?: number | Object; - container?: string | boolean; - viewport?: string | Function | Object; -} - -interface CollapseOptions { - parent?: any; - toggle?: boolean; -} - -interface CarouselOptions { - interval?: number; - pause?: string; - wrap?: boolean; - keybord?: boolean; -} - -interface TypeaheadOptions { - source?: any; - items?: number; - minLength?: number; - matcher?: (item: any) => boolean; - sorter?: (items: any[]) => any[]; - updater?: (item: any) => any; - highlighter?: (item: any) => string; -} - -interface AffixOptions { - offset?: number | Function | Object; - target?: any; -} - -interface JQuery { - modal(options?: ModalOptions): JQuery; - modal(options?: ModalOptionsBackdropString): JQuery; - modal(command: string): JQuery; - - dropdown(): JQuery; - dropdown(command: string): JQuery; - - scrollspy(command: string): JQuery; - scrollspy(options?: ScrollSpyOptions): JQuery; - - tab(): JQuery; - tab(command: string): JQuery; - - tooltip(options?: TooltipOptions): JQuery; - tooltip(command: string): JQuery; - - popover(options?: PopoverOptions): JQuery; - popover(command: string): JQuery; - - alert(): JQuery; - alert(command: string): JQuery; - - button(): JQuery; - button(command: string): JQuery; - - collapse(options?: CollapseOptions): JQuery; - collapse(command: string): JQuery; - - carousel(options?: CarouselOptions): JQuery; - carousel(command: string): JQuery; - - typeahead(options?: TypeaheadOptions): JQuery; - - affix(options?: AffixOptions): JQuery; -} - -declare module "bootstrap" { -} +// Type definitions for Bootstrap 3.3.5 +// Project: http://twitter.github.com/bootstrap/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface ModalOptions { + backdrop?: boolean|string; + keyboard?: boolean; + show?: boolean; + remote?: string; +} + +interface ModalOptionsBackdropString { + backdrop?: string; // for "static" + keyboard?: boolean; + show?: boolean; + remote?: string; +} + +interface ScrollSpyOptions { + offset?: number; + target?: string; +} + +interface TooltipOptions { + animation?: boolean; + html?: boolean; + placement?: string | Function; + selector?: string; + title?: string | Function; + trigger?: string; + template?: string; + delay?: number | Object; + container?: string | boolean; + viewport?: string | Function | Object; +} + +interface PopoverOptions { + animation?: boolean; + html?: boolean; + placement?: string | Function; + selector?: string; + trigger?: string; + title?: string | Function; + template?: string; + content?: any; + delay?: number | Object; + container?: string | boolean; + viewport?: string | Function | Object; +} + +interface CollapseOptions { + parent?: any; + toggle?: boolean; +} + +interface CarouselOptions { + interval?: number; + pause?: string; + wrap?: boolean; + keybord?: boolean; +} + +interface TypeaheadOptions { + source?: any; + items?: number; + minLength?: number; + matcher?: (item: any) => boolean; + sorter?: (items: any[]) => any[]; + updater?: (item: any) => any; + highlighter?: (item: any) => string; +} + +interface AffixOptions { + offset?: number | Function | Object; + target?: any; +} + +interface JQuery { + modal(options?: ModalOptions): JQuery; + modal(options?: ModalOptionsBackdropString): JQuery; + modal(command: string): JQuery; + + dropdown(): JQuery; + dropdown(command: string): JQuery; + + scrollspy(command: string): JQuery; + scrollspy(options?: ScrollSpyOptions): JQuery; + + tab(): JQuery; + tab(command: string): JQuery; + + tooltip(options?: TooltipOptions): JQuery; + tooltip(command: string): JQuery; + + popover(options?: PopoverOptions): JQuery; + popover(command: string): JQuery; + + alert(): JQuery; + alert(command: string): JQuery; + + button(): JQuery; + button(command: string): JQuery; + + collapse(options?: CollapseOptions): JQuery; + collapse(command: string): JQuery; + + carousel(options?: CarouselOptions): JQuery; + carousel(command: string): JQuery; + + typeahead(options?: TypeaheadOptions): JQuery; + + affix(options?: AffixOptions): JQuery; +} + +declare module "bootstrap" { +} diff --git a/browser-harness/browser-harness-tests.ts.tscparams b/browser-harness/browser-harness-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/browser-harness/browser-harness-tests.ts.tscparams +++ b/browser-harness/browser-harness-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/browser-harness/browser-harness.d.ts.tscparams b/browser-harness/browser-harness.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/browser-harness/browser-harness.d.ts.tscparams +++ b/browser-harness/browser-harness.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/camel-case/camel-case.d.ts b/camel-case/camel-case.d.ts index 9b2ec3fec..24f14e84a 100644 --- a/camel-case/camel-case.d.ts +++ b/camel-case/camel-case.d.ts @@ -1,9 +1,9 @@ -// Type definitions for camel-case -// Project: https://github.com/blakeembrey/camel-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "camel-case" { - function camelCase(string: string, locale?: string): string; - export = camelCase; -} +// Type definitions for camel-case +// Project: https://github.com/blakeembrey/camel-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "camel-case" { + function camelCase(string: string, locale?: string): string; + export = camelCase; +} diff --git a/camo/camo-tests.ts b/camo/camo-tests.ts new file mode 100644 index 000000000..68b515a61 --- /dev/null +++ b/camo/camo-tests.ts @@ -0,0 +1,43 @@ +/// + +import { + connect, + Document as CamoDocument, + DocumentSchema, + SchemaTypeExtended +} from "camo"; + +connect("mongodb://user:password@localhost:27017/database?authSource=admin").then(() => { + let document = new CamoDocument(); + + interface UserSchema extends DocumentSchema { + name: string; + password: string; + friends: string[]; + dateCreated?: Date; + } + + class User extends CamoDocument { + private name: SchemaTypeExtended = String; + private password: SchemaTypeExtended = String; + private friends: SchemaTypeExtended = [String]; + private dateCreated: SchemaTypeExtended = { + type: Date, + default: Date.now + }; + static collectionName() { + return "users"; + } + } + + var newUser = User.create({ + name: "user-1", + password: "secret", + friends: ["user-2", "user-3"] + }); + + newUser.save().then(done => { + console.log(done._id); + }); + +}); diff --git a/camo/camo.d.ts b/camo/camo.d.ts new file mode 100644 index 000000000..70f9817ff --- /dev/null +++ b/camo/camo.d.ts @@ -0,0 +1,139 @@ +// Type definitions for camo v0.11.4 +// Project: https://github.com/scottwrobinson/camo +// Definitions by: Lucas Matías Ciruzzi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "camo" { + + type TypeOrArray = Type | Type[]; + + /** + * Supported type constructors for document properties + */ + export type SchemaTypeConstructor = + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray; + + /** + * Supported types for document properties + */ + export type SchemaType = TypeOrArray; + + /** + * Document property with options + */ + export interface SchemaTypeOptions { + /** + * Type of data + */ + type: SchemaTypeConstructor; + /** + * Default value + */ + default?: Type; + /** + * Min value (only with Number) + */ + min?: number; + /** + * Max value (only with Number) + */ + max?: number; + /** + * Posible options + */ + choices?: Type[]; + /** + * RegEx to match value + */ + match?: RegExp; + /** + * Validation function + * + * @param value Value taken + * @returns true (validation ok) or false (validation wrong) + */ + validate?(value: Type): boolean; + /** + * Unique value (like ids) + */ + unique?: boolean; + /** + * Required field + */ + required?: boolean; + } + + /** + * Document property type or options + */ + export type SchemaTypeExtended = SchemaTypeConstructor | SchemaTypeOptions; + + /** + * Schema passed to Document.create() + */ + interface DocumentSchema { + /** + * Index signature + */ + [property: string]: SchemaType; + /** + * Document id + */ + _id?: string; + } + + /** + * Camo document instance + */ + class DocumentInstance { + public save(): Promise; + public loadOne(): Promise; + public loadMany(): Promise; + public delete(): Promise; + public deleteOne(): Promise; + public deleteMany(): Promise; + public loadOneAndDelete(): Promise; + public count(): Promise; + public preValidate(): Promise; + public postValidate(): Promise; + public preSave(): Promise; + public postSave(): Promise; + public preDelete(): Promise; + public postDelete(): Promise; + } + + /** + * Camo document + */ + export class Document { + /** + * Index signature + */ + [property: string]: SchemaTypeExtended | string | DocumentInstance; + /** + * Static method to define the collection name + * + * @returns The collection name + */ + static collectionName(): string; + /** + * Creates a camo document instance + * + * @returns A camo document instance + */ + static create(schema: Schema): DocumentInstance; + } + + /** + * Connect function + * + * @param uri Connection URI + */ + export function connect (uri: string): Promise; + +} diff --git a/casperjs/casperjs.d.ts b/casperjs/casperjs.d.ts index f03840380..e1fdd7dcf 100644 --- a/casperjs/casperjs.d.ts +++ b/casperjs/casperjs.d.ts @@ -1,312 +1,312 @@ -// Type definitions for CasperJS v1.0.0 -// Project: http://casperjs.org/ -// Definitions by: Jed Mao -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -interface CasperModule { - create(options: CasperOptions): Casper; - selectXPath(expression: string): Object -} - -interface EventEmitter { - removeAllFilters(filter: string): Casper; - setFilter(filter: string, cb: Function): boolean; -} - -interface Casper extends EventEmitter { - test: Tester; - - constructor (options: CasperOptions): Casper; - - options: CasperOptions; - // Properties - __utils__: ClientUtils; - - // Methods - back(): Casper; - base64encode(url: string, method?: string, data?: any): string; - bypass(nb: number): any; - click(selector: string): boolean; - clickLabel(label: string, tag?: string): boolean; - capture(targetFilePath: string, clipRect: ClipRect): Casper; - captureBase64(format: string): string; - captureBase64(format: string, area: string): string; - captureBase64(format: string, area: ClipRect): string; - captureBase64(format: string, area: any): string; - captureSelector(targetFile: string, selector: string): Casper; - clear(): Casper; - debugHTML(selector?: string, outer?: boolean): Casper; - debugPage(): Casper; - die(message: string, status?: number): Casper; - download(url: string, target?: string, method?: string, data?: any): Casper; - each(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper; - echo(message: string, style?: string): Casper; - evaluate(fn: () => T, ...args: any[]): T - evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; - exit(status?: number): Casper; - exists(selector: string): boolean; - fetchText(selector: string): string; - forward(): Casper; - log(message: string, level?: string, space?: string): Casper; - fill(selector: string, values: any, submit?: boolean): void; - fillSelectors(selector: string, values: any, submit?: boolean): void; - fillXPath(selector: string, values: any, submit?: boolean): void; - getCurrentUrl(): string; - getElementAttribute(selector: string, attribute: string): string; - getElementsAttribute(selector: string, attribute: string): string; - getElementBounds(selector: string): ElementBounds; - getElementsBounds(selector: string): ElementBounds[]; - getElementInfo(selector: string): ElementInfo; - getElementsInfo(selector: string): ElementInfo; - getFormValues(selector: string): any; - getGlobal(name: string): any; - getHTML(selector?: string, outer?: boolean): string; - getPageContent(): string; - getTitle(): string; - mouseEvent(type: string, selector: string): boolean; - open(location: string, settings: OpenSettings): Casper; - reload(then?: (response: HttpResponse) => void): Casper; - repeat(times: number, then: Function): Casper; - resourceExists(test: Function): boolean; - resourceExists(test: string): boolean; - run(onComplete: Function, time?: number): Casper; - scrollTo(x: number, y: number): Casper; - scrollToBottom(): Casper; - sendKeys(selector: string, keys: string, options?: any): Casper; - setHttpAuth(username: string, password: string): Casper; - start(url?: string, then?: (response: HttpResponse) => void): Casper; - status(asString: boolean): any; - then(fn: (self?: Casper) => void): Casper; - thenBypass(nb: number): Casper; - thenBypassIf(condition: any, nb: number): Casper; - thenBypassUnless(condition: any, nb: number): Casper; - thenClick(selector: string): Casper; - thenEvaluate(fn: () => any, ...args: any[]): Casper; - thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; - thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; - thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper; - toString(): string; - unwait(): Casper; - userAgent(agent: string): string; - viewport(width: number, height: number): Casper; - visible(selector: string): boolean; - wait(timeout: number, then?: Function): Casper; - waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForAlert(then: Function, onTimeout?: Function, timeout?: number): Casper; - waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForUrl(url: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForUrl(url: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - warn(message: string): Casper; - withFrame(frameInfo: string, then: Function): Casper; - withFrame(frameInfo: number, then: Function): Casper; - withPopup(popupInfo: string, step: Function): Casper; - withPopup(popupInfo: RegExp, step: Function): Casper; - zoom(factor: number): Casper; -} - -interface HttpResponse { - contentType: string; - headers: any[]; - id: number; - redirectURL: string; - stage: string; - status: number; - statusText: string; - time: string; - url: string; -} - -interface OpenSettings { - method: string; - data: any; - headers: any; -} - -interface ElementBounds { - top: number; - left: number; - width: number; - height: number; -} - -interface ElementInfo { - nodeName: string; - attributes: any; - tag: string; - html: string; - text: string; - x: number; - y: number; - width: number; - height: number; - visible: boolean; -} - -interface CasperOptions { - clientScripts?: any[]; - exitOnError?: boolean; - httpStatusHandlers?: any; - logLevel?: string; - onAlert?: Function; - onDie?: Function; - onError?: Function; - onLoadError?: Function; - onPageInitialized?: Function; - onResourceReceived?: Function; - onResourceRequested?: Function; - onStepComplete?: Function; - onStepTimeout?: Function; - onTimeout?: Function; - onWaitTimeout?: Function; - page?: WebPage; - pageSettings?: any; - remoteScripts?: any[]; - safeLogs?: boolean; - silentErrors?: boolean; - stepTimeout?: number; - timeout?: number; - verbose?: boolean; - viewportSize?: any; - retryTimeout?: number; - waitTimeout?: number; -} - -interface ClientUtils { - echo(message: string): void; - encode(contents: string): void; - exists(selector: string): void; - findAll(selector: string): void; - findOne(selector: string): void; - getBase64(url: string, method?: string, data?: any): void; - getBinary(url: string, method?: string, data?: any): void; - getDocumentHeight(): void; - getElementBounds(selector: string): void; - getElementsBounds(selector: string): void; - getElementByXPath(expression: string, scope?: HTMLElement): void; - getElementsByXPath(expression: string, scope?: HTMLElement): void; - getFieldValue(inputName: string): void; - getFormValues(selector: string): void; - mouseEvent(type: string, selector: string): void; - removeElementsByXPath(expression: string): void; - sendAJAX(url: string, method?: string, data?: any, async?: boolean): void; - visible(selector: string): void; -} - -interface Colorizer { - colorize(text: string, styleName: string): void; - format(text: string, style: any): void; -} - -interface Tester { - assert(condition: boolean, message?: string): any; - assertDoesntExist(selector: string, message?: string): any; - assertElementCount(selctor: string, expected: number, message?: string): any; - assertEquals(testValue: any, expected: any, message?: string): any; - assertEval(fn: Function, message: string, arguments: any): any; - assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any): any; - assertExists(selector: string, message?: string): any; - assertFalsy(subject: any, message?: string): any; - assertField(inputName: string, expected: string, message?: string): any; - assertFieldName(inputName: string, expected: string, message?: string, options?: any): any; - assertFieldCSS(cssSelector: string, expected: string, message?: string): any; - assertFieldXPath(xpathSelector: string, expected: string, message?: string): any; - assertHttpStatus(status: number, message?: string): any; - assertMatch(subject: any, pattern: RegExp, message?: string): any; - assertNot(subject: any, message?: string): any; - assertNotEquals(testValue: any, expected: any, message?: string): any; - assertNotVisible(selector: string, message?: string): any; - assertRaises(fn: Function, args: any[], message?: string): any; - assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any; - assertSelectorExists(selector: string, message?: string): any; - assertSelectorHasText(selector: string, text: string, message?: string): any; - assertResourceExists(testFx: Function, message?: string): any; - assertTextExists(expected: string, message?: string): any; - assertTextDoesntExist(unexpected: string, message: string): any; - assertTitle(expected: string, message?: string): any; - assertTitleMatch(pattern: RegExp, message?: string): any; - assertTruthy(subject: any, message?: string): any; - assertType(input: any, type: string, message?: string): any; - assertInstanceOf(input: any, ctor: Function, message?: string): any; - assertUrlMatch(pattern: string, message?: string): any; - assertUrlMatch(pattern: RegExp, message?: string): any; - assertVisible(selector: string, message?: string): any; - - /* since 1.1 */ - begin(description: string, planned: number, suite: Function): any; - begin(description: string, suite: Function): any; - begin(description: string, planned: number, config: Object): any; - begin(description: string, config: Object): any; - - colorize(message: string, style: string): any; - comment(message: string): any; - done(expected?: number): any; - error(message: string): any; - fail(message: string): any; - formatMessage(message: string, style: string): any; - getFailures(): Cases; - getPasses(): Cases; - info(message: string): any; - pass(message: string): any; - renderResults(exit: boolean, status: number, save: string): any; - - setup(fn: Function): any; - skip(nb: number, message: string): any; - tearDown(fn: Function): any; -} - -interface Cases { - length: number; - cases: Case[]; -} - -interface Case { - success: boolean; - type: string; - standard: string; - file: string; - values: CaseValues; -} - -interface CaseValues { - subject: boolean; - expected: boolean; -} - -interface Utils { - betterTypeOf(input: any): any; - dump(value: any): any; - fileExt(file: string): any; - fillBlanks(text: string, pad: number): any; - format(f: string, ...args: any[]): any; - getPropertyPath(obj: any, path: string): any; - inherits(ctor: any, superCtor: any): any; - isArray(value: any): any; - isCasperObject(value: any): any; - isClipRect(value: any): any; - isFalsy(subject: any): any; - isFunction(value: any): any; - isJsFile(file: string): any; - isNull(value: any): any; - isNumber(value: any): any; - isObject(value: any): any; - isRegExp(value: any): any; - isString(value: any): any; - isTruthy(subject: any): any; - isType(what: any, type: string): any; - isUndefined(value: any): any; - isWebPage(what: any): any; - mergeObjects(origin: any, add: any): any; - node(name: string, attributes: any): any; - serialize(value: any): any; - unique(array: any[]): any; -} +// Type definitions for CasperJS v1.0.0 +// Project: http://casperjs.org/ +// Definitions by: Jed Mao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface CasperModule { + create(options: CasperOptions): Casper; + selectXPath(expression: string): Object +} + +interface EventEmitter { + removeAllFilters(filter: string): Casper; + setFilter(filter: string, cb: Function): boolean; +} + +interface Casper extends EventEmitter { + test: Tester; + + constructor (options: CasperOptions): Casper; + + options: CasperOptions; + // Properties + __utils__: ClientUtils; + + // Methods + back(): Casper; + base64encode(url: string, method?: string, data?: any): string; + bypass(nb: number): any; + click(selector: string): boolean; + clickLabel(label: string, tag?: string): boolean; + capture(targetFilePath: string, clipRect: ClipRect): Casper; + captureBase64(format: string): string; + captureBase64(format: string, area: string): string; + captureBase64(format: string, area: ClipRect): string; + captureBase64(format: string, area: any): string; + captureSelector(targetFile: string, selector: string): Casper; + clear(): Casper; + debugHTML(selector?: string, outer?: boolean): Casper; + debugPage(): Casper; + die(message: string, status?: number): Casper; + download(url: string, target?: string, method?: string, data?: any): Casper; + each(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper; + echo(message: string, style?: string): Casper; + evaluate(fn: () => T, ...args: any[]): T + evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; + exit(status?: number): Casper; + exists(selector: string): boolean; + fetchText(selector: string): string; + forward(): Casper; + log(message: string, level?: string, space?: string): Casper; + fill(selector: string, values: any, submit?: boolean): void; + fillSelectors(selector: string, values: any, submit?: boolean): void; + fillXPath(selector: string, values: any, submit?: boolean): void; + getCurrentUrl(): string; + getElementAttribute(selector: string, attribute: string): string; + getElementsAttribute(selector: string, attribute: string): string; + getElementBounds(selector: string): ElementBounds; + getElementsBounds(selector: string): ElementBounds[]; + getElementInfo(selector: string): ElementInfo; + getElementsInfo(selector: string): ElementInfo; + getFormValues(selector: string): any; + getGlobal(name: string): any; + getHTML(selector?: string, outer?: boolean): string; + getPageContent(): string; + getTitle(): string; + mouseEvent(type: string, selector: string): boolean; + open(location: string, settings: OpenSettings): Casper; + reload(then?: (response: HttpResponse) => void): Casper; + repeat(times: number, then: Function): Casper; + resourceExists(test: Function): boolean; + resourceExists(test: string): boolean; + run(onComplete: Function, time?: number): Casper; + scrollTo(x: number, y: number): Casper; + scrollToBottom(): Casper; + sendKeys(selector: string, keys: string, options?: any): Casper; + setHttpAuth(username: string, password: string): Casper; + start(url?: string, then?: (response: HttpResponse) => void): Casper; + status(asString: boolean): any; + then(fn: (self?: Casper) => void): Casper; + thenBypass(nb: number): Casper; + thenBypassIf(condition: any, nb: number): Casper; + thenBypassUnless(condition: any, nb: number): Casper; + thenClick(selector: string): Casper; + thenEvaluate(fn: () => any, ...args: any[]): Casper; + thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; + thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; + thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper; + toString(): string; + unwait(): Casper; + userAgent(agent: string): string; + viewport(width: number, height: number): Casper; + visible(selector: string): boolean; + wait(timeout: number, then?: Function): Casper; + waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForAlert(then: Function, onTimeout?: Function, timeout?: number): Casper; + waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForUrl(url: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForUrl(url: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + warn(message: string): Casper; + withFrame(frameInfo: string, then: Function): Casper; + withFrame(frameInfo: number, then: Function): Casper; + withPopup(popupInfo: string, step: Function): Casper; + withPopup(popupInfo: RegExp, step: Function): Casper; + zoom(factor: number): Casper; +} + +interface HttpResponse { + contentType: string; + headers: any[]; + id: number; + redirectURL: string; + stage: string; + status: number; + statusText: string; + time: string; + url: string; +} + +interface OpenSettings { + method: string; + data: any; + headers: any; +} + +interface ElementBounds { + top: number; + left: number; + width: number; + height: number; +} + +interface ElementInfo { + nodeName: string; + attributes: any; + tag: string; + html: string; + text: string; + x: number; + y: number; + width: number; + height: number; + visible: boolean; +} + +interface CasperOptions { + clientScripts?: any[]; + exitOnError?: boolean; + httpStatusHandlers?: any; + logLevel?: string; + onAlert?: Function; + onDie?: Function; + onError?: Function; + onLoadError?: Function; + onPageInitialized?: Function; + onResourceReceived?: Function; + onResourceRequested?: Function; + onStepComplete?: Function; + onStepTimeout?: Function; + onTimeout?: Function; + onWaitTimeout?: Function; + page?: WebPage; + pageSettings?: any; + remoteScripts?: any[]; + safeLogs?: boolean; + silentErrors?: boolean; + stepTimeout?: number; + timeout?: number; + verbose?: boolean; + viewportSize?: any; + retryTimeout?: number; + waitTimeout?: number; +} + +interface ClientUtils { + echo(message: string): void; + encode(contents: string): void; + exists(selector: string): void; + findAll(selector: string): void; + findOne(selector: string): void; + getBase64(url: string, method?: string, data?: any): void; + getBinary(url: string, method?: string, data?: any): void; + getDocumentHeight(): void; + getElementBounds(selector: string): void; + getElementsBounds(selector: string): void; + getElementByXPath(expression: string, scope?: HTMLElement): void; + getElementsByXPath(expression: string, scope?: HTMLElement): void; + getFieldValue(inputName: string): void; + getFormValues(selector: string): void; + mouseEvent(type: string, selector: string): void; + removeElementsByXPath(expression: string): void; + sendAJAX(url: string, method?: string, data?: any, async?: boolean): void; + visible(selector: string): void; +} + +interface Colorizer { + colorize(text: string, styleName: string): void; + format(text: string, style: any): void; +} + +interface Tester { + assert(condition: boolean, message?: string): any; + assertDoesntExist(selector: string, message?: string): any; + assertElementCount(selctor: string, expected: number, message?: string): any; + assertEquals(testValue: any, expected: any, message?: string): any; + assertEval(fn: Function, message: string, arguments: any): any; + assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any): any; + assertExists(selector: string, message?: string): any; + assertFalsy(subject: any, message?: string): any; + assertField(inputName: string, expected: string, message?: string): any; + assertFieldName(inputName: string, expected: string, message?: string, options?: any): any; + assertFieldCSS(cssSelector: string, expected: string, message?: string): any; + assertFieldXPath(xpathSelector: string, expected: string, message?: string): any; + assertHttpStatus(status: number, message?: string): any; + assertMatch(subject: any, pattern: RegExp, message?: string): any; + assertNot(subject: any, message?: string): any; + assertNotEquals(testValue: any, expected: any, message?: string): any; + assertNotVisible(selector: string, message?: string): any; + assertRaises(fn: Function, args: any[], message?: string): any; + assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any; + assertSelectorExists(selector: string, message?: string): any; + assertSelectorHasText(selector: string, text: string, message?: string): any; + assertResourceExists(testFx: Function, message?: string): any; + assertTextExists(expected: string, message?: string): any; + assertTextDoesntExist(unexpected: string, message: string): any; + assertTitle(expected: string, message?: string): any; + assertTitleMatch(pattern: RegExp, message?: string): any; + assertTruthy(subject: any, message?: string): any; + assertType(input: any, type: string, message?: string): any; + assertInstanceOf(input: any, ctor: Function, message?: string): any; + assertUrlMatch(pattern: string, message?: string): any; + assertUrlMatch(pattern: RegExp, message?: string): any; + assertVisible(selector: string, message?: string): any; + + /* since 1.1 */ + begin(description: string, planned: number, suite: Function): any; + begin(description: string, suite: Function): any; + begin(description: string, planned: number, config: Object): any; + begin(description: string, config: Object): any; + + colorize(message: string, style: string): any; + comment(message: string): any; + done(expected?: number): any; + error(message: string): any; + fail(message: string): any; + formatMessage(message: string, style: string): any; + getFailures(): Cases; + getPasses(): Cases; + info(message: string): any; + pass(message: string): any; + renderResults(exit: boolean, status: number, save: string): any; + + setup(fn: Function): any; + skip(nb: number, message: string): any; + tearDown(fn: Function): any; +} + +interface Cases { + length: number; + cases: Case[]; +} + +interface Case { + success: boolean; + type: string; + standard: string; + file: string; + values: CaseValues; +} + +interface CaseValues { + subject: boolean; + expected: boolean; +} + +interface Utils { + betterTypeOf(input: any): any; + dump(value: any): any; + fileExt(file: string): any; + fillBlanks(text: string, pad: number): any; + format(f: string, ...args: any[]): any; + getPropertyPath(obj: any, path: string): any; + inherits(ctor: any, superCtor: any): any; + isArray(value: any): any; + isCasperObject(value: any): any; + isClipRect(value: any): any; + isFalsy(subject: any): any; + isFunction(value: any): any; + isJsFile(file: string): any; + isNull(value: any): any; + isNumber(value: any): any; + isObject(value: any): any; + isRegExp(value: any): any; + isString(value: any): any; + isTruthy(subject: any): any; + isType(what: any, type: string): any; + isUndefined(value: any): any; + isWebPage(what: any): any; + mergeObjects(origin: any, add: any): any; + node(name: string, attributes: any): any; + serialize(value: any): any; + unique(array: any[]): any; +} diff --git a/chai-as-promised/chai-as-promised-tests.ts b/chai-as-promised/chai-as-promised-tests.ts index 0b747d2c4..8685f953f 100644 --- a/chai-as-promised/chai-as-promised-tests.ts +++ b/chai-as-promised/chai-as-promised-tests.ts @@ -8,6 +8,8 @@ import Q = require('q'); chai.use(chaiAsPromised); +class TestClass {} + // ReSharper disable WrongExpressionStatement // BDD API (expect) var thenableNum: PromisesAPlus.Thenable; @@ -17,6 +19,13 @@ thenableNum = chai.expect(thenableNum).to.become(3); thenableNum = chai.expect(thenableNum).to.be.fulfilled; thenableNum = chai.expect(thenableNum).to.be.rejected; thenableNum = chai.expect(thenableNum).to.be.rejectedWith(Error); +thenableNum = chai.expect(thenableNum).to.be.rejectedWith('Error'); +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(/message/); +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(Error, /message/); +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(Error, 'message'); +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(TestClass); +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(TestClass, /message/); +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(TestClass, 'message'); thenableNum = chai.expect(thenableNum).to.notify(() => console.log('done')); // BDD API (should) @@ -25,6 +34,13 @@ thenableNum = thenableNum.should.eventually.deep.equal(3); thenableNum = thenableNum.should.become(3); thenableNum = thenableNum.should.be.rejected; thenableNum = thenableNum.should.be.rejectedWith(Error); +thenableNum = thenableNum.should.be.rejectedWith('Error'); +thenableNum = thenableNum.should.be.rejectedWith(/message/); +thenableNum = thenableNum.should.be.rejectedWith(Error, /message/); +thenableNum = thenableNum.should.be.rejectedWith(Error, 'message'); +thenableNum = thenableNum.should.be.rejectedWith(TestClass); +thenableNum = thenableNum.should.be.rejectedWith(TestClass, /message/); +thenableNum = thenableNum.should.be.rejectedWith(TestClass, 'message'); thenableNum = thenableNum.should.eventually.equal(3).notify(() => console.log('done')); thenableNum = thenableNum.should.be.fulfilled.and.notify(() => console.log('done')); diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts index d7f1472c7..36aa358f3 100644 --- a/chai-as-promised/chai-as-promised.d.ts +++ b/chai-as-promised/chai-as-promised.d.ts @@ -20,7 +20,7 @@ declare module Chai { become(expected: any): PromisedAssertion; fulfilled: PromisedAssertion; rejected: PromisedAssertion; - rejectedWith(expected: any, message?: string): PromisedAssertion; + rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; notify(fn: Function): PromisedAssertion; } @@ -30,7 +30,7 @@ declare module Chai { become(expected: PromisesAPlus.Thenable): PromisedAssertion; fulfilled: PromisedAssertion; rejected: PromisedAssertion; - rejectedWith(expected: any): PromisedAssertion; + rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; notify(fn: Function): PromisedAssertion; // From chai diff --git a/chai/chai-3.2.0.d.ts b/chai/chai-3.2.0.d.ts index e68e6fa3b..3ef3046ac 100644 --- a/chai/chai-3.2.0.d.ts +++ b/chai/chai-3.2.0.d.ts @@ -1,388 +1,388 @@ -// Type definitions for chai 3.2.0 -// Project: http://chaijs.com/ -// Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown , -// Olivier Chevet -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// - -declare module Chai { - - interface ChaiStatic { - expect: ExpectStatic; - should(): Should; - /** - * Provides a way to extend the internals of Chai - */ - use(fn: (chai: any, utils: any) => void): any; - assert: AssertStatic; - config: Config; - AssertionError: typeof AssertionError; - } - - export interface ExpectStatic extends AssertionStatic { - fail(actual?: any, expected?: any, message?: string, operator?: string): void; - } - - export interface AssertStatic extends Assert { - } - - export interface AssertionStatic { - (target: any, message?: string): Assertion; - } - - interface ShouldAssertion { - equal(value1: any, value2: any, message?: string): void; - Throw: ShouldThrow; - throw: ShouldThrow; - exist(value: any, message?: string): void; - } - - interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: string): void; - } - - interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; - (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; - } - - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - any: KeyFilter; - all: KeyFilter; - a: TypeComparison; - an: TypeComparison; - include: Include; - includes: Include; - contain: Include; - contains: Include; - ok: Assertion; - true: Assertion; - false: Assertion; - null: Assertion; - undefined: Assertion; - NaN: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - ownPropertyDescriptor: OwnPropertyDescriptor; - haveOwnPropertyDescriptor: OwnPropertyDescriptor; - length: Length; - lengthOf: Length; - match: Match; - matches: Match; - string(string: string, message?: string): Assertion; - keys: Keys; - key(string: string): Assertion; - throw: Throw; - throws: Throw; - Throw: Throw; - respondTo: RespondTo; - respondsTo: RespondTo; - itself: Assertion; - satisfy: Satisfy; - satisfies: Satisfy; - closeTo(expected: number, delta: number, message?: string): Assertion; - members: Members; - increase: PropertyChange; - increases: PropertyChange; - decrease: PropertyChange; - decreases: PropertyChange; - change: PropertyChange; - changes: PropertyChange; - extensible: Assertion; - sealed: Assertion; - frozen: Assertion; - - } - - interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; - } - - interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; - } - - interface NumberComparer { - (value: number, message?: string): Assertion; - } - - interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; - } - - interface InstanceOf { - (constructor: Object, message?: string): Assertion; - } - - interface Deep { - equal: Equal; - include: Include; - property: Property; - members: Members; - } - - interface KeyFilter { - keys: Keys; - } - - interface Equal { - (value: any, message?: string): Assertion; - } - - interface Property { - (name: string, value?: any, message?: string): Assertion; - } - - interface OwnProperty { - (name: string, message?: string): Assertion; - } - - interface OwnPropertyDescriptor { - (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; - (name: string, message?: string): Assertion; - } - - interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; - } - - interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; - keys: Keys; - members: Members; - any: KeyFilter; - all: KeyFilter; - } - - interface Match { - (regexp: RegExp|string, message?: string): Assertion; - } - - interface Keys { - (...keys: string[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; - } - - interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; - } - - interface RespondTo { - (method: string, message?: string): Assertion; - } - - interface Satisfy { - (matcher: Function, message?: string): Assertion; - } - - interface Members { - (set: any[], message?: string): Assertion; - } - - interface PropertyChange { - (object: Object, prop: string, msg?: string): Assertion; - } - - export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - - ok(val: any, msg?: string): void; - isOk(val: any, msg?: string): void; - notOk(val: any, msg?: string): void; - isNotOk(val: any, msg?: string): void; - - equal(act: any, exp: any, msg?: string): void; - notEqual(act: any, exp: any, msg?: string): void; - - strictEqual(act: any, exp: any, msg?: string): void; - notStrictEqual(act: any, exp: any, msg?: string): void; - - deepEqual(act: any, exp: any, msg?: string): void; - notDeepEqual(act: any, exp: any, msg?: string): void; - - isTrue(val: any, msg?: string): void; - isFalse(val: any, msg?: string): void; - - isNull(val: any, msg?: string): void; - isNotNull(val: any, msg?: string): void; - - isUndefined(val: any, msg?: string): void; - isDefined(val: any, msg?: string): void; - - isNaN(val: any, msg?: string): void; - isNotNaN(val: any, msg?: string): void; - - isAbove(val: number, abv: number, msg?: string): void; - isBelow(val: number, blw: number, msg?: string): void; - - isFunction(val: any, msg?: string): void; - isNotFunction(val: any, msg?: string): void; - - isObject(val: any, msg?: string): void; - isNotObject(val: any, msg?: string): void; - - isArray(val: any, msg?: string): void; - isNotArray(val: any, msg?: string): void; - - isString(val: any, msg?: string): void; - isNotString(val: any, msg?: string): void; - - isNumber(val: any, msg?: string): void; - isNotNumber(val: any, msg?: string): void; - - isBoolean(val: any, msg?: string): void; - isNotBoolean(val: any, msg?: string): void; - - typeOf(val: any, type: string, msg?: string): void; - notTypeOf(val: any, type: string, msg?: string): void; - - instanceOf(val: any, type: Function, msg?: string): void; - notInstanceOf(val: any, type: Function, msg?: string): void; - - include(exp: string, inc: any, msg?: string): void; - include(exp: any[], inc: any, msg?: string): void; - - notInclude(exp: string, inc: any, msg?: string): void; - notInclude(exp: any[], inc: any, msg?: string): void; - - match(exp: any, re: RegExp, msg?: string): void; - notMatch(exp: any, re: RegExp, msg?: string): void; - - property(obj: Object, prop: string, msg?: string): void; - notProperty(obj: Object, prop: string, msg?: string): void; - deepProperty(obj: Object, prop: string, msg?: string): void; - notDeepProperty(obj: Object, prop: string, msg?: string): void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - lengthOf(exp: any, len: number, msg?: string): void; - //alias frenzy - throw(fn: Function, msg?: string): void; - throw(fn: Function, regExp: RegExp): void; - throw(fn: Function, errType: Function, msg?: string): void; - throw(fn: Function, errType: Function, regExp: RegExp): void; - - throws(fn: Function, msg?: string): void; - throws(fn: Function, regExp: RegExp): void; - throws(fn: Function, errType: Function, msg?: string): void; - throws(fn: Function, errType: Function, regExp: RegExp): void; - - Throw(fn: Function, msg?: string): void; - Throw(fn: Function, regExp: RegExp): void; - Throw(fn: Function, errType: Function, msg?: string): void; - Throw(fn: Function, errType: Function, regExp: RegExp): void; - - doesNotThrow(fn: Function, msg?: string): void; - doesNotThrow(fn: Function, regExp: RegExp): void; - doesNotThrow(fn: Function, errType: Function, msg?: string): void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - - operator(val: any, operator: string, val2: any, msg?: string): void; - closeTo(act: number, exp: number, delta: number, msg?: string): void; - - sameMembers(set1: any[], set2: any[], msg?: string): void; - sameDeepMembers(set1: any[], set2: any[], msg?: string): void; - includeMembers(superset: any[], subset: any[], msg?: string): void; - - ifError(val: any, msg?: string): void; - - isExtensible(obj: {}, msg?: string): void; - extensible(obj: {}, msg?: string): void; - isNotExtensible(obj: {}, msg?: string): void; - notExtensible(obj: {}, msg?: string): void; - - isSealed(obj: {}, msg?: string): void; - sealed(obj: {}, msg?: string): void; - isNotSealed(obj: {}, msg?: string): void; - notSealed(obj: {}, msg?: string): void; - - isFrozen(obj: Object, msg?: string): void; - frozen(obj: Object, msg?: string): void; - isNotFrozen(obj: Object, msg?: string): void; - notFrozen(obj: Object, msg?: string): void; - - - } - - export interface Config { - includeStack: boolean; - } - - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } -} - -declare var chai: Chai.ChaiStatic; - -declare module "chai" { - export = chai; -} - -interface Object { - should: Chai.Assertion; -} +// Type definitions for chai 3.2.0 +// Project: http://chaijs.com/ +// Definitions by: Jed Mao , +// Bart van der Schoor , +// Andrew Brown , +// Olivier Chevet +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// + +declare module Chai { + + interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: (chai: any, utils: any) => void): any; + assert: AssertStatic; + config: Config; + AssertionError: typeof AssertionError; + } + + export interface ExpectStatic extends AssertionStatic { + fail(actual?: any, expected?: any, message?: string, operator?: string): void; + } + + export interface AssertStatic extends Assert { + } + + export interface AssertionStatic { + (target: any, message?: string): Assertion; + } + + interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(actual: any, expected: any, message?: string, operator?: string): void; + } + + interface ShouldThrow { + (actual: Function): void; + (actual: Function, expected: string|RegExp, message?: string): void; + (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; + } + + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + any: KeyFilter; + all: KeyFilter; + a: TypeComparison; + an: TypeComparison; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + property: Property; + ownProperty: OwnProperty; + haveOwnProperty: OwnProperty; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo(expected: number, delta: number, message?: string): Assertion; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + + } + + interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + } + + interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + } + + interface NumberComparer { + (value: number, message?: string): Assertion; + } + + interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + interface InstanceOf { + (constructor: Object, message?: string): Assertion; + } + + interface Deep { + equal: Equal; + include: Include; + property: Property; + members: Members; + } + + interface KeyFilter { + keys: Keys; + } + + interface Equal { + (value: any, message?: string): Assertion; + } + + interface Property { + (name: string, value?: any, message?: string): Assertion; + } + + interface OwnProperty { + (name: string, message?: string): Assertion; + } + + interface OwnPropertyDescriptor { + (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string, message?: string): Assertion; + } + + interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + interface Include { + (value: Object, message?: string): Assertion; + (value: string, message?: string): Assertion; + (value: number, message?: string): Assertion; + keys: Keys; + members: Members; + any: KeyFilter; + all: KeyFilter; + } + + interface Match { + (regexp: RegExp|string, message?: string): Assertion; + } + + interface Keys { + (...keys: string[]): Assertion; + (keys: any[]): Assertion; + (keys: Object): Assertion; + } + + interface Throw { + (): Assertion; + (expected: string, message?: string): Assertion; + (expected: RegExp, message?: string): Assertion; + (constructor: Error, expected?: string, message?: string): Assertion; + (constructor: Error, expected?: RegExp, message?: string): Assertion; + (constructor: Function, expected?: string, message?: string): Assertion; + (constructor: Function, expected?: RegExp, message?: string): Assertion; + } + + interface RespondTo { + (method: string, message?: string): Assertion; + } + + interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + interface Members { + (set: any[], message?: string): Assertion; + } + + interface PropertyChange { + (object: Object, prop: string, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string): void; + + ok(val: any, msg?: string): void; + isOk(val: any, msg?: string): void; + notOk(val: any, msg?: string): void; + isNotOk(val: any, msg?: string): void; + + equal(act: any, exp: any, msg?: string): void; + notEqual(act: any, exp: any, msg?: string): void; + + strictEqual(act: any, exp: any, msg?: string): void; + notStrictEqual(act: any, exp: any, msg?: string): void; + + deepEqual(act: any, exp: any, msg?: string): void; + notDeepEqual(act: any, exp: any, msg?: string): void; + + isTrue(val: any, msg?: string): void; + isFalse(val: any, msg?: string): void; + + isNull(val: any, msg?: string): void; + isNotNull(val: any, msg?: string): void; + + isUndefined(val: any, msg?: string): void; + isDefined(val: any, msg?: string): void; + + isNaN(val: any, msg?: string): void; + isNotNaN(val: any, msg?: string): void; + + isAbove(val: number, abv: number, msg?: string): void; + isBelow(val: number, blw: number, msg?: string): void; + + isFunction(val: any, msg?: string): void; + isNotFunction(val: any, msg?: string): void; + + isObject(val: any, msg?: string): void; + isNotObject(val: any, msg?: string): void; + + isArray(val: any, msg?: string): void; + isNotArray(val: any, msg?: string): void; + + isString(val: any, msg?: string): void; + isNotString(val: any, msg?: string): void; + + isNumber(val: any, msg?: string): void; + isNotNumber(val: any, msg?: string): void; + + isBoolean(val: any, msg?: string): void; + isNotBoolean(val: any, msg?: string): void; + + typeOf(val: any, type: string, msg?: string): void; + notTypeOf(val: any, type: string, msg?: string): void; + + instanceOf(val: any, type: Function, msg?: string): void; + notInstanceOf(val: any, type: Function, msg?: string): void; + + include(exp: string, inc: any, msg?: string): void; + include(exp: any[], inc: any, msg?: string): void; + + notInclude(exp: string, inc: any, msg?: string): void; + notInclude(exp: any[], inc: any, msg?: string): void; + + match(exp: any, re: RegExp, msg?: string): void; + notMatch(exp: any, re: RegExp, msg?: string): void; + + property(obj: Object, prop: string, msg?: string): void; + notProperty(obj: Object, prop: string, msg?: string): void; + deepProperty(obj: Object, prop: string, msg?: string): void; + notDeepProperty(obj: Object, prop: string, msg?: string): void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string): void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + lengthOf(exp: any, len: number, msg?: string): void; + //alias frenzy + throw(fn: Function, msg?: string): void; + throw(fn: Function, regExp: RegExp): void; + throw(fn: Function, errType: Function, msg?: string): void; + throw(fn: Function, errType: Function, regExp: RegExp): void; + + throws(fn: Function, msg?: string): void; + throws(fn: Function, regExp: RegExp): void; + throws(fn: Function, errType: Function, msg?: string): void; + throws(fn: Function, errType: Function, regExp: RegExp): void; + + Throw(fn: Function, msg?: string): void; + Throw(fn: Function, regExp: RegExp): void; + Throw(fn: Function, errType: Function, msg?: string): void; + Throw(fn: Function, errType: Function, regExp: RegExp): void; + + doesNotThrow(fn: Function, msg?: string): void; + doesNotThrow(fn: Function, regExp: RegExp): void; + doesNotThrow(fn: Function, errType: Function, msg?: string): void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; + + operator(val: any, operator: string, val2: any, msg?: string): void; + closeTo(act: number, exp: number, delta: number, msg?: string): void; + + sameMembers(set1: any[], set2: any[], msg?: string): void; + sameDeepMembers(set1: any[], set2: any[], msg?: string): void; + includeMembers(superset: any[], subset: any[], msg?: string): void; + + ifError(val: any, msg?: string): void; + + isExtensible(obj: {}, msg?: string): void; + extensible(obj: {}, msg?: string): void; + isNotExtensible(obj: {}, msg?: string): void; + notExtensible(obj: {}, msg?: string): void; + + isSealed(obj: {}, msg?: string): void; + sealed(obj: {}, msg?: string): void; + isNotSealed(obj: {}, msg?: string): void; + notSealed(obj: {}, msg?: string): void; + + isFrozen(obj: Object, msg?: string): void; + frozen(obj: Object, msg?: string): void; + isNotFrozen(obj: Object, msg?: string): void; + notFrozen(obj: Object, msg?: string): void; + + + } + + export interface Config { + includeStack: boolean; + } + + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } +} + +declare var chai: Chai.ChaiStatic; + +declare module "chai" { + export = chai; +} + +interface Object { + should: Chai.Assertion; +} diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index df09aea3e..dbca4c11a 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1097,6 +1097,12 @@ function use() { chai.use((_chai) => { _chai.can.use.any(); }); + + // chain style: use mulptile plug-ins + let expect = chai + .use((_chai, util) => {}) + .use((_chai, util) => {}) + .expect; } class Klass { diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 074827b65..fc3ea2cc7 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,401 +1,401 @@ -// Type definitions for chai 3.4.0 -// Project: http://chaijs.com/ -// Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown , -// Olivier Chevet , -// Matt Wistrand -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// - -declare module Chai { - - interface ChaiStatic { - expect: ExpectStatic; - should(): Should; - /** - * Provides a way to extend the internals of Chai - */ - use(fn: (chai: any, utils: any) => void): any; - assert: AssertStatic; - config: Config; - AssertionError: typeof AssertionError; - } - - export interface ExpectStatic extends AssertionStatic { - fail(actual?: any, expected?: any, message?: string, operator?: string): void; - } - - export interface AssertStatic extends Assert { - } - - export interface AssertionStatic { - (target: any, message?: string): Assertion; - } - - interface ShouldAssertion { - equal(value1: any, value2: any, message?: string): void; - Throw: ShouldThrow; - throw: ShouldThrow; - exist(value: any, message?: string): void; - } - - interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: string): void; - } - - interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; - (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; - } - - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - any: KeyFilter; - all: KeyFilter; - a: TypeComparison; - an: TypeComparison; - include: Include; - includes: Include; - contain: Include; - contains: Include; - ok: Assertion; - true: Assertion; - false: Assertion; - null: Assertion; - undefined: Assertion; - NaN: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - ownPropertyDescriptor: OwnPropertyDescriptor; - haveOwnPropertyDescriptor: OwnPropertyDescriptor; - length: Length; - lengthOf: Length; - match: Match; - matches: Match; - string(string: string, message?: string): Assertion; - keys: Keys; - key(string: string): Assertion; - throw: Throw; - throws: Throw; - Throw: Throw; - respondTo: RespondTo; - respondsTo: RespondTo; - itself: Assertion; - satisfy: Satisfy; - satisfies: Satisfy; - closeTo: CloseTo; - approximately: CloseTo; - members: Members; - increase: PropertyChange; - increases: PropertyChange; - decrease: PropertyChange; - decreases: PropertyChange; - change: PropertyChange; - changes: PropertyChange; - extensible: Assertion; - sealed: Assertion; - frozen: Assertion; - oneOf(list: any[], message?: string): Assertion; - } - - interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; - } - - interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; - } - - interface NumberComparer { - (value: number, message?: string): Assertion; - } - - interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; - } - - interface InstanceOf { - (constructor: Object, message?: string): Assertion; - } - - interface CloseTo { - (expected: number, delta: number, message?: string): Assertion; - } - - interface Deep { - equal: Equal; - include: Include; - property: Property; - members: Members; - } - - interface KeyFilter { - keys: Keys; - } - - interface Equal { - (value: any, message?: string): Assertion; - } - - interface Property { - (name: string, value?: any, message?: string): Assertion; - } - - interface OwnProperty { - (name: string, message?: string): Assertion; - } - - interface OwnPropertyDescriptor { - (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; - (name: string, message?: string): Assertion; - } - - interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; - } - - interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; - keys: Keys; - members: Members; - any: KeyFilter; - all: KeyFilter; - } - - interface Match { - (regexp: RegExp|string, message?: string): Assertion; - } - - interface Keys { - (...keys: string[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; - } - - interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; - } - - interface RespondTo { - (method: string, message?: string): Assertion; - } - - interface Satisfy { - (matcher: Function, message?: string): Assertion; - } - - interface Members { - (set: any[], message?: string): Assertion; - } - - interface PropertyChange { - (object: Object, prop: string, msg?: string): Assertion; - } - - export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - - ok(val: any, msg?: string): void; - isOk(val: any, msg?: string): void; - notOk(val: any, msg?: string): void; - isNotOk(val: any, msg?: string): void; - - equal(act: any, exp: any, msg?: string): void; - notEqual(act: any, exp: any, msg?: string): void; - - strictEqual(act: any, exp: any, msg?: string): void; - notStrictEqual(act: any, exp: any, msg?: string): void; - - deepEqual(act: any, exp: any, msg?: string): void; - notDeepEqual(act: any, exp: any, msg?: string): void; - - isTrue(val: any, msg?: string): void; - isFalse(val: any, msg?: string): void; - - isNotTrue(val: any, msg?: string): void; - isNotFalse(val: any, msg?: string): void; - - isNull(val: any, msg?: string): void; - isNotNull(val: any, msg?: string): void; - - isUndefined(val: any, msg?: string): void; - isDefined(val: any, msg?: string): void; - - isNaN(val: any, msg?: string): void; - isNotNaN(val: any, msg?: string): void; - - isAbove(val: number, abv: number, msg?: string): void; - isBelow(val: number, blw: number, msg?: string): void; - - isAtLeast(val: number, atlst: number, msg?: string): void; - isAtMost(val: number, atmst: number, msg?: string): void; - - isFunction(val: any, msg?: string): void; - isNotFunction(val: any, msg?: string): void; - - isObject(val: any, msg?: string): void; - isNotObject(val: any, msg?: string): void; - - isArray(val: any, msg?: string): void; - isNotArray(val: any, msg?: string): void; - - isString(val: any, msg?: string): void; - isNotString(val: any, msg?: string): void; - - isNumber(val: any, msg?: string): void; - isNotNumber(val: any, msg?: string): void; - - isBoolean(val: any, msg?: string): void; - isNotBoolean(val: any, msg?: string): void; - - typeOf(val: any, type: string, msg?: string): void; - notTypeOf(val: any, type: string, msg?: string): void; - - instanceOf(val: any, type: Function, msg?: string): void; - notInstanceOf(val: any, type: Function, msg?: string): void; - - include(exp: string, inc: any, msg?: string): void; - include(exp: any[], inc: any, msg?: string): void; - - notInclude(exp: string, inc: any, msg?: string): void; - notInclude(exp: any[], inc: any, msg?: string): void; - - match(exp: any, re: RegExp, msg?: string): void; - notMatch(exp: any, re: RegExp, msg?: string): void; - - property(obj: Object, prop: string, msg?: string): void; - notProperty(obj: Object, prop: string, msg?: string): void; - deepProperty(obj: Object, prop: string, msg?: string): void; - notDeepProperty(obj: Object, prop: string, msg?: string): void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - lengthOf(exp: any, len: number, msg?: string): void; - //alias frenzy - throw(fn: Function, msg?: string): void; - throw(fn: Function, regExp: RegExp): void; - throw(fn: Function, errType: Function, msg?: string): void; - throw(fn: Function, errType: Function, regExp: RegExp): void; - - throws(fn: Function, msg?: string): void; - throws(fn: Function, regExp: RegExp): void; - throws(fn: Function, errType: Function, msg?: string): void; - throws(fn: Function, errType: Function, regExp: RegExp): void; - - Throw(fn: Function, msg?: string): void; - Throw(fn: Function, regExp: RegExp): void; - Throw(fn: Function, errType: Function, msg?: string): void; - Throw(fn: Function, errType: Function, regExp: RegExp): void; - - doesNotThrow(fn: Function, msg?: string): void; - doesNotThrow(fn: Function, regExp: RegExp): void; - doesNotThrow(fn: Function, errType: Function, msg?: string): void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - - operator(val: any, operator: string, val2: any, msg?: string): void; - closeTo(act: number, exp: number, delta: number, msg?: string): void; - approximately(act: number, exp: number, delta: number, msg?: string): void; - - sameMembers(set1: any[], set2: any[], msg?: string): void; - sameDeepMembers(set1: any[], set2: any[], msg?: string): void; - includeMembers(superset: any[], subset: any[], msg?: string): void; - - ifError(val: any, msg?: string): void; - - isExtensible(obj: {}, msg?: string): void; - extensible(obj: {}, msg?: string): void; - isNotExtensible(obj: {}, msg?: string): void; - notExtensible(obj: {}, msg?: string): void; - - isSealed(obj: {}, msg?: string): void; - sealed(obj: {}, msg?: string): void; - isNotSealed(obj: {}, msg?: string): void; - notSealed(obj: {}, msg?: string): void; - - isFrozen(obj: Object, msg?: string): void; - frozen(obj: Object, msg?: string): void; - isNotFrozen(obj: Object, msg?: string): void; - notFrozen(obj: Object, msg?: string): void; - - oneOf(inList: any, list: any[], msg?: string): void; - } - - export interface Config { - includeStack: boolean; - } - - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } -} - -declare var chai: Chai.ChaiStatic; - -declare module "chai" { - export = chai; -} - -interface Object { - should: Chai.Assertion; -} +// Type definitions for chai 3.4.0 +// Project: http://chaijs.com/ +// Definitions by: Jed Mao , +// Bart van der Schoor , +// Andrew Brown , +// Olivier Chevet , +// Matt Wistrand +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// + +declare module Chai { + + interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: (chai: any, utils: any) => void): ChaiStatic; + assert: AssertStatic; + config: Config; + AssertionError: typeof AssertionError; + } + + export interface ExpectStatic extends AssertionStatic { + fail(actual?: any, expected?: any, message?: string, operator?: string): void; + } + + export interface AssertStatic extends Assert { + } + + export interface AssertionStatic { + (target: any, message?: string): Assertion; + } + + interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(actual: any, expected: any, message?: string, operator?: string): void; + } + + interface ShouldThrow { + (actual: Function): void; + (actual: Function, expected: string|RegExp, message?: string): void; + (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; + } + + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + any: KeyFilter; + all: KeyFilter; + a: TypeComparison; + an: TypeComparison; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + property: Property; + ownProperty: OwnProperty; + haveOwnProperty: OwnProperty; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo: CloseTo; + approximately: CloseTo; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + oneOf(list: any[], message?: string): Assertion; + } + + interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + } + + interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + } + + interface NumberComparer { + (value: number, message?: string): Assertion; + } + + interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + interface InstanceOf { + (constructor: Object, message?: string): Assertion; + } + + interface CloseTo { + (expected: number, delta: number, message?: string): Assertion; + } + + interface Deep { + equal: Equal; + include: Include; + property: Property; + members: Members; + } + + interface KeyFilter { + keys: Keys; + } + + interface Equal { + (value: any, message?: string): Assertion; + } + + interface Property { + (name: string, value?: any, message?: string): Assertion; + } + + interface OwnProperty { + (name: string, message?: string): Assertion; + } + + interface OwnPropertyDescriptor { + (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string, message?: string): Assertion; + } + + interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + interface Include { + (value: Object, message?: string): Assertion; + (value: string, message?: string): Assertion; + (value: number, message?: string): Assertion; + keys: Keys; + members: Members; + any: KeyFilter; + all: KeyFilter; + } + + interface Match { + (regexp: RegExp|string, message?: string): Assertion; + } + + interface Keys { + (...keys: string[]): Assertion; + (keys: any[]): Assertion; + (keys: Object): Assertion; + } + + interface Throw { + (): Assertion; + (expected: string, message?: string): Assertion; + (expected: RegExp, message?: string): Assertion; + (constructor: Error, expected?: string, message?: string): Assertion; + (constructor: Error, expected?: RegExp, message?: string): Assertion; + (constructor: Function, expected?: string, message?: string): Assertion; + (constructor: Function, expected?: RegExp, message?: string): Assertion; + } + + interface RespondTo { + (method: string, message?: string): Assertion; + } + + interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + interface Members { + (set: any[], message?: string): Assertion; + } + + interface PropertyChange { + (object: Object, prop: string, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string): void; + + ok(val: any, msg?: string): void; + isOk(val: any, msg?: string): void; + notOk(val: any, msg?: string): void; + isNotOk(val: any, msg?: string): void; + + equal(act: any, exp: any, msg?: string): void; + notEqual(act: any, exp: any, msg?: string): void; + + strictEqual(act: any, exp: any, msg?: string): void; + notStrictEqual(act: any, exp: any, msg?: string): void; + + deepEqual(act: any, exp: any, msg?: string): void; + notDeepEqual(act: any, exp: any, msg?: string): void; + + isTrue(val: any, msg?: string): void; + isFalse(val: any, msg?: string): void; + + isNotTrue(val: any, msg?: string): void; + isNotFalse(val: any, msg?: string): void; + + isNull(val: any, msg?: string): void; + isNotNull(val: any, msg?: string): void; + + isUndefined(val: any, msg?: string): void; + isDefined(val: any, msg?: string): void; + + isNaN(val: any, msg?: string): void; + isNotNaN(val: any, msg?: string): void; + + isAbove(val: number, abv: number, msg?: string): void; + isBelow(val: number, blw: number, msg?: string): void; + + isAtLeast(val: number, atlst: number, msg?: string): void; + isAtMost(val: number, atmst: number, msg?: string): void; + + isFunction(val: any, msg?: string): void; + isNotFunction(val: any, msg?: string): void; + + isObject(val: any, msg?: string): void; + isNotObject(val: any, msg?: string): void; + + isArray(val: any, msg?: string): void; + isNotArray(val: any, msg?: string): void; + + isString(val: any, msg?: string): void; + isNotString(val: any, msg?: string): void; + + isNumber(val: any, msg?: string): void; + isNotNumber(val: any, msg?: string): void; + + isBoolean(val: any, msg?: string): void; + isNotBoolean(val: any, msg?: string): void; + + typeOf(val: any, type: string, msg?: string): void; + notTypeOf(val: any, type: string, msg?: string): void; + + instanceOf(val: any, type: Function, msg?: string): void; + notInstanceOf(val: any, type: Function, msg?: string): void; + + include(exp: string, inc: any, msg?: string): void; + include(exp: any[], inc: any, msg?: string): void; + + notInclude(exp: string, inc: any, msg?: string): void; + notInclude(exp: any[], inc: any, msg?: string): void; + + match(exp: any, re: RegExp, msg?: string): void; + notMatch(exp: any, re: RegExp, msg?: string): void; + + property(obj: Object, prop: string, msg?: string): void; + notProperty(obj: Object, prop: string, msg?: string): void; + deepProperty(obj: Object, prop: string, msg?: string): void; + notDeepProperty(obj: Object, prop: string, msg?: string): void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string): void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + lengthOf(exp: any, len: number, msg?: string): void; + //alias frenzy + throw(fn: Function, msg?: string): void; + throw(fn: Function, regExp: RegExp): void; + throw(fn: Function, errType: Function, msg?: string): void; + throw(fn: Function, errType: Function, regExp: RegExp): void; + + throws(fn: Function, msg?: string): void; + throws(fn: Function, regExp: RegExp): void; + throws(fn: Function, errType: Function, msg?: string): void; + throws(fn: Function, errType: Function, regExp: RegExp): void; + + Throw(fn: Function, msg?: string): void; + Throw(fn: Function, regExp: RegExp): void; + Throw(fn: Function, errType: Function, msg?: string): void; + Throw(fn: Function, errType: Function, regExp: RegExp): void; + + doesNotThrow(fn: Function, msg?: string): void; + doesNotThrow(fn: Function, regExp: RegExp): void; + doesNotThrow(fn: Function, errType: Function, msg?: string): void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; + + operator(val: any, operator: string, val2: any, msg?: string): void; + closeTo(act: number, exp: number, delta: number, msg?: string): void; + approximately(act: number, exp: number, delta: number, msg?: string): void; + + sameMembers(set1: any[], set2: any[], msg?: string): void; + sameDeepMembers(set1: any[], set2: any[], msg?: string): void; + includeMembers(superset: any[], subset: any[], msg?: string): void; + + ifError(val: any, msg?: string): void; + + isExtensible(obj: {}, msg?: string): void; + extensible(obj: {}, msg?: string): void; + isNotExtensible(obj: {}, msg?: string): void; + notExtensible(obj: {}, msg?: string): void; + + isSealed(obj: {}, msg?: string): void; + sealed(obj: {}, msg?: string): void; + isNotSealed(obj: {}, msg?: string): void; + notSealed(obj: {}, msg?: string): void; + + isFrozen(obj: Object, msg?: string): void; + frozen(obj: Object, msg?: string): void; + isNotFrozen(obj: Object, msg?: string): void; + notFrozen(obj: Object, msg?: string): void; + + oneOf(inList: any, list: any[], msg?: string): void; + } + + export interface Config { + includeStack: boolean; + } + + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } +} + +declare var chai: Chai.ChaiStatic; + +declare module "chai" { + export = chai; +} + +interface Object { + should: Chai.Assertion; +} diff --git a/checksum/checksum-tests.ts b/checksum/checksum-tests.ts index de9faaa98..2746bcb9e 100644 --- a/checksum/checksum-tests.ts +++ b/checksum/checksum-tests.ts @@ -1,14 +1,14 @@ -/// - -import checksum = require("checksum"); - -var s: string = checksum("abcd"); -var t: string = checksum("abcd", { algorithm: 'sha1' }); - -checksum.file("myfile.txt", (error: Error, hash: string): void => { - // do nothing -}); - -checksum.file("myfile.txt", { algorithm: 'sha1' }, (error: Error, hash: string): void => { - // do nothing -}); +/// + +import checksum = require("checksum"); + +var s: string = checksum("abcd"); +var t: string = checksum("abcd", { algorithm: 'sha1' }); + +checksum.file("myfile.txt", (error: Error, hash: string): void => { + // do nothing +}); + +checksum.file("myfile.txt", { algorithm: 'sha1' }, (error: Error, hash: string): void => { + // do nothing +}); diff --git a/checksum/checksum.d.ts b/checksum/checksum.d.ts index 63f24224e..45974a061 100644 --- a/checksum/checksum.d.ts +++ b/checksum/checksum.d.ts @@ -1,44 +1,44 @@ -// Type definitions for checksum 0.1.1 -// Project: https://github.com/dshaw/checksum -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "checksum" { - - module checksum { - /** - * Options object for all functions - */ - interface ChecksumOptions { - /** - * Algorithm to use, default 'sha1' - * Can be 'sha1' or 'md5' (see module 'crypto'). - */ - algorithm?: string; - } - - /** - * Generate the checksum for a file on disk - * @param filename The file name - * @param callback Callback which is called with the result or an error - */ - function file(filename: string, callback: (error: Error, hash: string) => void): void; - /** - * Generate the checksum for a file on disk - * @param filename The file name - * @param options Options object to indicate hash algo - * @param callback Callback which is called with the result or an error - */ - function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void; - } - - /** - * Generates a checksum for the given value - * @param value Any value - * @param options Allows to set the algorithm - * @returns Checksum - */ - function checksum(value: any, options?: checksum.ChecksumOptions): string; - - export = checksum; -} +// Type definitions for checksum 0.1.1 +// Project: https://github.com/dshaw/checksum +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "checksum" { + + module checksum { + /** + * Options object for all functions + */ + interface ChecksumOptions { + /** + * Algorithm to use, default 'sha1' + * Can be 'sha1' or 'md5' (see module 'crypto'). + */ + algorithm?: string; + } + + /** + * Generate the checksum for a file on disk + * @param filename The file name + * @param callback Callback which is called with the result or an error + */ + function file(filename: string, callback: (error: Error, hash: string) => void): void; + /** + * Generate the checksum for a file on disk + * @param filename The file name + * @param options Options object to indicate hash algo + * @param callback Callback which is called with the result or an error + */ + function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void; + } + + /** + * Generates a checksum for the given value + * @param value Any value + * @param options Allows to set the algorithm + * @returns Checksum + */ + function checksum(value: any, options?: checksum.ChecksumOptions): string; + + export = checksum; +} diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index cb74619d4..c1b5eda89 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -1,294 +1,294 @@ -/// - -import * as cheerio from 'cheerio'; - -/* - * LOADING - */ -let html = -`
    -
  • Apple
  • -
  • Orange
  • -
  • Pear
  • - -
`; - -// Preferred Method -var $ = cheerio.load(html); -// Directly load element -cheerio(html); -cheerio('ul', html); -cheerio('li', 'ul', html); - -$ = cheerio.load(html, { - normalizeWhitespace: true, - xmlMode: true -}); - -$ = cheerio.load(html, { - normalizeWhitespace: true, - xmlMode: true, - decodeEntities: true, - lowerCaseTags: true, - lowerCaseAttributeNames: true, - recognizeCDATA: true, - recognizeSelfClosing: true -}); - -/** - * Selectors - */ -var $el = $('.class'); -var $multiEl = $('selector', 'selector', 'selector'); - -/** - * Attributes - */ - -// attr -$el.attr('id'); -$el.attr('id', 'favorite').html(); - -// data -$el.data(); -$el.data('apple-color'); -$el.data('kind', 'mac'); - -// val -$('input[type="text"]').val(); -$('input[type="text"]').val('test').html(); - -// removeAttr -$el.removeAttr('class').html(); - -// hasClass, addClass, removeClass, toggleClass -$el.addClass('class').addClass('test'); -$el.hasClass('test'); -$el.removeClass('class').removeClass('test'); -$el.addClass('red').removeClass().html(); -$el.toggleClass('fruit green red').html(); - -// is -$el.is('#id'); -$el.is($el); -$el.is(() => { - return true; -}); - -/** - * Forms - */ -// serializeArray -$('
').serializeArray(); - -/** - * Traversing - */ - // find -$el.find('li').length; -$el.find($('.apple')).length; - -// .parent([selector]) -$el.parent().attr('id'); -$el.parent('.class').attr('id'); - -// .parents([selector]) -$el.parents().length; -$el.parents('.class').length; - -// .parentsUntil([selector][,filter]) -$el.parentsUntil().length; -$el.parentsUntil('.class').length; - -// .closest(selector) -$el.closest(); -$el.closest('.class'); - -// .next([selector]) -$el.next().hasClass('class'); -$el.next('.class').hasClass('class'); - -// .nextAll([selector]) -$el.nextAll().length; -$el.nextAll('.class').length; - -// .nextUntil([selector], [filter]) -$el.nextUntil(); -$el.nextUntil('.class'); - -// .prev([selector]) -$el.prev().hasClass('class'); -$el.prev('.class').hasClass('class'); - -// .prevAll([selector]) -$el.prevAll().length; -$el.prevAll('.class').length; - -// .prevUntil([selector], [filter]) -$el.prevUntil(); -$el.prevUntil('.class'); - -// .slice( start, [end] ) -$el.slice(1).eq(0).text(); -$el.slice(1, 2).length; - -// .siblings([selector]) -$el.siblings().length; -$el.siblings('.class').length; - -// .children([selector]) -$el.children().length; -$el.children('.class').text(); - -// .contents() -$el.contents().length; - -// .each( function(index, element) ) -$el.each((i, el) => { - $(el).html(); -}); - -// .map( function(index, element) ) -$el.map((i, el) => { - return $(el).text(); -}).get().join(' '); - -// .filter -$ = cheerio.load(html); -$el.filter('.class').attr('class'); -$el.filter($('.class')).attr('class'); -$el.filter($('.class')[0]).attr('class'); - -$el.filter((i, el) => { - return $(el).attr('class') === 'class'; -}).attr('class'); - -// .not -$el.not('.class').length; -$el.not($('.class')).length; -$el.not($('.class')[0]).length; - -$el.not((i, el) => { - return $(el).attr('class') === 'class'; -}).length; - -// .has -$el.has('.class').attr('id'); -$el.has($el[0]).attr('id'); - -// .first() -$el.children().first().text(); - -// .last() -$el.children().last().text(); - -// .eq( i ) -$el.eq(0).text(); -$el.eq(-1).text(); - -// .get( [i] ) -$el.get(0).tagName; -$el.get().length; - -// .index() -// .index( selector ) -// .index( nodeOrSelection ) -$el.index(); -$el.index('li'); -$el.index($('#fruit, li')); - -// .end() -$el.eq(0).end().length; - -// .add -$el.add('.class').length - -// .addBack( [filter] ) -$el.eq(0).addBack().length -$el.eq(0).addBack('.class').length - -/** - * Manipulation - */ - -// .append( content, [content, ...] ) -$el.append('
  • Plum
  • ').html(); -$el.append('
  • Plum
  • ', '
  • Plum
  • ').html(); - -// .prepend( content, [content, ...] ) -$el.prepend('
  • Plum
  • ').html(); -$el.prepend('
  • Plum
  • ', '
  • Plum
  • ').html(); - -// .after( content, [content, ...] ) -$el.after('
  • Plum
  • ').html(); -$el.after('
  • Plum
  • ', '
  • Plum
  • ').html(); - -// .insertAfter( content ) -$('
  • Plum
  • ').insertAfter('.class').html(); - -// .before( content, [content, ...] ) -$el.before('
  • Plum
  • ').html(); -$el.before('
  • Plum
  • ', '
  • Plum
  • ').html(); - -// .insertBefore( content ) -$('
  • Plum
  • ').insertBefore('.class').html(); - -// .remove( [selector] ) -$el.remove().html(); -$el.remove('.class').html(); - -// .replaceWith( content ) -$el.replaceWith($('
  • Plum
  • ')).html(); - -// .empty() -$el.empty().html(); - -// .html( [htmlString] ) -$el.html(); -$el.html('
  • Mango
  • ').html(); - -// .text( [textString] ) -$el.text(); -$el.text('text'); - -// .wrap( content ) -// See https://github.com/cheeriojs/cheerio/issues/731 -// $el.wrap($('
    ')).html(); - -// .css -$el.css('width'); -$el.css(['width', 'height']); -$el.css('width', '50px'); - -/** - * Rendering - */ -$.html(); -$.html('.class'); -$.xml(); - -/** - * Miscellaneous - */ - -// .clone() #### -$el.clone().html(); - -/** - * Utilities - */ - -// $.root -$.root().append('
      ').html(); - -// $.contains( container, contained ) -$.contains($el[0], $el[0]); - -// $.parseHTML( data [, context ] [, keepScripts ] ) -$.parseHTML(html); -$.parseHTML(html, null, true); - -/** - * Not in doc - */ -$el.toArray(); +/// + +import * as cheerio from 'cheerio'; + +/* + * LOADING + */ +let html = +`
        +
      • Apple
      • +
      • Orange
      • +
      • Pear
      • + +
      `; + +// Preferred Method +var $ = cheerio.load(html); +// Directly load element +cheerio(html); +cheerio('ul', html); +cheerio('li', 'ul', html); + +$ = cheerio.load(html, { + normalizeWhitespace: true, + xmlMode: true +}); + +$ = cheerio.load(html, { + normalizeWhitespace: true, + xmlMode: true, + decodeEntities: true, + lowerCaseTags: true, + lowerCaseAttributeNames: true, + recognizeCDATA: true, + recognizeSelfClosing: true +}); + +/** + * Selectors + */ +var $el = $('.class'); +var $multiEl = $('selector', 'selector', 'selector'); + +/** + * Attributes + */ + +// attr +$el.attr('id'); +$el.attr('id', 'favorite').html(); + +// data +$el.data(); +$el.data('apple-color'); +$el.data('kind', 'mac'); + +// val +$('input[type="text"]').val(); +$('input[type="text"]').val('test').html(); + +// removeAttr +$el.removeAttr('class').html(); + +// hasClass, addClass, removeClass, toggleClass +$el.addClass('class').addClass('test'); +$el.hasClass('test'); +$el.removeClass('class').removeClass('test'); +$el.addClass('red').removeClass().html(); +$el.toggleClass('fruit green red').html(); + +// is +$el.is('#id'); +$el.is($el); +$el.is(() => { + return true; +}); + +/** + * Forms + */ +// serializeArray +$('
      ').serializeArray(); + +/** + * Traversing + */ + // find +$el.find('li').length; +$el.find($('.apple')).length; + +// .parent([selector]) +$el.parent().attr('id'); +$el.parent('.class').attr('id'); + +// .parents([selector]) +$el.parents().length; +$el.parents('.class').length; + +// .parentsUntil([selector][,filter]) +$el.parentsUntil().length; +$el.parentsUntil('.class').length; + +// .closest(selector) +$el.closest(); +$el.closest('.class'); + +// .next([selector]) +$el.next().hasClass('class'); +$el.next('.class').hasClass('class'); + +// .nextAll([selector]) +$el.nextAll().length; +$el.nextAll('.class').length; + +// .nextUntil([selector], [filter]) +$el.nextUntil(); +$el.nextUntil('.class'); + +// .prev([selector]) +$el.prev().hasClass('class'); +$el.prev('.class').hasClass('class'); + +// .prevAll([selector]) +$el.prevAll().length; +$el.prevAll('.class').length; + +// .prevUntil([selector], [filter]) +$el.prevUntil(); +$el.prevUntil('.class'); + +// .slice( start, [end] ) +$el.slice(1).eq(0).text(); +$el.slice(1, 2).length; + +// .siblings([selector]) +$el.siblings().length; +$el.siblings('.class').length; + +// .children([selector]) +$el.children().length; +$el.children('.class').text(); + +// .contents() +$el.contents().length; + +// .each( function(index, element) ) +$el.each((i, el) => { + $(el).html(); +}); + +// .map( function(index, element) ) +$el.map((i, el) => { + return $(el).text(); +}).get().join(' '); + +// .filter +$ = cheerio.load(html); +$el.filter('.class').attr('class'); +$el.filter($('.class')).attr('class'); +$el.filter($('.class')[0]).attr('class'); + +$el.filter((i, el) => { + return $(el).attr('class') === 'class'; +}).attr('class'); + +// .not +$el.not('.class').length; +$el.not($('.class')).length; +$el.not($('.class')[0]).length; + +$el.not((i, el) => { + return $(el).attr('class') === 'class'; +}).length; + +// .has +$el.has('.class').attr('id'); +$el.has($el[0]).attr('id'); + +// .first() +$el.children().first().text(); + +// .last() +$el.children().last().text(); + +// .eq( i ) +$el.eq(0).text(); +$el.eq(-1).text(); + +// .get( [i] ) +$el.get(0).tagName; +$el.get().length; + +// .index() +// .index( selector ) +// .index( nodeOrSelection ) +$el.index(); +$el.index('li'); +$el.index($('#fruit, li')); + +// .end() +$el.eq(0).end().length; + +// .add +$el.add('.class').length + +// .addBack( [filter] ) +$el.eq(0).addBack().length +$el.eq(0).addBack('.class').length + +/** + * Manipulation + */ + +// .append( content, [content, ...] ) +$el.append('
    • Plum
    • ').html(); +$el.append('
    • Plum
    • ', '
    • Plum
    • ').html(); + +// .prepend( content, [content, ...] ) +$el.prepend('
    • Plum
    • ').html(); +$el.prepend('
    • Plum
    • ', '
    • Plum
    • ').html(); + +// .after( content, [content, ...] ) +$el.after('
    • Plum
    • ').html(); +$el.after('
    • Plum
    • ', '
    • Plum
    • ').html(); + +// .insertAfter( content ) +$('
    • Plum
    • ').insertAfter('.class').html(); + +// .before( content, [content, ...] ) +$el.before('
    • Plum
    • ').html(); +$el.before('
    • Plum
    • ', '
    • Plum
    • ').html(); + +// .insertBefore( content ) +$('
    • Plum
    • ').insertBefore('.class').html(); + +// .remove( [selector] ) +$el.remove().html(); +$el.remove('.class').html(); + +// .replaceWith( content ) +$el.replaceWith($('
    • Plum
    • ')).html(); + +// .empty() +$el.empty().html(); + +// .html( [htmlString] ) +$el.html(); +$el.html('
    • Mango
    • ').html(); + +// .text( [textString] ) +$el.text(); +$el.text('text'); + +// .wrap( content ) +// See https://github.com/cheeriojs/cheerio/issues/731 +// $el.wrap($('
      ')).html(); + +// .css +$el.css('width'); +$el.css(['width', 'height']); +$el.css('width', '50px'); + +/** + * Rendering + */ +$.html(); +$.html('.class'); +$.xml(); + +/** + * Miscellaneous + */ + +// .clone() #### +$el.clone().html(); + +/** + * Utilities + */ + +// $.root +$.root().append('
        ').html(); + +// $.contains( container, contained ) +$.contains($el[0], $el[0]); + +// $.parseHTML( data [, context ] [, keepScripts ] ) +$.parseHTML(html); +$.parseHTML(html, null, true); + +/** + * Not in doc + */ +$el.toArray(); diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index 3b5b998d9..124dae5d9 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,266 +1,266 @@ -// Type definitions for Cheerio v0.17.0 -// Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little , VILIC VANE , Wayne Maurer -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Cheerio { - // Document References - // Cheerio https://github.com/cheeriojs/cheerio - // JQuery http://api.jquery.com - - [index: number]: CheerioElement; - length: number; - - // Attributes - - attr(name: string): string; - attr(name: string, value: any): Cheerio; - - data(): any; - data(name: string): any; - data(name: string, value: any): any; - - val(): string; - val(value: string): Cheerio; - - removeAttr(name: string): Cheerio; - - has(selector: string): Cheerio; - has(element: CheerioElement): Cheerio; - - hasClass(className: string): boolean; - addClass(classNames: string): Cheerio; - - removeClass(): Cheerio; - removeClass(className: string): Cheerio; - removeClass(func: (index: number, className: string) => string): Cheerio; - - toggleClass(className: string): Cheerio; - toggleClass(className: string, toggleSwitch: boolean): Cheerio; - toggleClass(toggleSwitch?: boolean): Cheerio; - toggleClass(func: (index: number, className: string, toggleSwitch: boolean) => string, toggleSwitch?: boolean): Cheerio; - - is(selector: string): boolean; - is(element: CheerioElement): boolean; - is(element: CheerioElement[]): boolean; - is(selection: Cheerio): boolean; - is(func: (index: number, element: CheerioElement) => boolean): boolean; - - // Form - serializeArray(): {name: string, value: string}[]; - - // Traversing - - find(selector: string): Cheerio; - find(element: Cheerio): Cheerio; - - parent(selector?: string): Cheerio; - parents(selector?: string): Cheerio; - parentsUntil(selector?: string, filter?: string): Cheerio; - parentsUntil(element: CheerioElement, filter?: string): Cheerio; - parentsUntil(element: Cheerio, filter?: string): Cheerio; - - closest(): Cheerio; - closest(selector: string): Cheerio; - - next(selector?: string): Cheerio; - nextAll(): Cheerio; - nextAll(selector: string): Cheerio; - - nextUntil(selector?: string, filter?: string): Cheerio; - nextUntil(element: CheerioElement, filter?: string): Cheerio; - nextUntil(element: Cheerio, filter?: string): Cheerio; - - prev(selector?: string): Cheerio; - prevAll(): Cheerio; - prevAll(selector: string): Cheerio; - - prevUntil(selector?: string, filter?: string): Cheerio; - prevUntil(element: CheerioElement, filter?: string): Cheerio; - prevUntil(element: Cheerio, filter?: string): Cheerio; - - slice(start: number, end?: number): Cheerio; - - siblings(selector?: string): Cheerio; - - children(selector?: string): Cheerio; - - contents(): Cheerio; - - each(func: (index: number, element: CheerioElement) => any): Cheerio; - map(func: (index: number, element: CheerioElement) => any): Cheerio; - - filter(selector: string): Cheerio; - filter(selection: Cheerio): Cheerio; - filter(element: CheerioElement): Cheerio; - filter(elements: CheerioElement[]): Cheerio; - filter(func: (index: number, element: CheerioElement) => boolean): Cheerio; - - not(selector: string): Cheerio; - not(selection: Cheerio): Cheerio; - not(element: CheerioElement): Cheerio; - not(func: (index: number, element: CheerioElement) => boolean): Cheerio; - - first(): Cheerio; - last(): Cheerio; - - eq(index: number): Cheerio; - - get(): CheerioElement[]; - get(index: number): CheerioElement; - - index(): number; - index(selector: string): number; - index(selection: Cheerio): number; - - end(): Cheerio; - - add(selectorOrHtml: string): Cheerio; - add(selector: string, context: Document): Cheerio; - add(element: CheerioElement): Cheerio; - add(elements: CheerioElement[]): Cheerio; - add(selection: Cheerio): Cheerio; - - addBack():Cheerio; - addBack(filter: string):Cheerio; - - // Manipulation - - append(content: string, ...contents: any[]): Cheerio; - append(content: Document, ...contents: any[]): Cheerio; - append(content: Document[], ...contents: any[]): Cheerio; - append(content: Cheerio, ...contents: any[]): Cheerio; - - prepend(content: string, ...contents: any[]): Cheerio; - prepend(content: Document, ...contents: any[]): Cheerio; - prepend(content: Document[], ...contents: any[]): Cheerio; - prepend(content: Cheerio, ...contents: any[]): Cheerio; - - after(content: string, ...contents: any[]): Cheerio; - after(content: Document, ...contents: any[]): Cheerio; - after(content: Document[], ...contents: any[]): Cheerio; - after(content: Cheerio, ...contents: any[]): Cheerio; - - insertAfter(content: string): Cheerio; - insertAfter(content: Document): Cheerio; - insertAfter(content: Cheerio): Cheerio; - - before(content: string, ...contents: any[]): Cheerio; - before(content: Document, ...contents: any[]): Cheerio; - before(content: Document[], ...contents: any[]): Cheerio; - before(content: Cheerio, ...contents: any[]): Cheerio; - - insertBefore(content: string): Cheerio; - insertBefore(content: Document): Cheerio; - insertBefore(content: Cheerio): Cheerio; - - remove(selector?: string): Cheerio; - - replaceWith(content: string): Cheerio; - replaceWith(content: CheerioElement): Cheerio; - replaceWith(content: CheerioElement[]): Cheerio; - replaceWith(content: Cheerio): Cheerio; - - empty(): Cheerio; - - html(): string; - html(html: string): Cheerio; - - text(): string; - text(text: string): Cheerio; - - // See https://github.com/cheeriojs/cheerio/issues/731 - /*wrap(content: string): Cheerio; - wrap(content: Document): Cheerio; - wrap(content: Cheerio): Cheerio;*/ - - css(propertyName: string): string; - css(propertyNames: string[]): string[]; - css(propertyName: string, value: string): Cheerio; - css(propertyName: string, value: number): Cheerio; - css(propertyName: string, func: (index: number, value: string) => string): Cheerio; - css(propertyName: string, func: (index: number, value: string) => number): Cheerio; - css(properties: Object): Cheerio; - - // Rendering - - // Miscellaneous - - clone(): Cheerio; - - // Not Documented - - toArray(): CheerioElement[]; -} - -interface CheerioOptionsInterface { - // Document References - // Cheerio https://github.com/cheeriojs/cheerio - // HTMLParser2 https://github.com/fb55/htmlparser2/wiki/Parser-options - // DomHandler https://github.com/fb55/DomHandler - - xmlMode?: boolean; - decodeEntities?: boolean; - lowerCaseTags?: boolean; - lowerCaseAttributeNames?: boolean; - recognizeCDATA?: boolean; - recognizeSelfClosing?: boolean; - normalizeWhitespace?: boolean; -} - -interface CheerioSelector { - (selector: string): Cheerio; - (selector: string, context: string): Cheerio; - (selector: string, context: CheerioElement): Cheerio; - (selector: string, context: CheerioElement[]): Cheerio; - (selector: string, context: Cheerio): Cheerio; - (selector: string, context: string, root: string): Cheerio; - (selector: string, context: CheerioElement, root: string): Cheerio; - (selector: string, context: CheerioElement[], root: string): Cheerio; - (selector: string, context: Cheerio, root: string): Cheerio; - (selector: any): Cheerio; -} - -interface CheerioStatic extends CheerioSelector { - // Document References - // Cheerio https://github.com/cheeriojs/cheerio - // JQuery http://api.jquery.com - xml(): string; - root(): Cheerio; - contains(container: CheerioElement, contained: CheerioElement): boolean; - parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[]; - - html(options?: CheerioOptionsInterface): string; - html(selector: string, options?: CheerioOptionsInterface): string; - html(element: Cheerio, options?: CheerioOptionsInterface): string; - html(element: CheerioElement, options?: CheerioOptionsInterface): string; -} - -interface CheerioElement { - // Document References - // Node Console - tagName: string; - type: string; - name: string; - attribs: Object; - children: CheerioElement[]; - childNodes: CheerioElement[]; - lastChild: CheerioElement; - next: CheerioElement; - nextSibling: CheerioElement; - prev: CheerioElement; - previousSibling: CheerioElement; - parent: CheerioElement; - parentNode: CheerioElement; - nodeValue: string; -} - -interface CheerioAPI extends CheerioSelector { - load(html: string, options?: CheerioOptionsInterface): CheerioStatic; -} - -declare var cheerio:CheerioAPI; - -declare module "cheerio" { - export = cheerio; -} +// Type definitions for Cheerio v0.17.0 +// Project: https://github.com/cheeriojs/cheerio +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Cheerio { + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com + + [index: number]: CheerioElement; + length: number; + + // Attributes + + attr(name: string): string; + attr(name: string, value: any): Cheerio; + + data(): any; + data(name: string): any; + data(name: string, value: any): any; + + val(): string; + val(value: string): Cheerio; + + removeAttr(name: string): Cheerio; + + has(selector: string): Cheerio; + has(element: CheerioElement): Cheerio; + + hasClass(className: string): boolean; + addClass(classNames: string): Cheerio; + + removeClass(): Cheerio; + removeClass(className: string): Cheerio; + removeClass(func: (index: number, className: string) => string): Cheerio; + + toggleClass(className: string): Cheerio; + toggleClass(className: string, toggleSwitch: boolean): Cheerio; + toggleClass(toggleSwitch?: boolean): Cheerio; + toggleClass(func: (index: number, className: string, toggleSwitch: boolean) => string, toggleSwitch?: boolean): Cheerio; + + is(selector: string): boolean; + is(element: CheerioElement): boolean; + is(element: CheerioElement[]): boolean; + is(selection: Cheerio): boolean; + is(func: (index: number, element: CheerioElement) => boolean): boolean; + + // Form + serializeArray(): {name: string, value: string}[]; + + // Traversing + + find(selector: string): Cheerio; + find(element: Cheerio): Cheerio; + + parent(selector?: string): Cheerio; + parents(selector?: string): Cheerio; + parentsUntil(selector?: string, filter?: string): Cheerio; + parentsUntil(element: CheerioElement, filter?: string): Cheerio; + parentsUntil(element: Cheerio, filter?: string): Cheerio; + + closest(): Cheerio; + closest(selector: string): Cheerio; + + next(selector?: string): Cheerio; + nextAll(): Cheerio; + nextAll(selector: string): Cheerio; + + nextUntil(selector?: string, filter?: string): Cheerio; + nextUntil(element: CheerioElement, filter?: string): Cheerio; + nextUntil(element: Cheerio, filter?: string): Cheerio; + + prev(selector?: string): Cheerio; + prevAll(): Cheerio; + prevAll(selector: string): Cheerio; + + prevUntil(selector?: string, filter?: string): Cheerio; + prevUntil(element: CheerioElement, filter?: string): Cheerio; + prevUntil(element: Cheerio, filter?: string): Cheerio; + + slice(start: number, end?: number): Cheerio; + + siblings(selector?: string): Cheerio; + + children(selector?: string): Cheerio; + + contents(): Cheerio; + + each(func: (index: number, element: CheerioElement) => any): Cheerio; + map(func: (index: number, element: CheerioElement) => any): Cheerio; + + filter(selector: string): Cheerio; + filter(selection: Cheerio): Cheerio; + filter(element: CheerioElement): Cheerio; + filter(elements: CheerioElement[]): Cheerio; + filter(func: (index: number, element: CheerioElement) => boolean): Cheerio; + + not(selector: string): Cheerio; + not(selection: Cheerio): Cheerio; + not(element: CheerioElement): Cheerio; + not(func: (index: number, element: CheerioElement) => boolean): Cheerio; + + first(): Cheerio; + last(): Cheerio; + + eq(index: number): Cheerio; + + get(): CheerioElement[]; + get(index: number): CheerioElement; + + index(): number; + index(selector: string): number; + index(selection: Cheerio): number; + + end(): Cheerio; + + add(selectorOrHtml: string): Cheerio; + add(selector: string, context: Document): Cheerio; + add(element: CheerioElement): Cheerio; + add(elements: CheerioElement[]): Cheerio; + add(selection: Cheerio): Cheerio; + + addBack():Cheerio; + addBack(filter: string):Cheerio; + + // Manipulation + + append(content: string, ...contents: any[]): Cheerio; + append(content: Document, ...contents: any[]): Cheerio; + append(content: Document[], ...contents: any[]): Cheerio; + append(content: Cheerio, ...contents: any[]): Cheerio; + + prepend(content: string, ...contents: any[]): Cheerio; + prepend(content: Document, ...contents: any[]): Cheerio; + prepend(content: Document[], ...contents: any[]): Cheerio; + prepend(content: Cheerio, ...contents: any[]): Cheerio; + + after(content: string, ...contents: any[]): Cheerio; + after(content: Document, ...contents: any[]): Cheerio; + after(content: Document[], ...contents: any[]): Cheerio; + after(content: Cheerio, ...contents: any[]): Cheerio; + + insertAfter(content: string): Cheerio; + insertAfter(content: Document): Cheerio; + insertAfter(content: Cheerio): Cheerio; + + before(content: string, ...contents: any[]): Cheerio; + before(content: Document, ...contents: any[]): Cheerio; + before(content: Document[], ...contents: any[]): Cheerio; + before(content: Cheerio, ...contents: any[]): Cheerio; + + insertBefore(content: string): Cheerio; + insertBefore(content: Document): Cheerio; + insertBefore(content: Cheerio): Cheerio; + + remove(selector?: string): Cheerio; + + replaceWith(content: string): Cheerio; + replaceWith(content: CheerioElement): Cheerio; + replaceWith(content: CheerioElement[]): Cheerio; + replaceWith(content: Cheerio): Cheerio; + + empty(): Cheerio; + + html(): string; + html(html: string): Cheerio; + + text(): string; + text(text: string): Cheerio; + + // See https://github.com/cheeriojs/cheerio/issues/731 + /*wrap(content: string): Cheerio; + wrap(content: Document): Cheerio; + wrap(content: Cheerio): Cheerio;*/ + + css(propertyName: string): string; + css(propertyNames: string[]): string[]; + css(propertyName: string, value: string): Cheerio; + css(propertyName: string, value: number): Cheerio; + css(propertyName: string, func: (index: number, value: string) => string): Cheerio; + css(propertyName: string, func: (index: number, value: string) => number): Cheerio; + css(properties: Object): Cheerio; + + // Rendering + + // Miscellaneous + + clone(): Cheerio; + + // Not Documented + + toArray(): CheerioElement[]; +} + +interface CheerioOptionsInterface { + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // HTMLParser2 https://github.com/fb55/htmlparser2/wiki/Parser-options + // DomHandler https://github.com/fb55/DomHandler + + xmlMode?: boolean; + decodeEntities?: boolean; + lowerCaseTags?: boolean; + lowerCaseAttributeNames?: boolean; + recognizeCDATA?: boolean; + recognizeSelfClosing?: boolean; + normalizeWhitespace?: boolean; +} + +interface CheerioSelector { + (selector: string): Cheerio; + (selector: string, context: string): Cheerio; + (selector: string, context: CheerioElement): Cheerio; + (selector: string, context: CheerioElement[]): Cheerio; + (selector: string, context: Cheerio): Cheerio; + (selector: string, context: string, root: string): Cheerio; + (selector: string, context: CheerioElement, root: string): Cheerio; + (selector: string, context: CheerioElement[], root: string): Cheerio; + (selector: string, context: Cheerio, root: string): Cheerio; + (selector: any): Cheerio; +} + +interface CheerioStatic extends CheerioSelector { + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com + xml(): string; + root(): Cheerio; + contains(container: CheerioElement, contained: CheerioElement): boolean; + parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[]; + + html(options?: CheerioOptionsInterface): string; + html(selector: string, options?: CheerioOptionsInterface): string; + html(element: Cheerio, options?: CheerioOptionsInterface): string; + html(element: CheerioElement, options?: CheerioOptionsInterface): string; +} + +interface CheerioElement { + // Document References + // Node Console + tagName: string; + type: string; + name: string; + attribs: Object; + children: CheerioElement[]; + childNodes: CheerioElement[]; + lastChild: CheerioElement; + next: CheerioElement; + nextSibling: CheerioElement; + prev: CheerioElement; + previousSibling: CheerioElement; + parent: CheerioElement; + parentNode: CheerioElement; + nodeValue: string; +} + +interface CheerioAPI extends CheerioSelector { + load(html: string, options?: CheerioOptionsInterface): CheerioStatic; +} + +declare var cheerio:CheerioAPI; + +declare module "cheerio" { + export = cheerio; +} diff --git a/chosen/chosen-tests.ts b/chosen/chosen-tests.ts index 8f6c3d9ad..818b1e126 100644 --- a/chosen/chosen-tests.ts +++ b/chosen/chosen-tests.ts @@ -1,8 +1,8 @@ -/// - -$(".chzn-select").chosen({ no_results_text: "No results matched" }); -$("#form_field").chosen().change(); -$("#form_field").trigger("liszt:updated"); - -$(".chzn-select").chosen(); +/// + +$(".chzn-select").chosen({ no_results_text: "No results matched" }); +$("#form_field").chosen().change(); +$("#form_field").trigger("liszt:updated"); + +$(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({ allow_single_deselect: true }); \ No newline at end of file diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts index 14d37fa97..d5c636c40 100644 --- a/chosen/chosen.jquery.d.ts +++ b/chosen/chosen.jquery.d.ts @@ -1,30 +1,30 @@ -// Type definitions for Chosen.JQuery 1.4.2 -// Project: http://harvesthq.github.com/chosen/ -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -interface ChosenOptions { - allow_single_deselect?: boolean; - disable_search?: boolean; - disable_search_threshold?: number; - enable_split_word_search?: boolean; - inherit_select_classes?: boolean; - max_selected_options?: number; - no_results_text?: string; - placeholder_text_multiple?: string; - placeholder_text_single?: string; - search_contains?: boolean; - single_backstroke_delete?: boolean; - width?: number|string; - display_disabled_options?: boolean; - display_selected_options?: boolean; - include_group_label_in_selected?: boolean; -} - -interface JQuery { - chosen(): JQuery; - chosen(options: ChosenOptions): JQuery; -} +// Type definitions for Chosen.JQuery 1.4.2 +// Project: http://harvesthq.github.com/chosen/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface ChosenOptions { + allow_single_deselect?: boolean; + disable_search?: boolean; + disable_search_threshold?: number; + enable_split_word_search?: boolean; + inherit_select_classes?: boolean; + max_selected_options?: number; + no_results_text?: string; + placeholder_text_multiple?: string; + placeholder_text_single?: string; + search_contains?: boolean; + single_backstroke_delete?: boolean; + width?: number|string; + display_disabled_options?: boolean; + display_selected_options?: boolean; + include_group_label_in_selected?: boolean; +} + +interface JQuery { + chosen(): JQuery; + chosen(options: ChosenOptions): JQuery; +} diff --git a/chrome/chrome-app-tests.ts b/chrome/chrome-app-tests.ts index 466571107..c7194b523 100644 --- a/chrome/chrome-app-tests.ts +++ b/chrome/chrome-app-tests.ts @@ -117,7 +117,7 @@ function test_socketsTcp(): void { chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.tcp.SocketInfo) => { }); // getSockets - chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); + chrome.sockets.tcp.getSockets((infos: chrome.sockets.tcp.SocketInfo[]) => { }); } function test_socketsTcpEvents(): void { @@ -283,7 +283,7 @@ function test_socketsTcpServer(): void { chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); // getSockets - chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); + chrome.sockets.tcp.getSockets((infos: chrome.sockets.tcp.SocketInfo[]) => { }); } function test_socketsTcpServerEvents(): void { diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index d40fa3b2d..0152b7472 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -1,8 +1,9 @@ -// Type definitions for Chrome packaged application development +// Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ // Definitions by: Adam Lay , MIZUNE Pine , MIZUSHIMA Junki // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// /// //////////////////// @@ -22,13 +23,9 @@ declare module chrome.app.runtime { type: string; } - interface LaunchedEvent { - addListener(callback: (launchData: LaunchData) => void): void; - } + interface LaunchedEvent extends chrome.events.Event<(launchData: LaunchData) => void> {} - interface RestartedEvent { - addListener(callback: () => void): void; - } + interface RestartedEvent extends chrome.events.Event<() => void> {} var onLaunched: LaunchedEvent; var onRestarted: RestartedEvent; @@ -136,10 +133,7 @@ declare module chrome.app.window { export function getAll(): AppWindow[]; export function canSetVisibleOnAllWorkspaces(): boolean; - interface WindowEvent { - addListener(callback: () => void): void; - removeListener(callback: () => void): void; - } + interface WindowEvent extends chrome.events.Event<() => void> {} var onBoundsChanged: WindowEvent; var onClosed: WindowEvent; @@ -154,20 +148,6 @@ declare module chrome.app.window { //////////////////// declare module chrome.fileSystem { - interface ChildChangeInfo { - entry: Entry; - type: string; - } - - interface EntryChangedEvent { - target: Entry; - childChanges?: ChildChangeInfo[]; - } - - interface EntryRemovedEvent { - target: Entry; - } - interface AcceptOptions { description?: string; mimeTypes?: string[]; @@ -207,10 +187,6 @@ declare module chrome.sockets.tcp { bytesSent?: number; } - interface Event { - addListener(callback: (info: T) => void): void; - } - interface ReceiveEventArgs { socketId: number; data: ArrayBuffer; @@ -258,10 +234,10 @@ declare module chrome.sockets.tcp { export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; export function close(socketId: number, callback?: () => void): void; export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; - export function getSockets(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; - var onReceive: Event; - var onReceiveError: Event; + var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } declare module chrome.sockets.udp { @@ -274,10 +250,6 @@ declare module chrome.sockets.udp { bytesSent?: number; } - interface Event { - addListener(callback: (info: T) => void): void; - } - interface ReceiveEventArgs { socketId: number; data: ArrayBuffer; @@ -323,8 +295,8 @@ declare module chrome.sockets.udp { export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; - var onReceive: Event; - var onReceiveError: Event; + var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } declare module chrome.sockets.tcpServer { @@ -332,10 +304,6 @@ declare module chrome.sockets.tcpServer { socketId: number; } - interface Event { - addListener(callback: (info: T) => void): void; - } - interface AcceptEventArgs { socketId: number; clientSocketId: number; @@ -375,8 +343,8 @@ declare module chrome.sockets.tcpServer { export function close(socketId: number, callback?: () => void): void; export function getInfo(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; - var onAccept: Event; - var onAcceptError: Event; + var onAccept: chrome.events.Event<(args: AcceptEventArgs) => void>; + var onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; } //////////////////// @@ -391,3 +359,49 @@ declare module chrome.system.network { export function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; } + +declare module chrome.runtime { + interface Manifest { + app?: { + background?: { + scripts?: string[]; + } + }, + bluetooth?: { + uuids?: string[]; + socket?: boolean; + low_energy?: boolean; + peripheral?: boolean; + }, + file_handlers?: { + [name: string]: { + types?: string[]; + extensions?: string[]; + title?: string; + } + }, + kiosk_enabled?: boolean, + kiosk_only?: boolean, + url_handlers?: { + [name: string]: { + matches: string[]; + title?: string; + } + }, + usb_printers?: { + filters: { + vendorId?: number; + productId?: number; + interfaceClass?: number; + interfaceSubclass?: number; + interfaceProtocol?: number; + }[] + }, + webview?: { + partitions?: { + name: string; + accessible_resources: string[]; + }[] + } + } +} diff --git a/chrome/chrome-tests.ts.tscparams b/chrome/chrome-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/chrome/chrome-tests.ts.tscparams +++ b/chrome/chrome-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 17613b88c..d10fab1f7 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -135,13 +135,7 @@ declare module chrome.alarms { name: string; } - interface AlarmEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function( Alarm alarm) {...}; - */ - addListener(callback: (alarm: Alarm) => void): void; - } + interface AlarmEvent extends chrome.events.Event<(alarm: Alarm) => void> {} /** * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. @@ -286,61 +280,19 @@ declare module chrome.bookmarks { childIds: string[]; } - interface BookmarkRemovedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object removeInfo) {...}; - */ - addListener(callback: (id: string, removeInfo: BookmarkRemoveInfo) => void): void; - } + interface BookmarkRemovedEvent extends chrome.events.Event<(id: string, removeInfo: BookmarkRemoveInfo) => void> {} - interface BookmarkImportEndedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface BookmarkImportEndedEvent extends chrome.events.Event<() => void> {} - interface BookmarkMovedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object moveInfo) {...}; - */ - addListener(callback: (id: string, moveInfo: BookmarkMoveInfo) => void): void; - } + interface BookmarkMovedEvent extends chrome.events.Event<(id: string, moveInfo: BookmarkMoveInfo) => void> {} - interface BookmarkImportBeganEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface BookmarkImportBeganEvent extends chrome.events.Event<() => void> {} - interface BookmarkChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object changeInfo) {...}; - */ - addListener(callback: (id: string, changeInfo: BookmarkChangeInfo) => void): void; - } + interface BookmarkChangedEvent extends chrome.events.Event<(id: string, changeInfo: BookmarkChangeInfo) => void> {} - interface BookmarkCreatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, BookmarkTreeNode bookmark) {...}; - */ - addListener(callback: (id: string, bookmark: BookmarkTreeNode) => void): void; - } + interface BookmarkCreatedEvent extends chrome.events.Event<(id: string, bookmark: BookmarkTreeNode) => void> {} - interface BookmarkChildrenReordered extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, object reorderInfo) {...}; - */ - addListener(callback: (id: string, reorderInfo: BookmarkReorderInfo) => void): void; - } + interface BookmarkChildrenReordered extends chrome.events.Event<(id: string, reorderInfo: BookmarkReorderInfo) => void> {} interface BookmarkSearchQuery { query?: string; @@ -524,13 +476,7 @@ declare module chrome.browserAction { popup: string; } - interface BrowserClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( tabs.Tab tab) {...}; - */ - addListener(callback: (tab: chrome.tabs.Tab) => void): void; - } + interface BrowserClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} /** * Since Chrome 22. @@ -787,13 +733,7 @@ declare module chrome.commands { shortcut?: string; } - interface CommandEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string command) {...}; - */ - addListener(callback: (command: string) => void): void; - } + interface CommandEvent extends chrome.events.Event<(command: string) => void> {} /** * Returns all the registered extension commands for this extension and their shortcut (if active). @@ -1118,15 +1058,7 @@ declare module chrome.contextMenus { type?: string; } - interface MenuClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object info, tabs.Tab tab) {...}; - * Parameter info: Information sent when a context menu item is clicked. - * Parameter tab: The details of the tab where the click took place. If the click did not take place in a tab, this parameter will be missing. - */ - addListener(callback: (info: OnClickData, tab?: chrome.tabs.Tab) => void): void; - } + interface MenuClickedEvent extends chrome.events.Event<(info: OnClickData, tab?: chrome.tabs.Tab) => void> {} /** * Since Chrome 38. @@ -1287,13 +1219,7 @@ declare module chrome.cookies { cause: string; } - interface CookieChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object changeInfo) {...}; - */ - addListener(callback: (changeInfo: CookieChangeInfo) => void): void; - } + interface CookieChangedEvent extends chrome.events.Event<(changeInfo: CookieChangeInfo) => void> {} /** * Lists all existing cookie stores. @@ -1396,26 +1322,9 @@ declare module "chrome.debugger" { faviconUrl?: string; } - interface DebuggerDetachedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Debuggee source, DetachReason reason) {...}; - * Parameter source: The debuggee that was detached. - * Parameter reason: Since Chrome 24. Connection termination reason. - */ - addListener(callback: (source: Debuggee, reason: string) => void): void; - } + interface DebuggerDetachedEvent extends chrome.events.Event<(source: Debuggee, reason: string) => void> {} - interface DebuggerEventEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Debuggee source, string method, object params) {...}; - * Parameter source: The debuggee that generated this event. - * Parameter method: Method name. Should be one of the notifications defined by the remote debugging protocol. - * Parameter params: JSON object with the parameters. Structure of the parameters varies depending on the method name and is defined by the 'parameters' attribute of the event description in the remote debugging protocol. - */ - addListener(callback: (source: Debuggee, method: string, params?: Object) => void): void; - } + interface DebuggerEventEvent extends chrome.events.Event<(source: Debuggee, method: string, params?: Object) => void> {} /** * Attaches debugger to the given target. @@ -1509,7 +1418,7 @@ declare module chrome.declarativeContent { /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ schemes?: string[]; /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ - port?: any[]; + ports?: (number | number[])[]; } /** Matches the state of a web page by various criteria. */ @@ -1631,9 +1540,7 @@ declare module chrome.declarativeWebRequest { filter: RequestCookie; } - interface RequestedEvent extends chrome.events.Event { - addListener(callback: Function): void; - } + interface RequestedEvent extends chrome.events.Event {} var onRequest: RequestedEvent; } @@ -1734,22 +1641,9 @@ declare module chrome.devtools.inspectedWindow { value: string; } - interface ResourceAddedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Resource resource) {...}; - */ - addListener(callback: (resource: Resource) => void): void; - } + interface ResourceAddedEvent extends chrome.events.Event<(resource: Resource) => void> {} - interface ResourceContentCommittedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Resource resource, string content) {...}; - * Parameter content: New content of the resource. - */ - addListener(callback: (resource: Resource, content: string) => void): void; - } + interface ResourceContentCommittedEvent extends chrome.events.Event<(resource: Resource, content: string) => void> {} /** The ID of the tab being inspected. This ID may be used with chrome.tabs.* API. */ var tabId: number; @@ -1801,23 +1695,9 @@ declare module chrome.devtools.network { getContent(callback: (content: string, encoding: string) => void): void; } - interface RequestFinishedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Request request) {...}; - * Parameter request: Description of a network request in the form of a HAR entry. See HAR specification for details. - */ - addListener(callback: (request: Request) => void): void; - } + interface RequestFinishedEvent extends chrome.events.Event<(request: Request) => void> {} - interface NavigatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string url) {...}; - * Parameter url: URL of the new page. - */ - addListener(callback: (url: string) => void): void; - } + interface NavigatedEvent extends chrome.events.Event<(url: string) => void> {} /** * Returns HAR log that contains all known network requests. @@ -1842,32 +1722,11 @@ declare module chrome.devtools.network { * Availability: Since Chrome 18. */ declare module chrome.devtools.panels { - interface PanelShownEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(global window) {...}; - * Parameter window: The JavaScript window object of panel's page. - */ - addListener(callback: (window: chrome.windows.Window) => void): void; - } + interface PanelShownEvent extends chrome.events.Event<(window: chrome.windows.Window) => void> {} - interface PanelHiddenEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface PanelHiddenEvent extends chrome.events.Event<() => void> {} - interface PanelSearchEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function(string action, string queryString) {...}; - * Parameter action: Type of search action being performed. - * Optional parameter queryString: Query string (only for 'performSearch'). - */ - addListener(callback: (action: string, queryString?: string) => void): void; - } + interface PanelSearchEvent extends chrome.events.Event<(action: string, queryString?: string) => void> {} /** Represents a panel created by extension. */ interface ExtensionPanel { @@ -1886,13 +1745,7 @@ declare module chrome.devtools.panels { onSearch: PanelSearchEvent; } - interface ButtonClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface ButtonClickedEvent extends chrome.events.Event<() => void> {} /** A button created by the extension. */ interface Button { @@ -1907,13 +1760,7 @@ declare module chrome.devtools.panels { onClicked: ButtonClickedEvent; } - interface SelectionChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface SelectionChangedEvent extends chrome.events.Event<() => void> {} /** Represents the Elements panel. */ interface ElementsPanel { @@ -1948,22 +1795,9 @@ declare module chrome.devtools.panels { onSelectionChanged: SelectionChangedEvent; } - interface ExtensionSidebarPaneShownEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(global window) {...}; - * Parameter window: The JavaScript window object of the sidebar page, if one was set with the setPage() method. - */ - addListener(callback: (window: chrome.windows.Window) => void): void; - } + interface ExtensionSidebarPaneShownEvent extends chrome.events.Event<(window: chrome.windows.Window) => void> {} - interface ExtensionSidebarPaneHiddenEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface ExtensionSidebarPaneHiddenEvent extends chrome.events.Event<() => void> {} /** A sidebar created by the extension. */ interface ExtensionSidebarPane { @@ -2279,39 +2113,13 @@ declare module chrome.downloads { conflictAction?: string; } - interface DownloadChangedEvent extends chrome.events.Event { - /** - * When any of a DownloadItem's properties except bytesReceived and estimatedEndTime changes, this event fires with the downloadId and an object containing the properties that changed. - * @param callback The callback parameter should be a function that looks like this: - * function(object downloadDelta) {...}; - */ - addListener(callback: (downloadDelta: DownloadDelta) => void): void; - } + interface DownloadChangedEvent extends chrome.events.Event<(downloadDelta: DownloadDelta) => void> {} - interface DownloadCreatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( DownloadItem downloadItem) {...}; - */ - addListener(callback: (downloadItem: DownloadItem) => void): void; - } + interface DownloadCreatedEvent extends chrome.events.Event<(downloadItem: DownloadItem) => void> {} - interface DownloadErasedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(integer downloadId) {...}; - * Parameter downloadId: The id of the DownloadItem that was erased. - */ - addListener(callback: (downloadId: number) => void): void; - } + interface DownloadErasedEvent extends chrome.events.Event<(downloadId: number) => void> {} - interface DownloadDeterminingFilenameEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( DownloadItem downloadItem, function suggest) {...}; - */ - addListener(callback: (downloadItem: DownloadItem, suggest: (suggestion?: DownloadFilenameSuggestion) => void) => void): void; - } + interface DownloadDeterminingFilenameEvent extends chrome.events.Event<(downloadItem: DownloadItem, suggest: (suggestion?: DownloadFilenameSuggestion) => void) => void> {} /** * Find DownloadItem. Set query to the empty object to get all DownloadItem. To get a specific DownloadItem, set only the id field. To page through a large number of items, set orderBy: ['-startTime'], set limit to the number of items per page, and set startedAfter to the startTime of the last item from the last page. @@ -2537,14 +2345,14 @@ declare module chrome.events { } /** An object which allows the addition and removal of listeners for a Chrome event. */ - interface Event { + interface Event { /** * Registers an event listener callback to an event. * @param callback Called when an event occurs. The parameters of this function depend on the type of event. * The callback parameter should be a function that looks like this: * function() {...}; */ - addListener(callback: Function): void; + addListener(callback: T): void; /** * Returns currently registered rules. * @param callback Called with registered rules. @@ -2565,7 +2373,7 @@ declare module chrome.events { /** * @param callback Listener whose registration status shall be tested. */ - hasListener(callback: Function): boolean; + hasListener(callback: T): boolean; /** * Unregisters currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered. @@ -2596,7 +2404,7 @@ declare module chrome.events { * The callback parameter should be a function that looks like this: * function() {...}; */ - removeListener(callback: () => void): void; + removeListener(callback: T): void; hasListeners(): boolean; } @@ -2639,21 +2447,7 @@ declare module chrome.extension { message: string; } - interface OnRequestEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(any request, runtime.MessageSender sender, function sendResponse) {...}; - * Parameter request: The request sent by the calling script. - * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one onRequest listener in the same document, then only one may send a response. - */ - addListener(callback: (request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void): void; - /** - * @param callback The callback parameter should be a function that looks like this: - * function(runtime.MessageSender sender, function sendResponse) {...}; - * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one onRequest listener in the same document, then only one may send a response. - */ - addListener(callback: (sender: runtime.MessageSender, sendResponse: (response: any) => void) => void): void; - } + interface OnRequestEvent extends chrome.events.Event<((request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) | ((sender: runtime.MessageSender, sendResponse: (response: any) => void) => void)> {} /** * Since Chrome 7. @@ -2764,15 +2558,7 @@ declare module chrome.fileBrowserHandler { entries: any[]; } - interface FileBrowserHandlerExecuteEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id, FileHandlerExecuteEventDetails details) {...}; - * Parameter id: File browser action id as specified in the listener component's manifest. - * Parameter details: File handler execute event details. - */ - addListener(callback: (id: string, details: FileHandlerExecuteEventDetails) => void): void; - } + interface FileBrowserHandlerExecuteEvent extends chrome.events.Event<(id: string, details: FileHandlerExecuteEventDetails) => void> {} /** * Prompts user to select file path under which file should be saved. When the file is selected, file access permission required to use the file (read, write and create) are granted to the caller. The file will not actually get created during the function call, so function caller must ensure its existence before using it. The function has to be invoked with a user gesture. @@ -3018,117 +2804,33 @@ declare module chrome.fileSystemProvider { operationRequestId: number; } - interface RequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface RequestedEvent extends chrome.events.Event<(options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface MetadataRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void): void; - } + interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void> {} - interface DirectoryPathRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void): void; - } + interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void> {} - interface OpenFileRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OpenedFileRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OpenedFileOffsetRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void): void; - } + interface OpenedFileOffsetRequestedEvent extends chrome.events.Event<(options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void> {} - interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface EntryPathRecursiveRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface FilePathRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface SourceTargetPathRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface FilePathLengthRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OpenedFileIoRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OperationRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object options, function successCallback, function errorCallback) {...}; - */ - addListener(callback: (options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - interface OptionlessRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(function successCallback, function errorCallback) {...}; - */ - addListener(callback: (successCallback: Function, errorCallback: (error: string) => void) => void): void; - } + interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: string) => void) => void> {} /** * Mounts a file system with the given fileSystemId and displayName. displayName will be shown in the left panel of Files.app. displayName can contain any characters including '/', but cannot be an empty string. displayName must be descriptive but doesn't have to be unique. The fileSystemId must not be an empty string. @@ -3289,37 +2991,13 @@ declare module chrome.fontSettings { fontId: string; } - interface DefaultFixedFontSizeChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FontSizeDetails) => void): void; - } + interface DefaultFixedFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - interface DefaultFontSizeChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FontSizeDetails) => void): void; - } + interface DefaultFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - interface MinimumFontSizeChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FontSizeDetails) => void): void; - } + interface MinimumFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - interface FontChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: FullFontDetails) => void): void; - } + interface FontChangedEvent extends chrome.events.Event<(details: FullFontDetails) => void> {} /** * Sets the default font size. @@ -3461,31 +3139,11 @@ declare module chrome.gcm { detail: Object; } - interface MessageReceptionEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object message) {...}; - * Parameter message: A message received from another party via GCM. - */ - addListener(callback: (message: IncomingMessage) => void): void; - } + interface MessageReceptionEvent extends chrome.events.Event<(message: IncomingMessage) => void> {} - interface MessageDeletionEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface MessageDeletionEvent extends chrome.events.Event<() => void> {} - interface GcmErrorEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object error) {...}; - * Parameter error: An error that occured while trying to send the message either in Chrome or on the GCM server. Application can retry sending the message with a reasonable backoff and possibly longer time-to-live. - */ - addListener(callback: (error: GcmError) => void): void; - } + interface GcmErrorEvent extends chrome.events.Event<(error: GcmError) => void> {} /** The maximum size (in bytes) of all key/value pairs in a message. */ var MAX_MESSAGE_SIZE: number; @@ -3593,21 +3251,9 @@ declare module chrome.history { urls?: string[]; } - interface HistoryVisitedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( HistoryItem result) {...}; - */ - addListener(callback: (result: HistoryItem) => void): void; - } + interface HistoryVisitedEvent extends chrome.events.Event<(result: HistoryItem) => void> {} - interface HistoryVisitRemovedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object removed) {...}; - */ - addListener(callback: (removed: RemovedResult) => void): void; - } + interface HistoryVisitRemovedEvent extends chrome.events.Event<(removed: RemovedResult) => void> {} /** * Searches the history for the last visit time of each page matching the query. @@ -3741,13 +3387,7 @@ declare module chrome.identity { interactive?: boolean; } - interface SignInChangeEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( AccountInfo account, boolean signedIn) {...}; - */ - addListener(callback: (account: AccountInfo, signedIn: boolean) => void): void; - } + interface SignInChangeEvent extends chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void> {} /** * Retrieves a list of AccountInfo objects describing the accounts present on the profile. @@ -3796,7 +3436,7 @@ declare module chrome.identity { * @since Chrome 33. * @param path Optional. The path appended to the end of the generated URL. */ - export function getRedirectURL(path?: string): void; + export function getRedirectURL(path?: string): string; /** * Fired when signin state changes for an account on the user's profile. @@ -3814,13 +3454,7 @@ declare module chrome.identity { * @since Chrome 6. */ declare module chrome.idle { - interface IdleStateChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( IdleState newState) {...}; - */ - addListener(callback: (newState: string) => void): void; - } + interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> {} /** * Returns "locked" if the system is locked, "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise. @@ -4109,101 +3743,25 @@ declare module chrome.input.ime { anchor: number; } - interface BlurEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(integer contextID) {...}; - * Parameter contextID: The ID of the text field that has lost focus. The ID is invalid after this call - */ - addListener(callback: (contextID: number) => void): void; - } + interface BlurEvent extends chrome.events.Event<(contextID: number) => void> {} - interface CandidateClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, integer candidateID, MouseButton button) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter candidateID: ID of the candidate that was clicked. - * Parameter button: Which mouse buttons was clicked. - */ - addListener(callback: (engineID: string, candidateID: number, button: string) => void): void; - } + interface CandidateClickedEvent extends chrome.events.Event<(engineID: string, candidateID: number, button: string) => void> {} - interface KeyEventEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, KeyboardEvent keyData) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter keyData: Data on the key event - */ - addListener(callback: (engineID: string, keyData: KeyboardEvent) => void): void; - } + interface KeyEventEvent extends chrome.events.Event<(engineID: string, keyData: KeyboardEvent) => void> {} - interface DeactivatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID) {...}; - * Parameter engineID: ID of the engine receiving the event - */ - addListener(callback: (engineID: string) => void): void; - } + interface DeactivatedEvent extends chrome.events.Event<(engineID: string) => void> {} - interface InputContextUpdateEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( InputContext context) {...}; - * Parameter context: An InputContext object describing the text field that has changed. - */ - addListener(callback: (context: InputContext) => void): void; - } + interface InputContextUpdateEvent extends chrome.events.Event<(context: InputContext) => void> {} - interface ActivateEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, ScreenType screen) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter The screen type under which the IME is activated. - */ - addListener(callback: (engineID: string, screen: string) => void): void; - } + interface ActivateEvent extends chrome.events.Event<(engineID: string, screen: string) => void> {} - interface FocusEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( InputContext context) {...}; - * Parameter context: Describes the text field that has acquired focus. - */ - addListener(callback: (context: InputContext) => void): void; - } + interface FocusEvent extends chrome.events.Event<(context: InputContext) => void> {} - interface MenuItemActivatedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, string name) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter name: Name of the MenuItem which was activated - */ - addListener(callback: (engineID: string, name: string) => void): void; - } + interface MenuItemActivatedEvent extends chrome.events.Event<(engineID: string, name: string) => void> {} - interface SurroundingTextChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID, object surroundingInfo) {...}; - * Parameter engineID: ID of the engine receiving the event - * Parameter surroundingInfo: The surrounding information. - */ - addListener(callback: (engineID: string, surroundingInfo: SurroundingTextInfo) => void): void; - } + interface SurroundingTextChangedEvent extends chrome.events.Event<(engineID: string, surroundingInfo: SurroundingTextInfo) => void> {} - interface InputResetEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string engineID) {...}; - * Parameter engineID: ID of the engine receiving the event - */ - addListener(callback: (engineID: string) => void): void; - } + interface InputResetEvent extends chrome.events.Event<(engineID: string) => void> {} /** * Adds the provided menu items to the language menu when this IME is active. @@ -4435,38 +3993,13 @@ declare module chrome.management { showConfirmDialog?: boolean; } - interface ManagementDisabledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( ExtensionInfo info) {...}; - */ - addListener(callback: (info: ExtensionInfo) => void): void; - } + interface ManagementDisabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} - interface ManagementUninstalledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string id) {...}; - * Parameter id: The id of the extension, app, or theme that was uninstalled. - */ - addListener(callback: (id: string) => void): void; - } + interface ManagementUninstalledEvent extends chrome.events.Event<(id: string) => void> {} - interface ManagementInstalledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( ExtensionInfo info) {...}; - */ - addListener(callback: (info: ExtensionInfo) => void): void; - } + interface ManagementInstalledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} - interface ManagementEnabledEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( ExtensionInfo info) {...}; - */ - addListener(callback: (info: ExtensionInfo) => void): void; - } + interface ManagementEnabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} /** * Enables or disables an app or extension. @@ -4613,14 +4146,7 @@ declare module chrome.networking.config { Security?: string; } - interface CaptivePorttalDetectedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( NetworkInfo networkInfo) {...}; - * Parameter networkInfo: Information about the network on which a captive portal was detected. - */ - addListener(callback: (networkInfo: NetworkInfo) => void): void; - } + interface CaptivePorttalDetectedEvent extends chrome.events.Event<(networkInfo: NetworkInfo) => void> {} /** * Allows an extension to define network filters for the networks it can handle. A call to this function will remove all filters previously installed by the extension before setting the new list. @@ -4719,45 +4245,15 @@ declare module chrome.notifications { imageUrl?: string; } - interface NotificationClosedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string notificationId, boolean byUser) {...}; - */ - addListener(callback: (notificationId: string, byUser: boolean) => void): void; - } + interface NotificationClosedEvent extends chrome.events.Event<(notificationId: string, byUser: boolean) => void> {} - interface NotificationClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string notificationId) {...}; - */ - addListener(callback: (notificationId: string) => void): void; - } + interface NotificationClickedEvent extends chrome.events.Event<(notificationId: string) => void> {} - interface NotificationButtonClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string notificationId, integer buttonIndex) {...}; - */ - addListener(callback: (notificationId: string, buttonIndex: number) => void): void; - } + interface NotificationButtonClickedEvent extends chrome.events.Event<(notificationId: string, buttonIndex: number) => void> {} - interface NotificationPermissionLevelChangedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( PermissionLevel level) {...}; - */ - addListener(callback: (level: string) => void): void; - } + interface NotificationPermissionLevelChangedEvent extends chrome.events.Event<(level: string) => void> {} - interface NotificationShowSettingsEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> {} /** The notification closed, either by the system or by user action. */ export var onClosed: NotificationClosedEvent; @@ -4857,40 +4353,13 @@ declare module chrome.omnibox { description: string; } - interface OmniboxInputEnteredEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function(string text, OnInputEnteredDisposition disposition) {...}; - */ - addListener(callback: (text: string) => void): void; - } + interface OmniboxInputEnteredEvent extends chrome.events.Event<(text: string) => void> {} - interface OmniboxInputChangedEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function(string text, function suggest) {...}; - * Parameter suggest: A callback passed to the onInputChanged event used for sending suggestions back to the browser. - * The suggest parameter should be a function that looks like this: - * function(array of SuggestResult suggestResults) {...}; - */ - addListener(callback: (text: string, suggest: (suggestResults: SuggestResult[]) => void) => void): void; - } + interface OmniboxInputChangedEvent extends chrome.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> {} - interface OmniboxInputStartedEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface OmniboxInputStartedEvent extends chrome.events.Event<() => void> {} - interface OmniboxInputCancelledEvent extends chrome.events.Event { - /** - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: () => void): void; - } + interface OmniboxInputCancelledEvent extends chrome.events.Event<() => void> {} /** * Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the first suggestion row underneath the URL bar. @@ -4917,13 +4386,7 @@ declare module chrome.omnibox { * @since Chrome 5. */ declare module chrome.pageAction { - interface PageActionClickedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( tabs.Tab tab) {...}; - */ - addListener(callback: (tab: chrome.tabs.Tab) => void): void; - } + interface PageActionClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} interface TitleDetails { /** The id of the tab for which you want to modify the page action. */ @@ -5232,45 +4695,13 @@ declare module chrome.printerProvider { document: Blob; } - interface PrinterRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(function resultCallback) {...}; - * Parameter resultCallback: Callback to return printer list. Every listener must call callback exactly once. - */ - addListener(callback: (resultCallback: (printerInfo: PrinterInfo[]) => void) => void): void; - } + interface PrinterRequestedEvent extends chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> {} - interface PrinterInfoRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( usb.Device device, function resultCallback) {...}; - * Parameter device: The USB device. - * Parameter resultCallback: Callback to return printer info. The receiving listener must call callback exactly once. If the parameter to this callback is undefined that indicates that the application has determined that the device is not supported. - */ - addListener(callback: (device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void): void; - } + interface PrinterInfoRequestedEvent extends chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void> {} - interface CapabilityRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(string printerId, function resultCallback) {...}; - * Parameter printerId: Unique ID of the printer whose capabilities are requested. - * Parameter resultCallback: Callback to return device capabilities in CDD format. The receiving listener must call callback exectly once. - */ - addListener(callback: (printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void): void; - } + interface CapabilityRequestedEvent extends chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void> {} - interface PrintRequestedEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object printJob, function resultCallback) {...}; - * Parameter printJob: The printing request parameters. - * Parameter resultCallback: Callback that should be called when the printing request is completed. - * Parameter result (for resultCallback): OK: Operation completed successfully. FAILED: General failure. INVALID_TICKET: Print ticket is invalid. For example, ticket is inconsistent with capabilities or extension is not able to handle all settings from the ticket. INVALID_DATA: Document is invalid. For example, data may be corrupted or the format is incompatible with the extension. - */ - addListener(callback: (printJob: PrintJob, resultCallback: (result: string) => void) => void): void; - } + interface PrintRequestedEvent extends chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> {} /** Event fired when print manager requests printers provided by extensions. */ export var onGetPrintersRequested: PrinterRequestedEvent; @@ -5407,13 +4838,7 @@ declare module chrome.proxy { fatal: boolean; } - interface ProxyErrorEvent extends chrome.events.Event { - /** - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - addListener(callback: (details: ErrorDetails) => void): void; - } + interface ProxyErrorEvent extends chrome.events.Event<(details: ErrorDetails) => void> {} var settings: chrome.types.ChromeSetting; /** Notifies about proxy errors. */ @@ -5527,7 +4952,7 @@ declare module chrome.runtime { */ sender?: MessageSender; /** An object which allows the addition and removal of listeners for a Chrome event. */ - onDisconnect: chrome.events.Event; + onDisconnect: chrome.events.Event<() => void>; /** An object which allows the addition and removal of listeners for a Chrome event. */ onMessage: PortMessageEvent; name: string; @@ -5543,46 +4968,226 @@ declare module chrome.runtime { version: string; } - interface PortMessageEvent extends chrome.events.Event { - addListener(callback: (message: Object, port: Port) => void): void; - } + interface PortMessageEvent extends chrome.events.Event<(message: Object, port: Port) => void> {} - interface ExtensionMessageEvent extends chrome.events.Event { - /** - * @param callback - * Optional parameter message: The message sent by the calling script. - * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called). - */ - addListener(callback: (message: any, sender: MessageSender, sendResponse: (response: any) => void) => void): void; - } + interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> {} - interface ExtensionConnectEvent extends chrome.events.Event { - addListener(callback: (port: Port) => void): void; - } + interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> {} - interface RuntimeInstalledEvent extends chrome.events.Event { - addListener(callback: (details: InstalledDetails) => void): void; - } + interface RuntimeInstalledEvent extends chrome.events.Event<(details: InstalledDetails) => void> {} - interface RuntimeEvent extends chrome.events.Event { - addListener(callback: () => void): void; - } + interface RuntimeEvent extends chrome.events.Event<() => void> {} - interface RuntimeRestartRequiredEvent extends chrome.events.Event { - /** - * @param callback - * Parameter reason: The reason that the event is being dispatched. One of: "app_update", "os_update", or "periodic" - */ - addListener(callback: (reason: string) => void): void; - } + interface RuntimeRestartRequiredEvent extends chrome.events.Event<(reason: string) => void> {} - interface RuntimeUpdateAvailableEvent extends chrome.events.Event { - /** - * @param callback - * Parameter details: The manifest details of the available update. - */ - addListener(callback: (details: UpdateAvailableDetails) => void): void; - } + interface RuntimeUpdateAvailableEvent extends chrome.events.Event<(details: UpdateAvailableDetails) => void> {} + + interface ManifestIcons { + [size: number]: string; + } + + interface ManifestAction { + default_icon?: ManifestIcons; + default_title?: string; + default_popup?: string; + } + + interface SearchProvider { + name?: string; + keyword?: string; + favicon_url?: string; + search_url: string; + encoding?: string; + suggest_url?: string; + instant_url?: string; + image_url?: string; + search_url_post_params?: string; + suggest_url_post_params?: string; + instant_url_post_params?: string; + image_url_post_params?: string; + alternate_urls?: string[]; + prepopulated_id?: number; + is_default?: boolean; + } + + interface Manifest { + // Required + manifest_version: number; + name: string; + version: string; + + // Recommended + default_locale?: string; + description?: string; + icons?: ManifestIcons; + + // Pick one (or none) + browser_action?: ManifestAction; + page_action?: ManifestAction; + + // Optional + author?: any; + automation?: any; + background?: { + scripts?: string[]; + page?: string; + persistent?: boolean; + }; + background_page?: string; + chrome_settings_overrides?: { + homepage?: string; + search_provider?: SearchProvider; + startup_pages?: string[]; + }; + chrome_ui_overrides?: { + bookmarks_ui?: { + remove_bookmark_shortcut?: boolean; + remove_button?: boolean; + } + }; + chrome_url_overrides?: { + bookmarks?: string; + history?: string; + newtab?: string; + }; + commands?: { + [name: string]: { + suggested_key?: { + default?: string; + windows?: string; + mac?: string; + chromeos?: string; + linux?: string; + }; + description?: string; + global?: boolean + } + }; + content_capabilities?: { + matches?: string[]; + permissions?: string[]; + }; + content_scripts?: { + matches?: string[]; + exclude_matches?: string[]; + css?: string[]; + js?: string[]; + run_at?: string; + all_frames?: boolean; + include_globs?: string[]; + exclude_globs?: string[]; + }[]; + content_security_policy?: string; + converted_from_user_script?: boolean; + copresence?: any; + current_locale?: string; + devtools_page?: string; + event_rules?: { + event?: string; + actions?: { + type: string; + }[]; + conditions?: chrome.declarativeContent.PageStateMatcher[] + }[]; + externally_connectable?: { + ids?: string[]; + matches?: string[]; + accepts_tls_channel_id?: boolean; + }; + file_browser_handlers?: { + id?: string; + default_title?: string; + file_filters?: string[]; + }[]; + file_system_provider_capabilities?: { + configurable?: boolean; + watchable?: boolean; + multiple_mounts?: boolean; + source?: string; + }; + homepage_url?: string; + import?: { + id: string; + minimum_version?: string + }[]; + export?: { + whitelist?: string[] + }; + incognito?: string; + input_components?: { + name?: string; + type?: string; + id?: string; + description?: string; + language?: string; + layouts?: any[]; + }[]; + key?: string; + minimum_chrome_version?: string; + nacl_modules?: { + path: string; + mime_type: string; + }[]; + oauth2?: { + client_id: string; + scopes?: string[]; + }; + offline_enabled?: boolean; + omnibox?: { + keyword: string; + }; + optional_permissions?: string[]; + options_page?: string; + options_ui?: { + page?: string; + chrome_style?: boolean; + open_in_tab?: boolean; + }; + permissions?: string[]; + platforms?: { + nacl_arch?: string; + sub_package_path: string; + }[]; + plugins?: { + path: string; + }[]; + requirements?: { + '3D'?: { + features?: string[] + }; + plugins?: { + npapi?: boolean; + } + }; + sandbox?: { + pages: string[]; + content_security_policy?: string; + }; + short_name?: string; + signature?: any; + spellcheck?: { + dictionary_language?: string; + dictionary_locale?: string; + dictionary_format?: string; + dictionary_path?: string; + }; + storage?: { + managed_schema: string + }; + system_indicator?: any; + tts_engine?: { + voices: { + voice_name: string; + lang?: string; + gender?: string; + event_types?: string[]; + }[] + }; + update_url?: string; + version_name?: string; + web_accessible_resources?: string[]; + [key: string]: any; + } /** * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. @@ -5608,7 +5213,7 @@ declare module chrome.runtime { * Returns details about the app or extension from the manifest. The object returned is a serialization of the full manifest file. * @returns The manifest details. */ - export function getManifest(): Object; + export function getManifest(): Manifest; /** * Returns a DirectoryEntry for the package directory. * @since Chrome 29. @@ -5763,9 +5368,7 @@ declare module chrome.scriptBadge { popup: string; } - interface ScriptBadgeClickedEvent extends chrome.events.Event { - addListener(callback: (tab: chrome.tabs.Tab) => void): void; - } + interface ScriptBadgeClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} export function getPopup(details: GetPopupDetails, callback: Function): void; export function getAttention(details: AttentionDetails): void; @@ -5813,9 +5416,7 @@ declare module chrome.sessions { sessions: Session[]; } - interface SessionChangedEvent extends chrome.events.Event { - addListener(callback: () => void): void; - } + interface SessionChangedEvent extends chrome.events.Event<() => void> {} /** The maximum number of sessions.Session that will be included in a requested list. */ export var MAX_SESSION_RESULTS: number; @@ -5978,14 +5579,7 @@ declare module chrome.storage { MAX_WRITE_OPERATIONS_PER_MINUTE: number; } - interface StorageChangedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter changes: Object mapping each key that changed to its corresponding storage.StorageChange for that item. - * Parameter areaName: Since Chrome 22. The name of the storage area ("sync", "local" or "managed") the changes are for. - */ - addListener(callback: (changes: { [key: string]: StorageChange }, areaName: string) => void): void; - } + interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: string) => void> {} /** Items in the local storage area are local to each machine. */ var local: LocalStorageArea; @@ -6159,13 +5753,9 @@ declare module chrome.system.storage { availableCapacity: number; } - interface SystemStorageAttachedEvent extends chrome.events.Event { - addListener(callback: (info: StorageUnitInfo) => void): void; - } + interface SystemStorageAttachedEvent extends chrome.events.Event<(info: StorageUnitInfo) => void> {} - interface SystemStorageDetachedEvent extends chrome.events.Event { - addListener(callback: (id: string) => void): void; - } + interface SystemStorageDetachedEvent extends chrome.events.Event<(id: string) => void> {} /** Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. */ export function getInfo(callback: (info: StorageUnitInfo[]) => void): void; @@ -6219,13 +5809,7 @@ declare module chrome.tabCapture { videoConstraints?: MediaStreamConstraints; } - interface CaptureStatusChangedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter info: CaptureInfo with new capture status for the tab. - */ - addListener(callback: (info: CaptureInfo) => void): void; - } + interface CaptureStatusChangedEvent extends chrome.events.Event<(info: CaptureInfo) => void> {} /** * Captures the visible area of the currently active tab. Capture can only be started on the currently active tab after the extension has been invoked. Capture is maintained across page navigations within the tab, and stops when the tab is closed, or the media stream is closed by the extension. @@ -6659,58 +6243,27 @@ declare module chrome.tabs { zoomSettings: ZoomSettings; } - interface TabHighlightedEvent extends chrome.events.Event { - addListener(callback: (highlightInfo: HighlightInfo) => void): void; - } + interface TabHighlightedEvent extends chrome.events.Event<(highlightInfo: HighlightInfo) => void> {} - interface TabRemovedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, removeInfo: TabRemoveInfo) => void): void; - } + interface TabRemovedEvent extends chrome.events.Event<(tabId: number, removeInfo: TabRemoveInfo) => void> {} - interface TabUpdatedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter changeInfo: Lists the changes to the state of the tab that was updated. - * Parameter tab: Gives the state of the tab that was updated. - */ - addListener(callback: (tabId: number, changeInfo: TabChangeInfo, tab: Tab) => void): void; - } + interface TabUpdatedEvent extends chrome.events.Event<(tabId: number, changeInfo: TabChangeInfo, tab: Tab) => void> {} - interface TabAttachedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, attachInfo: TabAttachInfo) => void): void; - } + interface TabAttachedEvent extends chrome.events.Event<(tabId: number, attachInfo: TabAttachInfo) => void> {} - interface TabMovedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, moveInfo: TabMoveInfo) => void): void; - } + interface TabMovedEvent extends chrome.events.Event<(tabId: number, moveInfo: TabMoveInfo) => void> {} - interface TabDetachedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, detachInfo: TabDetachInfo) => void): void; - } + interface TabDetachedEvent extends chrome.events.Event<(tabId: number, detachInfo: TabDetachInfo) => void> {} - interface TabCreatedEvent extends chrome.events.Event { - /** - * @param callback - * Parameter tab: Details of the tab that was created. - */ - addListener(callback: (tab: Tab) => void): void; - } + interface TabCreatedEvent extends chrome.events.Event<(tab: Tab) => void> {} - interface TabActivatedEvent extends chrome.events.Event { - addListener(callback: (activeInfo: TabActiveInfo) => void): void; - } + interface TabActivatedEvent extends chrome.events.Event<(activeInfo: TabActiveInfo) => void> {} - interface TabReplacedEvent extends chrome.events.Event { - addListener(callback: (addedTabId: number, removedTabId: number) => void): void; - } + interface TabReplacedEvent extends chrome.events.Event<(addedTabId: number, removedTabId: number) => void> {} - interface TabSelectedEvent extends chrome.events.Event { - addListener(callback: (tabId: number, selectInfo: TabWindowInfo) => void): void; - } + interface TabSelectedEvent extends chrome.events.Event<(tabId: number, selectInfo: TabWindowInfo) => void> {} - interface TabZoomChangeEvent extends chrome.events.Event { - addListener(callback: (ZoomChangeInfo: ZoomChangeInfo) => void): void; - } + interface TabZoomChangeEvent extends chrome.events.Event<(ZoomChangeInfo: ZoomChangeInfo) => void> {} /** * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. @@ -7185,30 +6738,22 @@ declare module chrome.ttsEngine { pitch?: number; } - interface TtsEngineSpeakEvent extends chrome.events.Event { - /** - * @param callback - * Parameter utterance: The text to speak, specified as either plain text or an SSML document. If your engine does not support SSML, you should strip out all XML markup and synthesize only the underlying text content. The value of this parameter is guaranteed to be no more than 32,768 characters. If this engine does not support speaking that many characters at a time, the utterance should be split into smaller chunks and queued internally without returning an error. - * Parameter options: Options specified to the tts.speak() method. - * Parameter sendTtsEvent: Call this function with events that occur in the process of speaking the utterance. - */ - addListener(callback: (utterance: string, options: SpeakOptions, sendTtsEvent: (event: chrome.tts.TtsEvent) => void) => void): void; - } + interface TtsEngineSpeakEvent extends chrome.events.Event<(utterance: string, options: SpeakOptions, sendTtsEvent: (event: chrome.tts.TtsEvent) => void) => void> {} /** Called when the user makes a call to tts.speak() and one of the voices from this extension's manifest is the first to match the options object. */ var onSpeak: TtsEngineSpeakEvent; /** Fired when a call is made to tts.stop and this extension may be in the middle of speaking. If an extension receives a call to onStop and speech is already stopped, it should do nothing (not raise an error). If speech is in the paused state, this should cancel the paused state. */ - var onStop: chrome.events.Event; + var onStop: chrome.events.Event<() => void>; /** * Optional: if an engine supports the pause event, it should pause the current utterance being spoken, if any, until it receives a resume event or stop event. Note that a stop event should also clear the paused state. * @since Chrome 29. */ - var onPause: chrome.events.Event; + var onPause: chrome.events.Event<() => void>; /** * Optional: if an engine supports the pause event, it should also support the resume event, to continue speaking the current utterance, if any. Note that a stop event should also clear the paused state. * @since Chrome 29. */ - var onResume: chrome.events.Event; + var onResume: chrome.events.Event<() => void>; } //////////////////// @@ -7277,9 +6822,7 @@ declare module chrome.types { incognitoSpecific?: boolean; } - interface ChromeSettingChangedEvent extends chrome.events.Event { - addListener(callback: DetailsCallback): void; - } + interface ChromeSettingChangedEvent extends chrome.events.Event {} /** An interface that allows access to a Chrome browser setting. See accessibilityFeatures for an example. */ interface ChromeSetting { @@ -7336,55 +6879,15 @@ declare module chrome.vpnProvider { dnsServer: string[]; } - interface VpnPlatformMessageEvent extends chrome.events.Event { - /** - * @param callback - * Parameter id: ID of the configuration the message is intended for. - * Parameter message: The message received from the platform. - * * connected: VPN configuration connected. - * * disconnected: VPN configuration disconnected. - * * error: An error occurred in VPN connection, for example a timeout. A description of the error is give as the error argument to onPlatformMessage. - * Parameter error: Error message when there is an error. - */ - addListener(callback: (id: string, message: string, error: string) => void): void; - } + interface VpnPlatformMessageEvent extends chrome.events.Event<(id: string, message: string, error: string) => void> {} - interface VpnPacketReceptionEvent extends chrome.events.Event { - /** - * @param callback - * Parameter data: The IP packet received from the platform. - */ - addListener(callback: (data: ArrayBuffer) => void): void; - } + interface VpnPacketReceptionEvent extends chrome.events.Event<(data: ArrayBuffer) => void> {} - interface VpnConfigRemovalEvent extends chrome.events.Event { - /** - * @param callback - * Parameter id: ID of the removed configuration. - */ - addListener(callback: (id: string) => void): void; - } + interface VpnConfigRemovalEvent extends chrome.events.Event<(id: string) => void> {} - interface VpnConfigCreationEvent extends chrome.events.Event { - /** - * @param callback - * Parameter id: ID of the configuration created. - * Parameter name: Name of the configuration created. - * Parameter data: Configuration data provided by the administrator. - */ - addListener(callback: (id: string, name: string, data: Object) => void): void; - } + interface VpnConfigCreationEvent extends chrome.events.Event<(id: string, name: string, data: Object) => void> {} - interface VpnUiEvent extends chrome.events.Event { - /** - * @param callback - * Parameter event: The UI event that is triggered. - * * showAddDialog: Request the VPN client to show add configuration dialog to the user. - * * showConfigureDialog: Request the VPN client to show configuration settings dialog to the user. - * Optional parameter id: ID of the configuration for which the UI event was triggered. - */ - addListener(callback: (event: string, id?: string) => void): void; - } + interface VpnUiEvent extends chrome.events.Event<(event: string, id?: string) => void> {} /** * Creates a new VPN configuration that persists across multiple login sessions of the user. @@ -7577,33 +7080,21 @@ declare module chrome.webNavigation { url: chrome.events.UrlFilter[]; } - interface WebNavigationEvent extends chrome.events.Event { - addListener(callback: (details: WebNavigationCallbackDetails) => void, filters?: WebNavigationEventFilter): void; + interface WebNavigationEvent extends chrome.events.Event<(details: T) => void> { + addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void; } + + interface WebNavigationFramedEvent extends WebNavigationEvent {} - interface WebNavigationFramedEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationFramedCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationFramedErrorEvent extends WebNavigationEvent {} - interface WebNavigationFramedErrorEvent extends WebNavigationFramedEvent { - addListener(callback: (details: WebNavigationFramedErrorCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationSourceEvent extends WebNavigationEvent {} - interface WebNavigationSourceEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationSourceCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationParentedEvent extends WebNavigationEvent {} - interface WebNavigationParentedEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationParentedCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationTransitionalEvent extends WebNavigationEvent {} - interface WebNavigationTransitionalEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationTransitionCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } - - interface WebNavigationReplacementEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationReplacementCallbackDetails) => void, filters?: WebNavigationEventFilter): void; - } + interface WebNavigationReplacementEvent extends WebNavigationEvent {} /** * Retrieves information about the given frame. A frame refers to an ') - */ - youTubeCode?: string; - /** - * Vimeo embed code. %id% is replaced by video id. (default: '') - */ - vimeoCode?: string; - } - - export interface RoyalSliderBlockOptions { - /** - * true or false (default: true) - */ - fadeEffect?: boolean; - /** - * Move effect direction.Can be 'left', 'right', 'top', 'bottom' or 'none'. (default: 'top') - */ - moveEffect?: string; - /** - * Distance for move effect in pixels. (default: 20) - */ - moveOffset?: number; - /** - * Transition speed of block, in ms. (default: 400) - */ - speed?: number; - /** - * Easing function of block animation.Read more in easing section of docs. (default: 'easeOutSine' ) - */ - easing?: string; - /** - * Delay between each block show up, in ms. (default: 200) - */ - delay?: number; - } - - export interface RoyalSliderVisibleOptions { - /** - * Enable visible-nearby. (default: true) - */ - enabled?: boolean; - /** - * Ratio that determines area of center image.For example for 0.6 - 60 % of slider area will get center image and 20% for two images on sides. (default: 0.6) - */ - centerArea?: number; - /** - * Alignment of center image, if you set it to false center image will be aligned to left. (default: true) - */ - center?: boolean; - /** - * Disables navigation to next slide by clicking on current slide (if navigateByClick is true). (default: true) - */ - navigateByCenterClick?: boolean; - /** - * Used for responsive design. Changes centerArea value to breakpointCenterArea when width of slider is less then value in this option. Set to 0 to disable. (default: 0) - */ - breakpoint?: number; - /** - * Same as centerArea option, just for breakpoint. Can be changed dynamically via `sliderInstance.st.breakpointCenterArea`. (default: 0.8) - */ - breakpointCenterArea?: number; - } - - export interface RoyalSliderOptions { - /** - * Automatically updates slider height based on base width. (default: false) - */ - autoScaleSlider?: boolean; - /** - * Base slider width.Slider will autocalculate the ratio based on these values. (default: 800) - */ - autoScaleSliderWidth?: number; - /** - * 400 Base slider height - */ - autoScaleSliderHeight?: number; - /** - * Scale mode for images."fill", "fit", "fit-if-smaller" or "none". (default: 'fit-if-smaller') - */ - imageScaleMode?: string; - /** - * Aligns image to center of slide. (default: true) - */ - imageAlignCenter?: boolean; - /** - * Distance between image and edge of slide (doesn't work with 'fill' scale mode). (default: 4) - */ - imageScalePadding?: number; - /** - * Navigation type, can be 'bullets', 'thumbnails', 'tabs' or 'none' (default: 'bullets') - */ - controlNavigation?: string; - /** - * Direction arrows navigation. (default: true) - */ - arrowsNav?: boolean; - /** - * Auto hide arrows. (default: true) - */ - arrowsNavAutoHide?: boolean; - /** - * Hides arrows completely on touch devices. (default: false) - */ - arrowsNavHideOnTouch?: boolean; - /** - * Adds base width to all images for better-looking loading. Can be specified separately for each image. (default: null) - */ - imgWidth?: number; - /** - * Adds base height to all images for better-looking loading. Can be specified separately for each image. (default: null) - */ - imgHeight?: number; - /** - * Spacing between slides in pixels. (default: 8) - */ - slidesSpacing?: number; - /** - * Start slide index. (default: 0) - */ - startSlideId?: number; - /** - * Makes slider to go from last slide to first. (default: false) - */ - loop?: boolean; - /** - * Makes slider to go from last slide to first with rewind. Overrides prev option. (default: false) - */ - loopRewind?: boolean; - /** - * Randomizes all slides at start. (default: false) - */ - randomizeSlides?: boolean; - /** - * Number of slides to preload on sides.If you set it to 0, only one slide will be kept in the display list at once. (default: 4) - */ - numImagesToPreload?: number; - /** - * Enables spinning preloader, you may style it via CSS (class rsPreloader). (default: true) - */ - usePreloader?: boolean; - /** - * Can be 'vertical' or 'horizontal'. (default: 'horizontal') - */ - slidesOrientation?: string; - /** - * 'move' or 'fade'. Important note about fade transition, slides must have background as only one image is animating. (default: 'move') - */ - transitionType?: string; - /** - * Slider transition speed, in ms. (default: 600) - */ - transitionSpeed?: number; - /** - * Easing function for simple transition.Read more in the easing section of the documentation. (default: 'easeInOutSine') - */ - easeInOut?: string; - /** - * Easing function of animation after ending of the swipe gesture. Read more in the easing section of the documentation. (default: 'easeOutSine') - */ - easeOut?: string; - /** - * If set to true adds arrows and fullscreen button inside rsOverflow container, otherwise inside root slider container. (default: true) - */ - controlsInside?: boolean; - /** - * Navigates forward by clicking on slide. (default: true) - */ - navigateByClick?: boolean; - /** - * Mouse drag navigation over slider. (default: true) - */ - sliderDrag?: boolean; - /** - * Touch navigation of slider. (default: true) - */ - sliderTouch?: boolean; - /** - * Navigate slider with keyboard left and right arrows. (default: false) - */ - keyboardNavEnabled?: boolean; - /** - * Fades in slide after it's loaded. (default: true) - */ - fadeinLoadedSlide?: boolean; - /** - * Allows usage of CSS3 transitions. Might be useful if you're experiencing font-rendering problems, or other CSS3-related bugs. (default: true) - */ - allowCSS3?: boolean; - /** - * Adds global caption element to slider, read more in the global caption section of documentation. (default: false) - */ - globalCaption?: boolean; - /** - * Adds rsActiveSlide class to current slide before transition. (default: false) - */ - addActiveClass?: boolean; - /** - * Minimum distance in pixels to show next slide while dragging. (default: 10) - */ - minSlideOffset?: number; - /** - * Scales and animates height based on current slide. Please note: if you have images in slide that don't have rsImg class) or don't have fixed size, use $(window).load() instead of $(document).ready() before initializing slider. Also, autoHeight doesn't work with properties like autoScaleSlider, imageScaleMode and imageAlignCenter. (default: false) - */ - autoHeight?: boolean;// false - /** - * Overrides HTML of slides, used for creating of slides from HTML that is not attached to DOM. More info in knowledge base. (default: null) - */ - slides?: Element; - /** - * Thumbnail options - */ - thumbs?: RoyalSliderThumbsOptions; - /** - * You may specify larger images when slider is in fullscreen mode by adding data-rsBigImg attribute to rsImg element. A few examples: - */ - fullscreen?: RoyalSliderFullscreenOptions; - /** - * Deep linking module makes URL automatically change when you switch slides and you can easily link to specific slide (aka permalink). - */ - deeplinking?: RoyalSliderDeeplinkingOptions; - /** - * Autoplay slideshow can be enabled via slider options. Delay between items can be set globally via delay option, or specifically for each item by adding data-rsDelay="1000" to root element of the slide (1000 = 1sec). - */ - autoplay?: RoyalSliderAutoplayOptions; - /** - * To add video to slide, you need to add data-rsVideo="" attribute to image. It can contain link to YouTube or Vimeo video. - */ - video?: RoyalSliderVideoOptions; - /** - * All elements inside slide that have class rsABlock will be treated by slider as animated blocks (tag name doesn't matter). Blocks can not be nested, but you can put multiple instances of them into one slide, or make slide itself animated block. - */ - block?: RoyalSliderBlockOptions; - /** - * Module "reveals" next and previous slides, like in this template. - */ - visibleNearby?: RoyalSliderVisibleOptions; - } - - export interface RoyalSlider { //TODO: extends/implements JQuery? (giving problems due to next(), prev(), width and height and 'selector'. - /** - * go to slide with id - */ - goTo(id: number): void; - /** - * next slide - */ - next(): void; - /** - * prev slide - */ - prev(): void; - /** - * removes all events and clears all slider data (use on ajax sites to avoid memory leaks) - */ - destroy(): void; - /** - * Dynamic slides adding/removing - */ - appendSlide(element: JQuery, index?: number): void; - /** - * Remove slide - */ - removeSlide(index?: number): void; - /** - * updates size of slider. Use after you resize slider with js. - */ - updateSliderSize(forceResize?: boolean): void; - /** - * changes orientation of thumbnails - */ - setThumbsOrientation(orientation: string): void; - /** - * updates size of thumbnails - */ - updateThumbsSize(): void; - /** - * Enter Fullscreen mode - */ - enterFullscreen(): void; - /** - * Exit Fullscreen mode - */ - exitFullscreen(): void; - /** - * Start autoplay - */ - startAutoPlay(): void; - /** - * Stop autoplay - */ - stopAutoPlay(): void; - /** - * Toggle autoplay between start and stop - */ - toggleAutoPlay(): void; - /** - * Toggle video between start and stop - */ - toggleVideo(): void; - /** - * Play video - */ - playVideo(): void; - /** - * Stop video - */ - stopVideo(): void; - /** - * current slide index - */ - currSlideId: number; - /** - * current slide object - */ - currSlide: JQuery; - /** - * total number of slides - */ - numSlides: number; - /** - * indicates if slider is in fullscreen mode - */ - isFullscreen: boolean; - /** - * indicates if browser supports native fullscreen - */ - nativeFS: boolean; - /** - * width of slider - */ - width: number; - /** - * height of slider - */ - height: number; - /** - * Boolean, changes on mouseup, indicates if slide was dragged. Used to check if event is drag or click. - */ - dragSuccess: boolean; - /** - * contains all data about each slide - */ - slides: any[]; //TODO: what type? - /** - * Contains list of HTML slides that are added to slider - */ - slidesJQ: JQuery[]; //TODO: what type? - /** - * Object with slider settings - */ - st: RoyalSliderOptions; - /** - * jQuery object with slider events - */ - ev: JQuery; - } -} - -interface JQuery { - /** - * Creates a new royal-slider with the specified, or default, options. - * - * @param options The options - */ - royalSlider(options?: RoyalSlider.RoyalSliderOptions): JQuery; +// Type definitions for jQuery royal-slider v9.4.0 +// Project: http://dimsemenov.com/plugins/royal-slider/documentation/ +// Definitions by: Christiaan Rakowski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module RoyalSlider { + export interface RoyalSliderThumbsOptions { + /** + * Thumbnails mouse drag. (default: true) + */ + drag?: boolean; + /** + * Thumbnails touch. (default: true) + */ + touch?: boolean; + /** + * 'horizontal' or 'vertical'. (default: 'horizontal') + */ + orientation?: string; + /** + * Thumbnails arrows. (default: true) + */ + arrows?: boolean; + /** + * Spacing between thumbs. (default: 4) + */ + spacing?: number; + /** + * Auto hide thumbnails arrows on hover. (default: false) + */ + arrowsAutoHide?: boolean; + /** + * Automatically centers container with thumbs if there are small number of items (default: true) + */ + autoCenter?: boolean; + /** + * Thumbnails transition speed. (default: 600) + */ + transitionSpeed?: number; + /** + * Reduces size of main viewport area by thumbnails width or height, use it when you set 100 % width to slider.This option is always true, when slider is in fullscreen mode. (default: true) + */ + fitInViewport?: boolean; + /** + * Margin that equals thumbs spacing for first and last item. (default: true) + */ + firstMargin?: boolean; + /** + * Replaces default thumbnail arrow. You have to add it to DOM manually. (default: null) + */ + arrowLeft?: JQuery; + /** + * Replaces default thumbnail arrow. You have to add it to DOM manually. (default: null) + */ + arrowRight?: JQuery; + /** + * Adds span element with class thumbIco to every thumbnail. Useful for styling (default: false) + */ + appendSpan?: boolean; + } + + export interface RoyalSliderFullscreenOptions { + /** + * Fullscreen functions enabled. (default: false) + */ + enabled?: boolean; + /** + * Force keyboard arrows nav in fullscreen. (default: true) + */ + keyboardNav?: boolean; + /** + * Fullscreen button at top right. (default: true) + */ + buttonFS?: boolean; + /** + * Native browser fullscreen. (default: false) + */ + nativeFS?: boolean; + } + + export interface RoyalSliderDeeplinkingOptions { + /** + * Linking to slides by appending #SLIDE_INDEX to url.Slides count starts from 1. If change is set to false hash is only read once, after page load. (default: false) + */ + enabled?: boolean; + /** + * Automatically change URL after transition and listen for hash change. (default: false) + */ + change?: boolean; + /** + * Prefix that will be added to hash. For example if you set it to 'gallery-', hash would look like this: #gallery-5 (default: '') + */ + prefix?: string; + } + + export interface RoyalSliderAutoplayOptions { + /** + * Enable autoplay or not. (default: false) + */ + enabled?: boolean; + /** + * Stop autoplay at first user action. (default: true) + */ + stopAtAction?: boolean; + /** + * Pause autoplay on hover. (default: true) + */ + pauseOnHover?: boolean; + /** + * Delay between items in ms. (default: 300) + */ + delay?: number; + } + + export interface RoyalSliderVideoOptions { + /** + * Auto hide arrows when video is playing (default: true) + */ + autoHideArrows?: boolean; + /** + * Auto hide navigation when video is playing. (default: false) + */ + autoHideControlNav?: boolean; + /** + * Auto hide animated blocks when video is playing. (default: false) + */ + autoHideBlocks?: boolean; + /** + * Youtube embed code. %id% is replaced by video id. (default: '') + */ + youTubeCode?: string; + /** + * Vimeo embed code. %id% is replaced by video id. (default: '') + */ + vimeoCode?: string; + } + + export interface RoyalSliderBlockOptions { + /** + * true or false (default: true) + */ + fadeEffect?: boolean; + /** + * Move effect direction.Can be 'left', 'right', 'top', 'bottom' or 'none'. (default: 'top') + */ + moveEffect?: string; + /** + * Distance for move effect in pixels. (default: 20) + */ + moveOffset?: number; + /** + * Transition speed of block, in ms. (default: 400) + */ + speed?: number; + /** + * Easing function of block animation.Read more in easing section of docs. (default: 'easeOutSine' ) + */ + easing?: string; + /** + * Delay between each block show up, in ms. (default: 200) + */ + delay?: number; + } + + export interface RoyalSliderVisibleOptions { + /** + * Enable visible-nearby. (default: true) + */ + enabled?: boolean; + /** + * Ratio that determines area of center image.For example for 0.6 - 60 % of slider area will get center image and 20% for two images on sides. (default: 0.6) + */ + centerArea?: number; + /** + * Alignment of center image, if you set it to false center image will be aligned to left. (default: true) + */ + center?: boolean; + /** + * Disables navigation to next slide by clicking on current slide (if navigateByClick is true). (default: true) + */ + navigateByCenterClick?: boolean; + /** + * Used for responsive design. Changes centerArea value to breakpointCenterArea when width of slider is less then value in this option. Set to 0 to disable. (default: 0) + */ + breakpoint?: number; + /** + * Same as centerArea option, just for breakpoint. Can be changed dynamically via `sliderInstance.st.breakpointCenterArea`. (default: 0.8) + */ + breakpointCenterArea?: number; + } + + export interface RoyalSliderOptions { + /** + * Automatically updates slider height based on base width. (default: false) + */ + autoScaleSlider?: boolean; + /** + * Base slider width.Slider will autocalculate the ratio based on these values. (default: 800) + */ + autoScaleSliderWidth?: number; + /** + * 400 Base slider height + */ + autoScaleSliderHeight?: number; + /** + * Scale mode for images."fill", "fit", "fit-if-smaller" or "none". (default: 'fit-if-smaller') + */ + imageScaleMode?: string; + /** + * Aligns image to center of slide. (default: true) + */ + imageAlignCenter?: boolean; + /** + * Distance between image and edge of slide (doesn't work with 'fill' scale mode). (default: 4) + */ + imageScalePadding?: number; + /** + * Navigation type, can be 'bullets', 'thumbnails', 'tabs' or 'none' (default: 'bullets') + */ + controlNavigation?: string; + /** + * Direction arrows navigation. (default: true) + */ + arrowsNav?: boolean; + /** + * Auto hide arrows. (default: true) + */ + arrowsNavAutoHide?: boolean; + /** + * Hides arrows completely on touch devices. (default: false) + */ + arrowsNavHideOnTouch?: boolean; + /** + * Adds base width to all images for better-looking loading. Can be specified separately for each image. (default: null) + */ + imgWidth?: number; + /** + * Adds base height to all images for better-looking loading. Can be specified separately for each image. (default: null) + */ + imgHeight?: number; + /** + * Spacing between slides in pixels. (default: 8) + */ + slidesSpacing?: number; + /** + * Start slide index. (default: 0) + */ + startSlideId?: number; + /** + * Makes slider to go from last slide to first. (default: false) + */ + loop?: boolean; + /** + * Makes slider to go from last slide to first with rewind. Overrides prev option. (default: false) + */ + loopRewind?: boolean; + /** + * Randomizes all slides at start. (default: false) + */ + randomizeSlides?: boolean; + /** + * Number of slides to preload on sides.If you set it to 0, only one slide will be kept in the display list at once. (default: 4) + */ + numImagesToPreload?: number; + /** + * Enables spinning preloader, you may style it via CSS (class rsPreloader). (default: true) + */ + usePreloader?: boolean; + /** + * Can be 'vertical' or 'horizontal'. (default: 'horizontal') + */ + slidesOrientation?: string; + /** + * 'move' or 'fade'. Important note about fade transition, slides must have background as only one image is animating. (default: 'move') + */ + transitionType?: string; + /** + * Slider transition speed, in ms. (default: 600) + */ + transitionSpeed?: number; + /** + * Easing function for simple transition.Read more in the easing section of the documentation. (default: 'easeInOutSine') + */ + easeInOut?: string; + /** + * Easing function of animation after ending of the swipe gesture. Read more in the easing section of the documentation. (default: 'easeOutSine') + */ + easeOut?: string; + /** + * If set to true adds arrows and fullscreen button inside rsOverflow container, otherwise inside root slider container. (default: true) + */ + controlsInside?: boolean; + /** + * Navigates forward by clicking on slide. (default: true) + */ + navigateByClick?: boolean; + /** + * Mouse drag navigation over slider. (default: true) + */ + sliderDrag?: boolean; + /** + * Touch navigation of slider. (default: true) + */ + sliderTouch?: boolean; + /** + * Navigate slider with keyboard left and right arrows. (default: false) + */ + keyboardNavEnabled?: boolean; + /** + * Fades in slide after it's loaded. (default: true) + */ + fadeinLoadedSlide?: boolean; + /** + * Allows usage of CSS3 transitions. Might be useful if you're experiencing font-rendering problems, or other CSS3-related bugs. (default: true) + */ + allowCSS3?: boolean; + /** + * Adds global caption element to slider, read more in the global caption section of documentation. (default: false) + */ + globalCaption?: boolean; + /** + * Adds rsActiveSlide class to current slide before transition. (default: false) + */ + addActiveClass?: boolean; + /** + * Minimum distance in pixels to show next slide while dragging. (default: 10) + */ + minSlideOffset?: number; + /** + * Scales and animates height based on current slide. Please note: if you have images in slide that don't have rsImg class) or don't have fixed size, use $(window).load() instead of $(document).ready() before initializing slider. Also, autoHeight doesn't work with properties like autoScaleSlider, imageScaleMode and imageAlignCenter. (default: false) + */ + autoHeight?: boolean;// false + /** + * Overrides HTML of slides, used for creating of slides from HTML that is not attached to DOM. More info in knowledge base. (default: null) + */ + slides?: Element; + /** + * Thumbnail options + */ + thumbs?: RoyalSliderThumbsOptions; + /** + * You may specify larger images when slider is in fullscreen mode by adding data-rsBigImg attribute to rsImg element. A few examples: + */ + fullscreen?: RoyalSliderFullscreenOptions; + /** + * Deep linking module makes URL automatically change when you switch slides and you can easily link to specific slide (aka permalink). + */ + deeplinking?: RoyalSliderDeeplinkingOptions; + /** + * Autoplay slideshow can be enabled via slider options. Delay between items can be set globally via delay option, or specifically for each item by adding data-rsDelay="1000" to root element of the slide (1000 = 1sec). + */ + autoplay?: RoyalSliderAutoplayOptions; + /** + * To add video to slide, you need to add data-rsVideo="" attribute to image. It can contain link to YouTube or Vimeo video. + */ + video?: RoyalSliderVideoOptions; + /** + * All elements inside slide that have class rsABlock will be treated by slider as animated blocks (tag name doesn't matter). Blocks can not be nested, but you can put multiple instances of them into one slide, or make slide itself animated block. + */ + block?: RoyalSliderBlockOptions; + /** + * Module "reveals" next and previous slides, like in this template. + */ + visibleNearby?: RoyalSliderVisibleOptions; + } + + export interface RoyalSlider { //TODO: extends/implements JQuery? (giving problems due to next(), prev(), width and height and 'selector'. + /** + * go to slide with id + */ + goTo(id: number): void; + /** + * next slide + */ + next(): void; + /** + * prev slide + */ + prev(): void; + /** + * removes all events and clears all slider data (use on ajax sites to avoid memory leaks) + */ + destroy(): void; + /** + * Dynamic slides adding/removing + */ + appendSlide(element: JQuery, index?: number): void; + /** + * Remove slide + */ + removeSlide(index?: number): void; + /** + * updates size of slider. Use after you resize slider with js. + */ + updateSliderSize(forceResize?: boolean): void; + /** + * changes orientation of thumbnails + */ + setThumbsOrientation(orientation: string): void; + /** + * updates size of thumbnails + */ + updateThumbsSize(): void; + /** + * Enter Fullscreen mode + */ + enterFullscreen(): void; + /** + * Exit Fullscreen mode + */ + exitFullscreen(): void; + /** + * Start autoplay + */ + startAutoPlay(): void; + /** + * Stop autoplay + */ + stopAutoPlay(): void; + /** + * Toggle autoplay between start and stop + */ + toggleAutoPlay(): void; + /** + * Toggle video between start and stop + */ + toggleVideo(): void; + /** + * Play video + */ + playVideo(): void; + /** + * Stop video + */ + stopVideo(): void; + /** + * current slide index + */ + currSlideId: number; + /** + * current slide object + */ + currSlide: JQuery; + /** + * total number of slides + */ + numSlides: number; + /** + * indicates if slider is in fullscreen mode + */ + isFullscreen: boolean; + /** + * indicates if browser supports native fullscreen + */ + nativeFS: boolean; + /** + * width of slider + */ + width: number; + /** + * height of slider + */ + height: number; + /** + * Boolean, changes on mouseup, indicates if slide was dragged. Used to check if event is drag or click. + */ + dragSuccess: boolean; + /** + * contains all data about each slide + */ + slides: any[]; //TODO: what type? + /** + * Contains list of HTML slides that are added to slider + */ + slidesJQ: JQuery[]; //TODO: what type? + /** + * Object with slider settings + */ + st: RoyalSliderOptions; + /** + * jQuery object with slider events + */ + ev: JQuery; + } +} + +interface JQuery { + /** + * Creates a new royal-slider with the specified, or default, options. + * + * @param options The options + */ + royalSlider(options?: RoyalSlider.RoyalSliderOptions): JQuery; } \ No newline at end of file diff --git a/rtree/rtree.d.ts b/rtree/rtree.d.ts index fa6276c6e..752d2e89e 100644 --- a/rtree/rtree.d.ts +++ b/rtree/rtree.d.ts @@ -1,25 +1,25 @@ -// Type definitions for rtree 1.4.0 -// Project: https://github.com/leaflet-extras/RTree -// Definitions by: Omede Firouz -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Rectangle { - x: number; - y: number; - w: number; - h: number; -} - -interface RTreeStatic { - insert(bounds: Rectangle, element: Object): boolean; - remove(area: Rectangle, element?: Object): any[]; - geoJSON(geoJSON: any): void; - bbox(arg1: any, arg2?: any, arg3?: number, arg4?: number): any[]; - search(area: Rectangle, return_node?: boolean, return_array?: any[]): any[]; -} - -interface RTreeFactory { - (max_node_width?: number): RTreeStatic; -} - -declare var RTree: RTreeFactory; +// Type definitions for rtree 1.4.0 +// Project: https://github.com/leaflet-extras/RTree +// Definitions by: Omede Firouz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Rectangle { + x: number; + y: number; + w: number; + h: number; +} + +interface RTreeStatic { + insert(bounds: Rectangle, element: Object): boolean; + remove(area: Rectangle, element?: Object): any[]; + geoJSON(geoJSON: any): void; + bbox(arg1: any, arg2?: any, arg3?: number, arg4?: number): any[]; + search(area: Rectangle, return_node?: boolean, return_array?: any[]): any[]; +} + +interface RTreeFactory { + (max_node_width?: number): RTreeStatic; +} + +declare var RTree: RTreeFactory; diff --git a/rx-angular/rx.angular-tests.ts b/rx-angular/rx.angular-tests.ts index 3caf01170..32240b660 100644 --- a/rx-angular/rx.angular-tests.ts +++ b/rx-angular/rx.angular-tests.ts @@ -1,21 +1,21 @@ -// Type definitions for angularjs extensions to rxjs -// Project: http://reactivex.io/ -// Definitions by: Mick Delaney -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -var app = angular.module('testModule'); - -interface AppScope extends rx.angular.IRxScope { -} - -app.controller('Ctrl', ($scope: AppScope) => { - - this.inputObservable = $scope.$toObservable('term') - .throttle(400) - .safeApply($scope, (results: any) => { - this.results = results; - }); - -}); +// Type definitions for angularjs extensions to rxjs +// Project: http://reactivex.io/ +// Definitions by: Mick Delaney +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +var app = angular.module('testModule'); + +interface AppScope extends rx.angular.IRxScope { +} + +app.controller('Ctrl', ($scope: AppScope) => { + + this.inputObservable = $scope.$toObservable('term') + .throttle(400) + .safeApply($scope, (results: any) => { + this.results = results; + }); + +}); diff --git a/rx-angular/rx.angular.d.ts b/rx-angular/rx.angular.d.ts index 8b1b94d84..c7dfceff7 100644 --- a/rx-angular/rx.angular.d.ts +++ b/rx-angular/rx.angular.d.ts @@ -1,33 +1,33 @@ -// Type definitions for angularjs extensions to rxjs -// Project: http://reactivex.io/ -// Definitions by: Mick Delaney -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// -/// - -declare module Rx { - - interface IObservable { - safeApply($scope: ng.IScope, callback: (data: T) => void): Rx.Observable; - } - - export interface ScopeScheduler extends IScheduler { - constructor(scope: ng.IScope) : ScopeScheduler; - } - - export interface ScopeSchedulerStatic extends SchedulerStatic { - new ($scope: angular.IScope): ScopeScheduler; - } - - export var ScopeScheduler: ScopeSchedulerStatic; -} - -declare module rx.angular { - - export interface IRxScope extends ng.IScope { - $toObservable(property: string): Rx.Observable; - } -} - +// Type definitions for angularjs extensions to rxjs +// Project: http://reactivex.io/ +// Definitions by: Mick Delaney +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +declare module Rx { + + interface IObservable { + safeApply($scope: ng.IScope, callback: (data: T) => void): Rx.Observable; + } + + export interface ScopeScheduler extends IScheduler { + constructor(scope: ng.IScope) : ScopeScheduler; + } + + export interface ScopeSchedulerStatic extends SchedulerStatic { + new ($scope: angular.IScope): ScopeScheduler; + } + + export var ScopeScheduler: ScopeSchedulerStatic; +} + +declare module rx.angular { + + export interface IRxScope extends ng.IScope { + $toObservable(property: string): Rx.Observable; + } +} + diff --git a/s3rver/s3rver-tests.ts b/s3rver/s3rver-tests.ts index afa7e9227..d8f25f4fb 100644 --- a/s3rver/s3rver-tests.ts +++ b/s3rver/s3rver-tests.ts @@ -1,14 +1,14 @@ -/// - -import S3rver = require('s3rver'); - -var s3rver = new S3rver({ - port: 5694, - hostname: 'localhost', - silent: true, - indexDocument: 'index.html', - errorDocument: '', - directory: '/tmp/s3rver_test_directory' -}).run((err, hostname, port, directory) => {}); - -s3rver.close(); +/// + +import S3rver = require('s3rver'); + +var s3rver = new S3rver({ + port: 5694, + hostname: 'localhost', + silent: true, + indexDocument: 'index.html', + errorDocument: '', + directory: '/tmp/s3rver_test_directory' +}).run((err, hostname, port, directory) => {}); + +s3rver.close(); diff --git a/s3rver/s3rver.d.ts b/s3rver/s3rver.d.ts index e34650986..3eb6c73be 100644 --- a/s3rver/s3rver.d.ts +++ b/s3rver/s3rver.d.ts @@ -1,32 +1,32 @@ -// Type definitions for S3rver -// Project: https://github.com/jamhall/s3rver -// Definitions by: David Broder-Rodgers -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "s3rver" { - import * as http from "http"; - - class S3rver { - constructor(options: S3rverOptions) - setPort(port: number): S3rver; - setHostname(hostname: string): S3rver; - setDirectory(directory: string): S3rver; - setSilent(silent: boolean): S3rver; - setIndexDocument(indexDocument: string): S3rver; - setErrorDocument(errorDocument: string): S3rver; - run(callback: (error: Error, hostname: string, port: number, directory: string) => void): http.Server; - } - - interface S3rverOptions { - port?: number; - hostname?: string; - silent?: boolean; - indexDocument?: string; - errorDocument?: string; - directory: string; - } - - export = S3rver; -} +// Type definitions for S3rver +// Project: https://github.com/jamhall/s3rver +// Definitions by: David Broder-Rodgers +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "s3rver" { + import * as http from "http"; + + class S3rver { + constructor(options: S3rverOptions) + setPort(port: number): S3rver; + setHostname(hostname: string): S3rver; + setDirectory(directory: string): S3rver; + setSilent(silent: boolean): S3rver; + setIndexDocument(indexDocument: string): S3rver; + setErrorDocument(errorDocument: string): S3rver; + run(callback: (error: Error, hostname: string, port: number, directory: string) => void): http.Server; + } + + interface S3rverOptions { + port?: number; + hostname?: string; + silent?: boolean; + indexDocument?: string; + errorDocument?: string; + directory: string; + } + + export = S3rver; +} diff --git a/sammyjs/sammyjs-tests.ts b/sammyjs/sammyjs-tests.ts index 1aa151d6e..6a54a8019 100644 --- a/sammyjs/sammyjs-tests.ts +++ b/sammyjs/sammyjs-tests.ts @@ -1,554 +1,554 @@ -/// - -function test_general() { - // Example from homepage - var app = Sammy('#main', function () { - var _this: Sammy.Application = this; - _this.use('Mustache'); - _this.get('#/', function () { - var _this: Sammy.RenderContext; - _this.load('posts.json') - .renderEach('post.mustache') - .swap(); - }); - }); - - app.run('#/'); - - var _this: Sammy.Application; - _this.get('#/', function (context) { - var _this: Sammy.RenderContext; - _this.load('data/items.json') - .then(function (items) { - $.each(items, function (i, item) { - context.log(item.title, '-', item.artist); - }); - }); - }); -} - -function test_app() { - var s = new Sammy.Object({ first_name: 'Sammy', last_name: 'Davis Jr.' }); - s.toHTML(); - - var app = $.sammy(function () { - - var current_user = false; - function checkLoggedIn(callback) { - var _this: Sammy.EventContext; - if (!current_user) { - $.getJSON('/session', function (json) { - if (json.login) { - current_user = json; - callback(); - } else { - current_user = false; - _this.redirect('#/login'); - } - }); - } else { - callback(); - } - }; - var _this: Sammy.Application; - _this.around(checkLoggedIn); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.before('#/route', function () { }); - _this.before({ except: { path: '#/route' } }, function () { - _this.log('not before #/route'); - }); - _this.get('#/', function () { }); - _this.get('#/route', function () { }); - }); - - var app = $.sammy(), - context = { verb: 'get', path: '#/mypath' }; - - app.contextMatchesOptions(context, '#/mypath'); - app.contextMatchesOptions(context, '#/otherpath'); - app.contextMatchesOptions(context, { only: { path: '#/mypath' } }); - app.contextMatchesOptions(context, { only: { path: '#/otherpath' } }); - app.contextMatchesOptions(context, /path/); - app.contextMatchesOptions(context, /^path/); - app.contextMatchesOptions(context, { only: { verb: 'get' } }); - app.contextMatchesOptions(context, { only: { verb: 'post' } }); - app.contextMatchesOptions(context, { except: { verb: 'post' } }); - app.contextMatchesOptions(context, { except: { verb: 'get' } }); - app.contextMatchesOptions(context, { except: { path: '#/otherpath' } }); - app.contextMatchesOptions(context, { except: { path: '#/mypath' } }); - app.contextMatchesOptions(context, { path: ['#/mypath', '#/otherpath'] }); - app.contextMatchesOptions(context, { path: ['#/otherpath', '#/thirdpath'] }); - app.contextMatchesOptions(context, { only: { path: ['#/mypath', '#/otherpath'] } }); - app.contextMatchesOptions(context, { only: { path: ['#/otherpath', '#/thirdpath'] } }); - app.contextMatchesOptions(context, { except: { path: ['#/mypath', '#/otherpath'] } }); - app.contextMatchesOptions(context, { except: { path: ['#/otherpath', '#/thirdpath'] } }); - - var app = $.sammy(function (app) { - var _this: Sammy.Application; - $.each([1, 2, 3], function (i, num) { - app.helper('helper' + num, function () { - _this.log("I'm helper number " + num); - }); - }); - _this.get('#/', function () { - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - var better = _this.helpers({ - upcase: function (text) { - return text.toString().toUpperCase(); - } - }); - better.get('#/', function () { - $('#main').html(better.upcase($('#main').text())); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.mapRoutes([ - ['get', '#/', function () { }], - ['post', '#/create', 'addUser'], - [/dowhatever/, function () { }] - ]); - }); - - var app = $.sammy(function () { }); - $(function () { - app.run(); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.setLocationProxy(new Sammy.DataLocationProxy(_this)); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.swap = function (content, callback) { - var context = _this; - context.$element().fadeOut('slow', function () { - context.$element().html(content); - context.$element().fadeIn('slow', function () { - if (callback) { - callback.apply(this); - } - }); - }); - }; - }); - - var MyPlugin = function (app, prepend) { - var _this: Sammy.Application; - _this.helpers({ - myhelper: function (text) { - alert(prepend + " " + text); - } - }); - }; - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(MyPlugin, '_this is my plugin'); - _this.get('#/', function () { - }); - }); - - $.sammy(function () { - var _this: Sammy.Application; - _this.use('Mustache'); - _this.use('Storage'); - }); -} - -function test_misc() { - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.setLocationProxy(new Sammy.DataLocationProxy(_this, 'location', 'rel')); - _this.get('about', function () { - var _this: Sammy.EventContext; - _this.partial('about.html'); - }); - }); - - $.sammy(function () { - var _this: Sammy.Application; - _this.get('#/:name', function () { - var _evt: Sammy.EventContext = this; - if (_evt.params['name'] == 'sammy') { - _evt.partial('name.html.erb', { name: 'Sammy' }); - } else { - _evt.redirect('#/somewhere-else') - } - }); - }); - - function evtContextTests() { - var _this: Sammy.EventContext; - _this.redirect('#/other/route'); - _this.redirect('#', 'other', 'route'); - _this.render('mytemplate.mustache', { name: 'quirkey' }) - .appendTo('ul'); - _this.renderEach('mytemplate.mustache', [{ name: 'quirkey' }, { name: 'endor' }]); - - var item = { - name: 'My Item', - price: '$25.50', - meta: { - id: '123' - } - }; - var form = new Sammy.FormBuilder('item', item); - form.text('name'); - - var options = [ - ['Small', 's'], - ['Medium', 'm'], - ['Large', 'l'] - ]; - form.select('size', options); - - $.sammy(function () { - var _this: Sammy.Application; - _this.use('GoogleAnalytics') - _this.get('#/dont/track/me', function () { - var evt: Sammy.GoogleAnalytics = this; - evt.noTrack(); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(Sammy.Haml); - _this.get('#/hello/:name', function () { - var evt: Sammy.Haml = this; - evt.title = 'Hello!'; - evt.name = evt.params.name; - evt.partial('mytemplate.haml'); - }); - }); - app.run() - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Handlebars', 'hb'); - _this.get('#/hello/:name', function () { - var evt: Sammy.Handlebars = this; - evt.title = 'Hello!' - evt.name = evt.params.name; - evt.partial('mytemplate.hb'); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Handlebars', 'hb'); - _this.get('#/hello/:name/to/:friend', function (context: Sammy.Handlebars) { - context.load('mypartial.hb') - .then(function (partial) { - context.partials = { hello_friend: partial }; - context.name = context.params.name; - // dynamically add a property to the context - (context).friend = context.params.friend; - context.partial('mytemplate.hb'); - }); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Hogan', 'hg'); - _this.get('#/hello/:name', function () { - var evt: Sammy.Hogan = this; - evt.title = 'Hello!' - evt.name = evt.params.name; - evt.partial('mytemplate.hg'); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Hogan', 'hg'); - _this.get('#/hello/:name/to/:friend', function (context) { - context.load('mypartial.hg') - .then(function (partial) { - context.partials = { hello_friend: partial }; - context.name = context.params.name; - context.friend = context.params.friend; - context.partial('mytemplate.hg'); - }); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(Sammy.JSON); - _this.get('#/', function () { - var evt: Sammy.JSON = this; - evt.json({ user_id: 123 }); - evt.json("{\"user_id\":\"123\"}"); - evt.json("{\"user_id\":\"123\"}").user_id; - }); - }) - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Mustache', 'ms'); - _this.get('#/hello/:name', function () { - var evt: Sammy.Mustache = this; - evt.title = 'Hello!' - evt.name = evt.params.name; - evt.partial('mytemplate.ms'); - }); - }); - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use('Mustache', 'ms'); - _this.get('#/hello/:name/to/:friend', function (context: Sammy.Mustache) { - context.load('mypartial.ms') - .then(function (partial) { - context.partials = { hello_friend: partial }; - context.name = context.params.name; - (context).friend = context.params.friend; - context.partial('mytemplate.ms'); - }); - }); - }); - - var app = $.sammy(function (app) { - var _this: Sammy.Application; - _this.use(Sammy.NestedParams); - _this.post('#/parse_me', function (context) { - $.log(context.params); - }); - }); - }; - - var _this: Sammy.Application; - _this.use('Storage'); - _this.use('OAuth2'); - _this.oauthorize = "/oauth/authorize"; - _this.requireOAuth(); - _this.requireOAuth("/private"); - _this.before(function (context) { return context.requireOAuth(); }) - _this.get("/private", function (context) { - _this.requireOAuth(function () { }); - }); - _this.bind("oauth.connected", function () { $("#signin").hide() }); - _this.bind("oauth.disconnected", function () { $("#signin").show() }); - _this.bind("oauth.denied", function (evt, error) { - evt.partial("admin/views/no_access.tmpl", { error: error.message }); - }); - _this.get("#/signout", function (context) { - context.loseAccessToken(); - context.redirect("#/"); - }); - - _this.get('#/', function () { - this.render('mytemplate.template', { name: 'test' }); - }); - - _this.send($.getJSON, '/app.json') - .then(function (json) { - $('#message').text(json['message']); - } - ); - - _this.get('#/', function () { - var evt: Sammy.EventContext = this; - evt.load('myfile.txt') - .then(function (content) { - $('#main').html(content); - }); - }); - - _this.get('#/', function () { - var evt: Sammy.EventContext = this; - evt.load('mytext.json') - .then(function (content) { - var context = this, - data = JSON.parse(content); - context.wait(); - $.post(data.url, {}, function (response) { - context.next(JSON.parse(response)); - }); - }) - .then(function (data) { - $('#message').text(data.status); - }); - }); - - var store = new Sammy.Store({ name: 'mystore', element: '#element', type: 'local' }); - store.set('foo', 'bar'); - store.get('foo'); - store.set('json', { obj: '_this is an obj' }); - store.get('json'); - store.keys(); - store.clear('foo'); - store.keys(); - store.clearAll(); - store.keys(); - - store.each(function (key, value) { - Sammy.log('key', key, 'value', value); - }); - - store = new Sammy.Store(); - store.exists('foo'); - store.fetch('foo', function () { - return 'bar!'; - }); - store.get('foo'); - store.fetch('foo', function () { - return 'baz!'; - }); - - store = new Sammy.Store(); - store.set('one', 'two'); - store.set('two', 'three'); - store.set('1', 'two'); - var returned = store.filter(function (key, value) { - return value === 'two'; - }); - - var store = new Sammy.Store(); - store.load('mytemplate', '/mytemplate.tpl', function () { - store.get('mytemplate') - }); - - store = new Sammy.Store({ name: 'kvo' }); - $('body').bind('set-kvo-foo', function (e, data?) { - Sammy.log(data.key + ' changed to ' + data.value); - }); - store.set('foo', 'bar'); - - $.sammy(function () { - _this.use('Template'); - _this.get('#/', function () { - var evt: Sammy.EventContext = this; - // Adding a dynamic property - (evt).user = { name: 'Aaron Quint' }; - evt.partial('user.template'); - }) - }); - - _this.use(Sammy.Template, 'tpl'); - _this.get('#/', function () { - this.partial('myfile.tpl'); - }); - _this.get('#/', function () { - this.template('myform.tpl', { form: "
        " }, { escape_html: false }); - }); -} - -function test_routes() { - var _this: Sammy.Application; - - _this.route('get', '#/', function () { - }); - _this.put('#/post/form', function () { - return false; - }); - _this.get('/test/123', function () { - }); - - _this.get('#/by_name/:name', function () { - alert(this.params['name']); - }); - _this.get(/\#\/by_name\/(.*)/, function () { - alert(this.params['splat']); - }); - _this.get('#/by_name/:name', function () { - this.redirect('#', this.params['name']); - }); - - _this.get('#/by_name/:name', function (context) { - context.redirect('#', this.params['name']); - }); -} - -function test_events() { - var _this: Sammy.Application; - - _this.bind('db-loaded', function (e, data) { - var _this: Sammy.EventContext; - _this.redirect('#/'); - }); - - var app1 = $.sammy(function () { - var _this: Sammy.Application; - _this.bind('test', function () { - var _this: Sammy.EventContext; - _this.trigger('other-event'); - }); - }); - app1.trigger('other-event'); - - var app2 = $.sammy(function () { - var _this: Sammy.Application; - _this.bind('test', function (e, data) { - alert(data['my_data']); - }); - _this.get('#/', function () { - _this.trigger('test', { my_data: 'EVENTED!' }); - }); - }); -} - -function test_plugins() { - var MyPlugin = function (app) { - var _this: Sammy.Application; - _this.helpers({ - alert: function (message) { - _this.log("ALERT! " + message); - } - }); - }; - var app1 = $.sammy(function () { - var _this: Sammy.Application; - _this.use(MyPlugin); - _this.get('#/', function () { - var _this: Sammy.EventContext; - alert("I'm home"); - }); - }); - var MyAdvancedPlugin = function (app, prefix, suffix) { - var _this: Sammy.Application; - _this.helpers({ - alert: function (message) { - _this.log(prefix, message, suffix); - } - }); - }; - - var app = $.sammy(function () { - var _this: Sammy.Application; - _this.use(MyAdvancedPlugin, 'BEFORE!', 'AFTER!'); - _this.get('#/', function () { - alert("I'm home"); - }); - }); - - var dbLoadAndDisplay = function (app) { - var _this: Sammy.Application; - _this.get('#/', function () { - this.record = this.app.db[this.app.element_selector]; - this.app.swap(this.record.toHTML()); - }); - _this.bind('run', function () { - }); - }; - - var app1 = Sammy('#div_1', function () { - this.use(dbLoadAndDisplay); - }); - - var app2 = Sammy('#div_2', function () { - this.use(dbLoadAndDisplay); - }); +/// + +function test_general() { + // Example from homepage + var app = Sammy('#main', function () { + var _this: Sammy.Application = this; + _this.use('Mustache'); + _this.get('#/', function () { + var _this: Sammy.RenderContext; + _this.load('posts.json') + .renderEach('post.mustache') + .swap(); + }); + }); + + app.run('#/'); + + var _this: Sammy.Application; + _this.get('#/', function (context) { + var _this: Sammy.RenderContext; + _this.load('data/items.json') + .then(function (items) { + $.each(items, function (i, item) { + context.log(item.title, '-', item.artist); + }); + }); + }); +} + +function test_app() { + var s = new Sammy.Object({ first_name: 'Sammy', last_name: 'Davis Jr.' }); + s.toHTML(); + + var app = $.sammy(function () { + + var current_user = false; + function checkLoggedIn(callback) { + var _this: Sammy.EventContext; + if (!current_user) { + $.getJSON('/session', function (json) { + if (json.login) { + current_user = json; + callback(); + } else { + current_user = false; + _this.redirect('#/login'); + } + }); + } else { + callback(); + } + }; + var _this: Sammy.Application; + _this.around(checkLoggedIn); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.before('#/route', function () { }); + _this.before({ except: { path: '#/route' } }, function () { + _this.log('not before #/route'); + }); + _this.get('#/', function () { }); + _this.get('#/route', function () { }); + }); + + var app = $.sammy(), + context = { verb: 'get', path: '#/mypath' }; + + app.contextMatchesOptions(context, '#/mypath'); + app.contextMatchesOptions(context, '#/otherpath'); + app.contextMatchesOptions(context, { only: { path: '#/mypath' } }); + app.contextMatchesOptions(context, { only: { path: '#/otherpath' } }); + app.contextMatchesOptions(context, /path/); + app.contextMatchesOptions(context, /^path/); + app.contextMatchesOptions(context, { only: { verb: 'get' } }); + app.contextMatchesOptions(context, { only: { verb: 'post' } }); + app.contextMatchesOptions(context, { except: { verb: 'post' } }); + app.contextMatchesOptions(context, { except: { verb: 'get' } }); + app.contextMatchesOptions(context, { except: { path: '#/otherpath' } }); + app.contextMatchesOptions(context, { except: { path: '#/mypath' } }); + app.contextMatchesOptions(context, { path: ['#/mypath', '#/otherpath'] }); + app.contextMatchesOptions(context, { path: ['#/otherpath', '#/thirdpath'] }); + app.contextMatchesOptions(context, { only: { path: ['#/mypath', '#/otherpath'] } }); + app.contextMatchesOptions(context, { only: { path: ['#/otherpath', '#/thirdpath'] } }); + app.contextMatchesOptions(context, { except: { path: ['#/mypath', '#/otherpath'] } }); + app.contextMatchesOptions(context, { except: { path: ['#/otherpath', '#/thirdpath'] } }); + + var app = $.sammy(function (app) { + var _this: Sammy.Application; + $.each([1, 2, 3], function (i, num) { + app.helper('helper' + num, function () { + _this.log("I'm helper number " + num); + }); + }); + _this.get('#/', function () { + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + var better = _this.helpers({ + upcase: function (text) { + return text.toString().toUpperCase(); + } + }); + better.get('#/', function () { + $('#main').html(better.upcase($('#main').text())); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.mapRoutes([ + ['get', '#/', function () { }], + ['post', '#/create', 'addUser'], + [/dowhatever/, function () { }] + ]); + }); + + var app = $.sammy(function () { }); + $(function () { + app.run(); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.setLocationProxy(new Sammy.DataLocationProxy(_this)); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.swap = function (content, callback) { + var context = _this; + context.$element().fadeOut('slow', function () { + context.$element().html(content); + context.$element().fadeIn('slow', function () { + if (callback) { + callback.apply(this); + } + }); + }); + }; + }); + + var MyPlugin = function (app, prepend) { + var _this: Sammy.Application; + _this.helpers({ + myhelper: function (text) { + alert(prepend + " " + text); + } + }); + }; + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(MyPlugin, '_this is my plugin'); + _this.get('#/', function () { + }); + }); + + $.sammy(function () { + var _this: Sammy.Application; + _this.use('Mustache'); + _this.use('Storage'); + }); +} + +function test_misc() { + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.setLocationProxy(new Sammy.DataLocationProxy(_this, 'location', 'rel')); + _this.get('about', function () { + var _this: Sammy.EventContext; + _this.partial('about.html'); + }); + }); + + $.sammy(function () { + var _this: Sammy.Application; + _this.get('#/:name', function () { + var _evt: Sammy.EventContext = this; + if (_evt.params['name'] == 'sammy') { + _evt.partial('name.html.erb', { name: 'Sammy' }); + } else { + _evt.redirect('#/somewhere-else') + } + }); + }); + + function evtContextTests() { + var _this: Sammy.EventContext; + _this.redirect('#/other/route'); + _this.redirect('#', 'other', 'route'); + _this.render('mytemplate.mustache', { name: 'quirkey' }) + .appendTo('ul'); + _this.renderEach('mytemplate.mustache', [{ name: 'quirkey' }, { name: 'endor' }]); + + var item = { + name: 'My Item', + price: '$25.50', + meta: { + id: '123' + } + }; + var form = new Sammy.FormBuilder('item', item); + form.text('name'); + + var options = [ + ['Small', 's'], + ['Medium', 'm'], + ['Large', 'l'] + ]; + form.select('size', options); + + $.sammy(function () { + var _this: Sammy.Application; + _this.use('GoogleAnalytics') + _this.get('#/dont/track/me', function () { + var evt: Sammy.GoogleAnalytics = this; + evt.noTrack(); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(Sammy.Haml); + _this.get('#/hello/:name', function () { + var evt: Sammy.Haml = this; + evt.title = 'Hello!'; + evt.name = evt.params.name; + evt.partial('mytemplate.haml'); + }); + }); + app.run() + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Handlebars', 'hb'); + _this.get('#/hello/:name', function () { + var evt: Sammy.Handlebars = this; + evt.title = 'Hello!' + evt.name = evt.params.name; + evt.partial('mytemplate.hb'); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Handlebars', 'hb'); + _this.get('#/hello/:name/to/:friend', function (context: Sammy.Handlebars) { + context.load('mypartial.hb') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + // dynamically add a property to the context + (context).friend = context.params.friend; + context.partial('mytemplate.hb'); + }); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Hogan', 'hg'); + _this.get('#/hello/:name', function () { + var evt: Sammy.Hogan = this; + evt.title = 'Hello!' + evt.name = evt.params.name; + evt.partial('mytemplate.hg'); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Hogan', 'hg'); + _this.get('#/hello/:name/to/:friend', function (context) { + context.load('mypartial.hg') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + context.friend = context.params.friend; + context.partial('mytemplate.hg'); + }); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(Sammy.JSON); + _this.get('#/', function () { + var evt: Sammy.JSON = this; + evt.json({ user_id: 123 }); + evt.json("{\"user_id\":\"123\"}"); + evt.json("{\"user_id\":\"123\"}").user_id; + }); + }) + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Mustache', 'ms'); + _this.get('#/hello/:name', function () { + var evt: Sammy.Mustache = this; + evt.title = 'Hello!' + evt.name = evt.params.name; + evt.partial('mytemplate.ms'); + }); + }); + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use('Mustache', 'ms'); + _this.get('#/hello/:name/to/:friend', function (context: Sammy.Mustache) { + context.load('mypartial.ms') + .then(function (partial) { + context.partials = { hello_friend: partial }; + context.name = context.params.name; + (context).friend = context.params.friend; + context.partial('mytemplate.ms'); + }); + }); + }); + + var app = $.sammy(function (app) { + var _this: Sammy.Application; + _this.use(Sammy.NestedParams); + _this.post('#/parse_me', function (context) { + $.log(context.params); + }); + }); + }; + + var _this: Sammy.Application; + _this.use('Storage'); + _this.use('OAuth2'); + _this.oauthorize = "/oauth/authorize"; + _this.requireOAuth(); + _this.requireOAuth("/private"); + _this.before(function (context) { return context.requireOAuth(); }) + _this.get("/private", function (context) { + _this.requireOAuth(function () { }); + }); + _this.bind("oauth.connected", function () { $("#signin").hide() }); + _this.bind("oauth.disconnected", function () { $("#signin").show() }); + _this.bind("oauth.denied", function (evt, error) { + evt.partial("admin/views/no_access.tmpl", { error: error.message }); + }); + _this.get("#/signout", function (context) { + context.loseAccessToken(); + context.redirect("#/"); + }); + + _this.get('#/', function () { + this.render('mytemplate.template', { name: 'test' }); + }); + + _this.send($.getJSON, '/app.json') + .then(function (json) { + $('#message').text(json['message']); + } + ); + + _this.get('#/', function () { + var evt: Sammy.EventContext = this; + evt.load('myfile.txt') + .then(function (content) { + $('#main').html(content); + }); + }); + + _this.get('#/', function () { + var evt: Sammy.EventContext = this; + evt.load('mytext.json') + .then(function (content) { + var context = this, + data = JSON.parse(content); + context.wait(); + $.post(data.url, {}, function (response) { + context.next(JSON.parse(response)); + }); + }) + .then(function (data) { + $('#message').text(data.status); + }); + }); + + var store = new Sammy.Store({ name: 'mystore', element: '#element', type: 'local' }); + store.set('foo', 'bar'); + store.get('foo'); + store.set('json', { obj: '_this is an obj' }); + store.get('json'); + store.keys(); + store.clear('foo'); + store.keys(); + store.clearAll(); + store.keys(); + + store.each(function (key, value) { + Sammy.log('key', key, 'value', value); + }); + + store = new Sammy.Store(); + store.exists('foo'); + store.fetch('foo', function () { + return 'bar!'; + }); + store.get('foo'); + store.fetch('foo', function () { + return 'baz!'; + }); + + store = new Sammy.Store(); + store.set('one', 'two'); + store.set('two', 'three'); + store.set('1', 'two'); + var returned = store.filter(function (key, value) { + return value === 'two'; + }); + + var store = new Sammy.Store(); + store.load('mytemplate', '/mytemplate.tpl', function () { + store.get('mytemplate') + }); + + store = new Sammy.Store({ name: 'kvo' }); + $('body').bind('set-kvo-foo', function (e, data?) { + Sammy.log(data.key + ' changed to ' + data.value); + }); + store.set('foo', 'bar'); + + $.sammy(function () { + _this.use('Template'); + _this.get('#/', function () { + var evt: Sammy.EventContext = this; + // Adding a dynamic property + (evt).user = { name: 'Aaron Quint' }; + evt.partial('user.template'); + }) + }); + + _this.use(Sammy.Template, 'tpl'); + _this.get('#/', function () { + this.partial('myfile.tpl'); + }); + _this.get('#/', function () { + this.template('myform.tpl', { form: "
        " }, { escape_html: false }); + }); +} + +function test_routes() { + var _this: Sammy.Application; + + _this.route('get', '#/', function () { + }); + _this.put('#/post/form', function () { + return false; + }); + _this.get('/test/123', function () { + }); + + _this.get('#/by_name/:name', function () { + alert(this.params['name']); + }); + _this.get(/\#\/by_name\/(.*)/, function () { + alert(this.params['splat']); + }); + _this.get('#/by_name/:name', function () { + this.redirect('#', this.params['name']); + }); + + _this.get('#/by_name/:name', function (context) { + context.redirect('#', this.params['name']); + }); +} + +function test_events() { + var _this: Sammy.Application; + + _this.bind('db-loaded', function (e, data) { + var _this: Sammy.EventContext; + _this.redirect('#/'); + }); + + var app1 = $.sammy(function () { + var _this: Sammy.Application; + _this.bind('test', function () { + var _this: Sammy.EventContext; + _this.trigger('other-event'); + }); + }); + app1.trigger('other-event'); + + var app2 = $.sammy(function () { + var _this: Sammy.Application; + _this.bind('test', function (e, data) { + alert(data['my_data']); + }); + _this.get('#/', function () { + _this.trigger('test', { my_data: 'EVENTED!' }); + }); + }); +} + +function test_plugins() { + var MyPlugin = function (app) { + var _this: Sammy.Application; + _this.helpers({ + alert: function (message) { + _this.log("ALERT! " + message); + } + }); + }; + var app1 = $.sammy(function () { + var _this: Sammy.Application; + _this.use(MyPlugin); + _this.get('#/', function () { + var _this: Sammy.EventContext; + alert("I'm home"); + }); + }); + var MyAdvancedPlugin = function (app, prefix, suffix) { + var _this: Sammy.Application; + _this.helpers({ + alert: function (message) { + _this.log(prefix, message, suffix); + } + }); + }; + + var app = $.sammy(function () { + var _this: Sammy.Application; + _this.use(MyAdvancedPlugin, 'BEFORE!', 'AFTER!'); + _this.get('#/', function () { + alert("I'm home"); + }); + }); + + var dbLoadAndDisplay = function (app) { + var _this: Sammy.Application; + _this.get('#/', function () { + this.record = this.app.db[this.app.element_selector]; + this.app.swap(this.record.toHTML()); + }); + _this.bind('run', function () { + }); + }; + + var app1 = Sammy('#div_1', function () { + this.use(dbLoadAndDisplay); + }); + + var app2 = Sammy('#div_2', function () { + this.use(dbLoadAndDisplay); + }); } \ No newline at end of file diff --git a/sammyjs/sammyjs-tests.ts.tscparams b/sammyjs/sammyjs-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sammyjs/sammyjs-tests.ts.tscparams +++ b/sammyjs/sammyjs-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/sammyjs/sammyjs.d.ts b/sammyjs/sammyjs.d.ts index 5d980a09f..185193bab 100644 --- a/sammyjs/sammyjs.d.ts +++ b/sammyjs/sammyjs.d.ts @@ -1,286 +1,286 @@ -// Type definitions for Sammy.js -// Project: http://sammyjs.org/ -// Definitions by: Boris Yankov , Oisin Grehan -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare function Sammy(): Sammy.Application; -declare function Sammy(selector: string): Sammy.Application; -declare function Sammy(handler: Function): Sammy.Application; -declare function Sammy(selector: string, handler: Function): Sammy.Application; - -declare module Sammy { - interface SammyFunc { - (): Sammy.Application; - (selector: string): Sammy.Application; - (handler: Function): Sammy.Application; - (selector: string, handler: Function): Sammy.Application; - } - - export function Cache(app, options); - export function DataCacheProxy(initial, $element); - export var DataLocationProxy:DataLocationProxy; - export function DefaultLocationProxy(app, run_interval_every); - export function EJS(app, method_alias); - - export function Exceptional(app, errorReporter); - export function Flash(app); - export var FormBuilder: FormBuilder; - export function Form(app); // formFor ( name, object, content_callback ) - - export function Haml(app, method_alias); - export function Handlebars(app, method_alias); - export function Hogan(app, method_alias); - export function Hoptoad(app, errorReporter); - export function JSON(app); - export function Meld(app, method_alias); - export function MemoryCacheProxy(initial); - export function Mustache(app, method_alias); - export function NestedParams(app); - export function OAuth2(app); - export function PathLocationProxy(app); - export function Pure(app, method_alias); - export function PushLocationProxy(app); - export function Session(app, options); - export function Storage(app); - export var Store: Store; - - export function Title(); - export function Template(app, method_alias); - export function Tmpl(app, method_alias); - export function addLogger(logger); - export function log(...args:any[]); - - export class Object { - - constructor(obj: any); - - escapeHTML(s: string): string; - h(s: string): string; - - has(key: string): boolean; - join(...args: any[]): string; - keys(attributes_only?: boolean): string[]; - log(...args: any[]): void; - toHTML(): string; - toHash(): any; - toString(include_functions?: boolean): string; - } - - export interface Application extends Object { - - ROUTE_VERBS: string[]; - APP_EVENTS: string[]; - - (appFn: Function); - - $element(selector?: string): JQuery; - after(callback: Function): Application; - any(verb: string, path: string, callback: Function): void; - around(callback: Function): Application; - before(callback: Function): Application; - before(options: any, callback: Function): Application; - bind(name: string, callback: Function): Application; - bind(name: string, data: any, callback: Function): Application; - bindToAllEvents(callback: Function): Application; - clearTemplateCache(): any; - contextMatchesOptions(context: any, match_options: any, positive?: boolean): boolean; - del(path: string, callback: Function): Application; - del(path: RegExp, callback: Function): Application; - destroy(): Application; - error(message: string, original_error: Error): void; - eventNamespace(): string; - get(path: string, callback: Function): Application; - get(path: RegExp, callback: Function): Application; - getLocation(): string; - helper(name: string, method: Function): any; // Behaviour similar to _.extend - helpers(extensions: any): any; // Behaviour similar to _.extend - isRunning(): boolean; - log(...params: any[]): void; - lookupRoute(verb: string, path: string): any; - mapRoutes(route_array: any[]): Application; - notFound(verb: string, path: string): any; - post(path: string, callback: Function): Application; - post(path: RegExp, callback: Function): Application; - put(path: string, callback: Function): Application; - put(path: RegExp, callback: Function): Application; - refresh(): Application; - routablePath(path: string): string; - route(verb: string, path: string, callback: Function): Application; - route(verb: string, path: RegExp, callback: Function): Application; - run(start_url?: string): Application; - runRoute(verb: string, path?: string, params?: any, target?: any): any; - send(...params: any[]); - setLocation(new_location: string): string; - setLocationProxy(new_proxy: DataLocationProxy): void; - swap(content: any, callback: Function): any; - templateCache(key: string, value: any): any; - toString(): string; - trigger(name: string, data?: any): Application; - unload(): Application; - use(...params: any[]): void; - last_location: string[]; - - // Features provided by oauth2 plugin - oauthorize: string; - requireOAuth(); - requireOAuth(path?:string); - requireOAuth(callback?: Function); - } - - export interface DataLocationProxy { - - new (app, run_interval_every?): DataLocationProxy; - new (app, data_name, href_attribute): DataLocationProxy; - - fullPath(location_obj): string; - bind(): void; - unbind(): void; - setLocation(new_location: string): string; - _startPolling(every: number): void; - } - - export interface EventContext extends Object { - - new (app, verb, path, params, target); - - $element(): JQuery; - engineFor(engine: any): any; - eventNamespace(): string; - interpolate(content: any, data: any, engine: any, partials): EventContext; - json(str: any): any; - json(str: string): any; - load(location: any, options?: any, callback?: Function): any; - loadPartials(partials); - notFound(): any; - partial(location: string, data?: any, callback?: Function, partials?): RenderContext; - partials: any; - params: any; - redirect(...params: any[]): void; - render(location: string, data?: any, callback?: Function, partials?): RenderContext; - renderEach(location: any, data?: { name: string;data?:any}[],callback?: Function): RenderContext; - send(...params: any[]): RenderContext; - swap(contents: any, callback: Function): string; - toString(): string; - trigger(name: string, data?: any): EventContext; - - // Provided by common sammy modules: - name: any; - title: any; - } - - export interface FormBuilder { - - new (name, object); - - checkbox(keypath: string, value: any, ...attributes: any[]): string; - close(): string; - hidden(keypath: string, ...attributes: any[]): string; - label(keypath: string, content: any, ...attributes: any[]): string; - open(...attributes: any[]); - password(keypath: string, ...attributes: any[]): string; - radio(keypath: string, value: any, ...attributes: any[]): string; - select(keypath: string, options: any, ...attributes: any[]): string; - submit(...attributes: any[]): string; - text(keypath: string, ...attributes: any[]): string; - textarea(keypath: string, ...attributes: any[]): string; - } - - export interface Form { - formFor(name: string, object: any, content_callback: Function): FormBuilder; - } - - export interface GoogleAnalytics { - - new (app, tracker); - - noTrack(); - track(path); - } - - export interface Haml extends EventContext { } - - export interface Handlebars extends EventContext { } - - export interface Hogan extends EventContext { } - - export interface JSON extends EventContext { } - - export interface Mustache extends EventContext { } - - export interface RenderContext extends Object { - - new (event_context); - - appendTo(selector: string): RenderContext; - collect(array: any[], callback: Function, now?: boolean): RenderContext; - interpolate(data: any, engine?: any, retain?: boolean): RenderContext; - load(location: string, options?: any, callback?: Function): RenderContext; - loadPartials(partials?: any): RenderContext; - next(content: any): void; - partial(location: string, callback: Function, partials): RenderContext; - partial(location: string, data: any, callback: Function, partials): RenderContext; - prependTo(selector: string): RenderContext; - render(callback: Function): RenderContext; - render(location: string, data: any): RenderContext; - render(location: string, callback: Function, partials?: any): RenderContext; - render(location: string, data: any, callback: Function): RenderContext; - render(location: string, data: any, callback: Function, partials: any): RenderContext; - renderEach(location: string, name?: string, data?: any, callback?: Function): RenderContext; - replace(selector: string): RenderContext; - send(...params: any[]): RenderContext; - swap(callback?: Function): RenderContext; - then(callback: Function): RenderContext; - trigger(name, data); - wait(): void; - } - - export interface StoreOptions { - name?: string; - element?: string; - type?: string; - memory?: any; - data?: any; - cookie?: any; - local?: any; - session?: any; - } - - export interface Store { - - stores: any; - - new (options?:any); - - clear(key: string): any; - clearAll(): void; - each(callback: Function): boolean; - exists(key: string): boolean; - fetch(key: string, callback: Function): any; - filter(callback: Function): boolean; - first(callback: Function): boolean; - get(key: string): any; - isAvailable(): boolean; - keys(): string[]; - load(key: string, path: string, callback: Function): void; - set(key: string, value: any): any; - - Cookie(name, element, options); - Data(name, element); - LocalStorage(name, element); - Memory(name, element); - SessionStorage(name, element); - isAvailable(type); - Template(app, method_alias); - } -} - -declare module "sammy" { - export = Sammy; -} - -interface JQueryStatic { - sammy: Sammy.SammyFunc; - log: Function; -} +// Type definitions for Sammy.js +// Project: http://sammyjs.org/ +// Definitions by: Boris Yankov , Oisin Grehan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare function Sammy(): Sammy.Application; +declare function Sammy(selector: string): Sammy.Application; +declare function Sammy(handler: Function): Sammy.Application; +declare function Sammy(selector: string, handler: Function): Sammy.Application; + +declare module Sammy { + interface SammyFunc { + (): Sammy.Application; + (selector: string): Sammy.Application; + (handler: Function): Sammy.Application; + (selector: string, handler: Function): Sammy.Application; + } + + export function Cache(app, options); + export function DataCacheProxy(initial, $element); + export var DataLocationProxy:DataLocationProxy; + export function DefaultLocationProxy(app, run_interval_every); + export function EJS(app, method_alias); + + export function Exceptional(app, errorReporter); + export function Flash(app); + export var FormBuilder: FormBuilder; + export function Form(app); // formFor ( name, object, content_callback ) + + export function Haml(app, method_alias); + export function Handlebars(app, method_alias); + export function Hogan(app, method_alias); + export function Hoptoad(app, errorReporter); + export function JSON(app); + export function Meld(app, method_alias); + export function MemoryCacheProxy(initial); + export function Mustache(app, method_alias); + export function NestedParams(app); + export function OAuth2(app); + export function PathLocationProxy(app); + export function Pure(app, method_alias); + export function PushLocationProxy(app); + export function Session(app, options); + export function Storage(app); + export var Store: Store; + + export function Title(); + export function Template(app, method_alias); + export function Tmpl(app, method_alias); + export function addLogger(logger); + export function log(...args:any[]); + + export class Object { + + constructor(obj: any); + + escapeHTML(s: string): string; + h(s: string): string; + + has(key: string): boolean; + join(...args: any[]): string; + keys(attributes_only?: boolean): string[]; + log(...args: any[]): void; + toHTML(): string; + toHash(): any; + toString(include_functions?: boolean): string; + } + + export interface Application extends Object { + + ROUTE_VERBS: string[]; + APP_EVENTS: string[]; + + (appFn: Function); + + $element(selector?: string): JQuery; + after(callback: Function): Application; + any(verb: string, path: string, callback: Function): void; + around(callback: Function): Application; + before(callback: Function): Application; + before(options: any, callback: Function): Application; + bind(name: string, callback: Function): Application; + bind(name: string, data: any, callback: Function): Application; + bindToAllEvents(callback: Function): Application; + clearTemplateCache(): any; + contextMatchesOptions(context: any, match_options: any, positive?: boolean): boolean; + del(path: string, callback: Function): Application; + del(path: RegExp, callback: Function): Application; + destroy(): Application; + error(message: string, original_error: Error): void; + eventNamespace(): string; + get(path: string, callback: Function): Application; + get(path: RegExp, callback: Function): Application; + getLocation(): string; + helper(name: string, method: Function): any; // Behaviour similar to _.extend + helpers(extensions: any): any; // Behaviour similar to _.extend + isRunning(): boolean; + log(...params: any[]): void; + lookupRoute(verb: string, path: string): any; + mapRoutes(route_array: any[]): Application; + notFound(verb: string, path: string): any; + post(path: string, callback: Function): Application; + post(path: RegExp, callback: Function): Application; + put(path: string, callback: Function): Application; + put(path: RegExp, callback: Function): Application; + refresh(): Application; + routablePath(path: string): string; + route(verb: string, path: string, callback: Function): Application; + route(verb: string, path: RegExp, callback: Function): Application; + run(start_url?: string): Application; + runRoute(verb: string, path?: string, params?: any, target?: any): any; + send(...params: any[]); + setLocation(new_location: string): string; + setLocationProxy(new_proxy: DataLocationProxy): void; + swap(content: any, callback: Function): any; + templateCache(key: string, value: any): any; + toString(): string; + trigger(name: string, data?: any): Application; + unload(): Application; + use(...params: any[]): void; + last_location: string[]; + + // Features provided by oauth2 plugin + oauthorize: string; + requireOAuth(); + requireOAuth(path?:string); + requireOAuth(callback?: Function); + } + + export interface DataLocationProxy { + + new (app, run_interval_every?): DataLocationProxy; + new (app, data_name, href_attribute): DataLocationProxy; + + fullPath(location_obj): string; + bind(): void; + unbind(): void; + setLocation(new_location: string): string; + _startPolling(every: number): void; + } + + export interface EventContext extends Object { + + new (app, verb, path, params, target); + + $element(): JQuery; + engineFor(engine: any): any; + eventNamespace(): string; + interpolate(content: any, data: any, engine: any, partials): EventContext; + json(str: any): any; + json(str: string): any; + load(location: any, options?: any, callback?: Function): any; + loadPartials(partials); + notFound(): any; + partial(location: string, data?: any, callback?: Function, partials?): RenderContext; + partials: any; + params: any; + redirect(...params: any[]): void; + render(location: string, data?: any, callback?: Function, partials?): RenderContext; + renderEach(location: any, data?: { name: string;data?:any}[],callback?: Function): RenderContext; + send(...params: any[]): RenderContext; + swap(contents: any, callback: Function): string; + toString(): string; + trigger(name: string, data?: any): EventContext; + + // Provided by common sammy modules: + name: any; + title: any; + } + + export interface FormBuilder { + + new (name, object); + + checkbox(keypath: string, value: any, ...attributes: any[]): string; + close(): string; + hidden(keypath: string, ...attributes: any[]): string; + label(keypath: string, content: any, ...attributes: any[]): string; + open(...attributes: any[]); + password(keypath: string, ...attributes: any[]): string; + radio(keypath: string, value: any, ...attributes: any[]): string; + select(keypath: string, options: any, ...attributes: any[]): string; + submit(...attributes: any[]): string; + text(keypath: string, ...attributes: any[]): string; + textarea(keypath: string, ...attributes: any[]): string; + } + + export interface Form { + formFor(name: string, object: any, content_callback: Function): FormBuilder; + } + + export interface GoogleAnalytics { + + new (app, tracker); + + noTrack(); + track(path); + } + + export interface Haml extends EventContext { } + + export interface Handlebars extends EventContext { } + + export interface Hogan extends EventContext { } + + export interface JSON extends EventContext { } + + export interface Mustache extends EventContext { } + + export interface RenderContext extends Object { + + new (event_context); + + appendTo(selector: string): RenderContext; + collect(array: any[], callback: Function, now?: boolean): RenderContext; + interpolate(data: any, engine?: any, retain?: boolean): RenderContext; + load(location: string, options?: any, callback?: Function): RenderContext; + loadPartials(partials?: any): RenderContext; + next(content: any): void; + partial(location: string, callback: Function, partials): RenderContext; + partial(location: string, data: any, callback: Function, partials): RenderContext; + prependTo(selector: string): RenderContext; + render(callback: Function): RenderContext; + render(location: string, data: any): RenderContext; + render(location: string, callback: Function, partials?: any): RenderContext; + render(location: string, data: any, callback: Function): RenderContext; + render(location: string, data: any, callback: Function, partials: any): RenderContext; + renderEach(location: string, name?: string, data?: any, callback?: Function): RenderContext; + replace(selector: string): RenderContext; + send(...params: any[]): RenderContext; + swap(callback?: Function): RenderContext; + then(callback: Function): RenderContext; + trigger(name, data); + wait(): void; + } + + export interface StoreOptions { + name?: string; + element?: string; + type?: string; + memory?: any; + data?: any; + cookie?: any; + local?: any; + session?: any; + } + + export interface Store { + + stores: any; + + new (options?:any); + + clear(key: string): any; + clearAll(): void; + each(callback: Function): boolean; + exists(key: string): boolean; + fetch(key: string, callback: Function): any; + filter(callback: Function): boolean; + first(callback: Function): boolean; + get(key: string): any; + isAvailable(): boolean; + keys(): string[]; + load(key: string, path: string, callback: Function): void; + set(key: string, value: any): any; + + Cookie(name, element, options); + Data(name, element); + LocalStorage(name, element); + Memory(name, element); + SessionStorage(name, element); + isAvailable(type); + Template(app, method_alias); + } +} + +declare module "sammy" { + export = Sammy; +} + +interface JQueryStatic { + sammy: Sammy.SammyFunc; + log: Function; +} diff --git a/sammyjs/sammyjs.d.ts.tscparams b/sammyjs/sammyjs.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sammyjs/sammyjs.d.ts.tscparams +++ b/sammyjs/sammyjs.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/scroller/easyscroller.d.ts b/scroller/easyscroller.d.ts index fc0418a57..28359932f 100644 --- a/scroller/easyscroller.d.ts +++ b/scroller/easyscroller.d.ts @@ -1,15 +1,15 @@ -// Type definitions for Zynga EasyScroller -// Project: https://github.com/zynga/scroller -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -declare class EasyScroller { - constructor (content: any, options: ScrollerOptions); - - render(): void; - reflow(): void; - bindEvents(): void; -} +// Type definitions for Zynga EasyScroller +// Project: https://github.com/zynga/scroller +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare class EasyScroller { + constructor (content: any, options: ScrollerOptions); + + render(): void; + reflow(): void; + bindEvents(): void; +} diff --git a/scroller/scroller-tests.ts b/scroller/scroller-tests.ts index 411ddab92..6a5a29be9 100644 --- a/scroller/scroller-tests.ts +++ b/scroller/scroller-tests.ts @@ -1,260 +1,260 @@ -/// - -var clientWidth: any; -var clientHeight: any; -var render: any; - -var Tiling: any; - -function test_basic() { - var scrollerObj = new Scroller(function (left, top, zoom) { - }, { - scrollingY: false - }); - scrollerObj.setDimensions(1000, 1000, 3000, 3000); -} - -function test_canvas() { - var contentWidth = 2000; - var contentHeight = 2000; - var cellWidth = 100; - var cellHeight = 100; - var content = document.getElementById('content'); - var context = content.getContext('2d'); - var tiling = new Tiling(); - var render = function (left, top, zoom) { - content.width = clientWidth; - content.height = clientHeight; - context.clearRect(0, 0, clientWidth, clientHeight); - tiling.setup(clientWidth, clientHeight, contentWidth, contentHeight, cellWidth, cellHeight); - tiling.render(left, top, zoom, paint); - }; - var paint = function (row, col, left, top, width, height, zoom) { - context.fillStyle = row % 2 + col % 2 > 0 ? "#ddd" : "#fff"; - context.fillRect(left, top, width, height); - context.fillStyle = "black"; - context.font = (14 * zoom).toFixed(2) + 'px "Helvetica Neue", Helvetica, Arial, sans-serif'; - context.fillText(row + "," + col, left + (6 * zoom), top + (18 * zoom)); - }; -} - -function test_domlist() { - var container = document.getElementById("container"); - var content = document.getElementById("content"); - var refreshElem = content.getElementsByTagName("div")[0]; - var scroller = new Scroller(render, { - scrollingX: false - }); - scroller.activatePullToRefresh(50, function () { - refreshElem.className += " active"; - refreshElem.innerHTML = "Release to Refresh"; - }, function () { - refreshElem.className = refreshElem.className.replace(" active", ""); - refreshElem.innerHTML = "Pull to Refresh"; - }, function () { - refreshElem.className += " running"; - refreshElem.innerHTML = "Refreshing..."; - setTimeout(function () { - refreshElem.className = refreshElem.className.replace(" running", ""); - insertItems(); - scroller.finishPullToRefresh(); - }, 2000); - }); - var rect = container.getBoundingClientRect(); - scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); - var insertItems = function () { - for (var i = 0; i < 15; i++) { - var row = document.createElement("div"); - row.className = "row"; - row.style.backgroundColor = i % 2 > 0 ? "#ddd" : ""; - row.innerHTML = Math.random(); - if (content.firstChild == content.lastChild) { - content.appendChild(row); - } else { - content.insertBefore(row, content.childNodes[1]) - } - } - scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight - 50); - }; - insertItems(); - if ('ontouchstart' in window) { - container.addEventListener("touchstart", function (e) { - // Don't react if initial down happens on a form element - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart((e).touches, e.timeStamp); - e.preventDefault(); - }, false); - document.addEventListener("touchmove", function (e) { - scroller.doTouchMove((e).touches, e.timeStamp); - }, false); - document.addEventListener("touchend", function (e) { - scroller.doTouchEnd(e.timeStamp); - }, false); - } else { - var mousedown = false; - container.addEventListener("mousedown", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mousemove", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchMove([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mouseup", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchEnd(e.timeStamp); - mousedown = false; - }, false); - } -} - -function test_dompaging() { - var container = document.getElementById("container"); - var content = document.getElementById("content"); - var size = 400; - var frag = document.createDocumentFragment(); - for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { - var elem = document.createElement("div"); - elem.className = "cell"; - elem.style.backgroundColor = cell % 2 > 0 ? "#ddd" : ""; - elem.innerHTML = cell; - frag.appendChild(elem); - } - content.appendChild(frag); - var scroller = new Scroller(render, { - scrollingY: false, - paging: true - }); - var rect = container.getBoundingClientRect(); - scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); - scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); - if ('ontouchstart' in window) { - container.addEventListener("touchstart", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart((e).touches, e.timeStamp); - e.preventDefault(); - }, false); - document.addEventListener("touchmove", function (e) { - scroller.doTouchMove((e).touches, e.timeStamp); - }, false); - document.addEventListener("touchend", function (e) { - scroller.doTouchEnd(e.timeStamp); - }, false); - } else { - var mousedown = false; - container.addEventListener("mousedown", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mousemove", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchMove([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - - document.addEventListener("mouseup", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchEnd(e.timeStamp); - mousedown = false; - }, false); - } -} - -function test_domsnapping() { - var container = document.getElementById("container"); - var content = document.getElementById("content"); - var size = 100; - var frag = document.createDocumentFragment(); - for (var row = 0, rl = content.clientHeight / size; row < rl; row++) { - for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { - var elem = document.createElement("div"); - elem.className = "cell"; - elem.style.backgroundColor = row % 2 + cell % 2 > 0 ? "#ddd" : ""; - elem.innerHTML = row + "," + cell; - frag.appendChild(elem); - } - } - content.appendChild(frag); - var scroller = new Scroller(render, { - snapping: true - }); - var rect = container.getBoundingClientRect(); - scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); - scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); - scroller.setSnapSize(100, 100); - if ('ontouchstart' in window) { - container.addEventListener("touchstart", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart((e).touches, e.timeStamp); - e.preventDefault(); - }, false); - document.addEventListener("touchmove", function (e) { - scroller.doTouchMove((e).touches, e.timeStamp); - }, false); - document.addEventListener("touchend", function (e) { - scroller.doTouchEnd(e.timeStamp); - }, false); - } else { - var mousedown = false; - container.addEventListener("mousedown", function (e) { - if ((e.target).tagName.match(/input|textarea|select/i)) { - return; - } - scroller.doTouchStart([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mousemove", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchMove([{ - pageX: (e).pageX, - pageY: (e).pageY - }], e.timeStamp); - mousedown = true; - }, false); - document.addEventListener("mouseup", function (e) { - if (!mousedown) { - return; - } - scroller.doTouchEnd(e.timeStamp); - mousedown = false; - }, false); - } +/// + +var clientWidth: any; +var clientHeight: any; +var render: any; + +var Tiling: any; + +function test_basic() { + var scrollerObj = new Scroller(function (left, top, zoom) { + }, { + scrollingY: false + }); + scrollerObj.setDimensions(1000, 1000, 3000, 3000); +} + +function test_canvas() { + var contentWidth = 2000; + var contentHeight = 2000; + var cellWidth = 100; + var cellHeight = 100; + var content = document.getElementById('content'); + var context = content.getContext('2d'); + var tiling = new Tiling(); + var render = function (left, top, zoom) { + content.width = clientWidth; + content.height = clientHeight; + context.clearRect(0, 0, clientWidth, clientHeight); + tiling.setup(clientWidth, clientHeight, contentWidth, contentHeight, cellWidth, cellHeight); + tiling.render(left, top, zoom, paint); + }; + var paint = function (row, col, left, top, width, height, zoom) { + context.fillStyle = row % 2 + col % 2 > 0 ? "#ddd" : "#fff"; + context.fillRect(left, top, width, height); + context.fillStyle = "black"; + context.font = (14 * zoom).toFixed(2) + 'px "Helvetica Neue", Helvetica, Arial, sans-serif'; + context.fillText(row + "," + col, left + (6 * zoom), top + (18 * zoom)); + }; +} + +function test_domlist() { + var container = document.getElementById("container"); + var content = document.getElementById("content"); + var refreshElem = content.getElementsByTagName("div")[0]; + var scroller = new Scroller(render, { + scrollingX: false + }); + scroller.activatePullToRefresh(50, function () { + refreshElem.className += " active"; + refreshElem.innerHTML = "Release to Refresh"; + }, function () { + refreshElem.className = refreshElem.className.replace(" active", ""); + refreshElem.innerHTML = "Pull to Refresh"; + }, function () { + refreshElem.className += " running"; + refreshElem.innerHTML = "Refreshing..."; + setTimeout(function () { + refreshElem.className = refreshElem.className.replace(" running", ""); + insertItems(); + scroller.finishPullToRefresh(); + }, 2000); + }); + var rect = container.getBoundingClientRect(); + scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); + var insertItems = function () { + for (var i = 0; i < 15; i++) { + var row = document.createElement("div"); + row.className = "row"; + row.style.backgroundColor = i % 2 > 0 ? "#ddd" : ""; + row.innerHTML = Math.random(); + if (content.firstChild == content.lastChild) { + content.appendChild(row); + } else { + content.insertBefore(row, content.childNodes[1]) + } + } + scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight - 50); + }; + insertItems(); + if ('ontouchstart' in window) { + container.addEventListener("touchstart", function (e) { + // Don't react if initial down happens on a form element + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart((e).touches, e.timeStamp); + e.preventDefault(); + }, false); + document.addEventListener("touchmove", function (e) { + scroller.doTouchMove((e).touches, e.timeStamp); + }, false); + document.addEventListener("touchend", function (e) { + scroller.doTouchEnd(e.timeStamp); + }, false); + } else { + var mousedown = false; + container.addEventListener("mousedown", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mousemove", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchMove([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mouseup", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchEnd(e.timeStamp); + mousedown = false; + }, false); + } +} + +function test_dompaging() { + var container = document.getElementById("container"); + var content = document.getElementById("content"); + var size = 400; + var frag = document.createDocumentFragment(); + for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { + var elem = document.createElement("div"); + elem.className = "cell"; + elem.style.backgroundColor = cell % 2 > 0 ? "#ddd" : ""; + elem.innerHTML = cell; + frag.appendChild(elem); + } + content.appendChild(frag); + var scroller = new Scroller(render, { + scrollingY: false, + paging: true + }); + var rect = container.getBoundingClientRect(); + scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); + scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); + if ('ontouchstart' in window) { + container.addEventListener("touchstart", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart((e).touches, e.timeStamp); + e.preventDefault(); + }, false); + document.addEventListener("touchmove", function (e) { + scroller.doTouchMove((e).touches, e.timeStamp); + }, false); + document.addEventListener("touchend", function (e) { + scroller.doTouchEnd(e.timeStamp); + }, false); + } else { + var mousedown = false; + container.addEventListener("mousedown", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mousemove", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchMove([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + + document.addEventListener("mouseup", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchEnd(e.timeStamp); + mousedown = false; + }, false); + } +} + +function test_domsnapping() { + var container = document.getElementById("container"); + var content = document.getElementById("content"); + var size = 100; + var frag = document.createDocumentFragment(); + for (var row = 0, rl = content.clientHeight / size; row < rl; row++) { + for (var cell = 0, cl = content.clientWidth / size; cell < cl; cell++) { + var elem = document.createElement("div"); + elem.className = "cell"; + elem.style.backgroundColor = row % 2 + cell % 2 > 0 ? "#ddd" : ""; + elem.innerHTML = row + "," + cell; + frag.appendChild(elem); + } + } + content.appendChild(frag); + var scroller = new Scroller(render, { + snapping: true + }); + var rect = container.getBoundingClientRect(); + scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop); + scroller.setDimensions(container.clientWidth, container.clientHeight, content.offsetWidth, content.offsetHeight); + scroller.setSnapSize(100, 100); + if ('ontouchstart' in window) { + container.addEventListener("touchstart", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart((e).touches, e.timeStamp); + e.preventDefault(); + }, false); + document.addEventListener("touchmove", function (e) { + scroller.doTouchMove((e).touches, e.timeStamp); + }, false); + document.addEventListener("touchend", function (e) { + scroller.doTouchEnd(e.timeStamp); + }, false); + } else { + var mousedown = false; + container.addEventListener("mousedown", function (e) { + if ((e.target).tagName.match(/input|textarea|select/i)) { + return; + } + scroller.doTouchStart([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mousemove", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchMove([{ + pageX: (e).pageX, + pageY: (e).pageY + }], e.timeStamp); + mousedown = true; + }, false); + document.addEventListener("mouseup", function (e) { + if (!mousedown) { + return; + } + scroller.doTouchEnd(e.timeStamp); + mousedown = false; + }, false); + } } \ No newline at end of file diff --git a/scroller/scroller-tests.ts.tscparams b/scroller/scroller-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/scroller/scroller-tests.ts.tscparams +++ b/scroller/scroller-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/scroller/scroller.d.ts b/scroller/scroller.d.ts index b1312ff35..5b1ccba2c 100644 --- a/scroller/scroller.d.ts +++ b/scroller/scroller.d.ts @@ -1,50 +1,50 @@ -// Type definitions for Zynga Scroller -// Project: https://github.com/zynga/scroller -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface ScrollerOptions { - scrollingX?: boolean; - scrollingY?: boolean; - animating?: boolean; - animationDuration?: number; - bouncing?: boolean; - locking?: boolean; - paging?: boolean; - snapping?: boolean; - zooming?: boolean; - minZoom?: number; - maxZoom?: number; - speedMultiplier?: number; -} - -interface ScrollValues { - left: number; - top: number; -} - -interface ScrollValuesWithZoom extends ScrollValues { - zoom: number; -} - -declare class Scroller { - constructor (callback: (left: number, top: number, zoom: number) => void , options: ScrollerOptions); - - setDimensions(clientWidth: number, clientHeight: number, contentWidth: number, contentHeight: number): void; - setPosition(left: number, top: number): void; - setSnapSize(width: number, height: number): void; - activatePullToRefresh(height: number, activateCallback: Function, deactivateCallback: Function, startCallback: Function): void; - finishPullToRefresh(): void; - getValues(): ScrollValuesWithZoom; - getScrollMax(): ScrollValues; - zoomTo(level: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; - zoomBy(factor: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; - scrollTo(left?: number, top?: number, animate?: boolean, zoom?: number): void; - scrollBy(left?: number, top?: number, animate?: boolean): void; - - doMouseZoom(wheelDelta: number, timeStamp: number, pageX: number, pageY: number): void; - doTouchStart(touches: any[], timeStamp: number): void; - doTouchMove(touches: any[], timeStamp: number, scale?: number): void; - doTouchEnd(timeStamp: number): void; -} +// Type definitions for Zynga Scroller +// Project: https://github.com/zynga/scroller +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface ScrollerOptions { + scrollingX?: boolean; + scrollingY?: boolean; + animating?: boolean; + animationDuration?: number; + bouncing?: boolean; + locking?: boolean; + paging?: boolean; + snapping?: boolean; + zooming?: boolean; + minZoom?: number; + maxZoom?: number; + speedMultiplier?: number; +} + +interface ScrollValues { + left: number; + top: number; +} + +interface ScrollValuesWithZoom extends ScrollValues { + zoom: number; +} + +declare class Scroller { + constructor (callback: (left: number, top: number, zoom: number) => void , options: ScrollerOptions); + + setDimensions(clientWidth: number, clientHeight: number, contentWidth: number, contentHeight: number): void; + setPosition(left: number, top: number): void; + setSnapSize(width: number, height: number): void; + activatePullToRefresh(height: number, activateCallback: Function, deactivateCallback: Function, startCallback: Function): void; + finishPullToRefresh(): void; + getValues(): ScrollValuesWithZoom; + getScrollMax(): ScrollValues; + zoomTo(level: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; + zoomBy(factor: number, animate?: boolean, originLeft?: number, originTop?: number, callback?: Function): void; + scrollTo(left?: number, top?: number, animate?: boolean, zoom?: number): void; + scrollBy(left?: number, top?: number, animate?: boolean): void; + + doMouseZoom(wheelDelta: number, timeStamp: number, pageX: number, pageY: number): void; + doTouchStart(touches: any[], timeStamp: number): void; + doTouchMove(touches: any[], timeStamp: number, scale?: number): void; + doTouchEnd(timeStamp: number): void; +} diff --git a/select2/select2-tests.ts b/select2/select2-tests.ts index b63d3cc1e..2ab6e94af 100644 --- a/select2/select2-tests.ts +++ b/select2/select2-tests.ts @@ -1,199 +1,199 @@ -/// -/// - -$("#e9").select2(); -$("#e2").select2({ - placeholder: "Select a State", - allowClear: true -}); -$("#e2_2").select2({ - placeholder: "Select a State" -}); -$("#e3").select2({ - minimumInputLength: 2 -}); -function format(state) { - if (!state.id) return state.text; - return "" + state.text; -} -$("#e4").select2({ - formatResult: format, - formatSelection: format -}); -$("#e5").select2({ - minimumInputLength: 1, - query: function (query) { - var data = { results: [] }, i, j, s; - for (i = 1; i < 5; i++) { - s = ""; - for (j = 0; j < i; j++) { s = s + query.term; } - data.results.push({ id: query.term + i, text: s }); - } - } -}); -$("#e19").select2({ maximumSelectionSize: 3 }); -$("#e10").select2({ - data: [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }] -}); - -var data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; - -$("#e10_2").select2({ - data: { results: data, text: 'tag' }, - formatSelection: format, - formatResult: format -}); - -$("#e10_3").select2({ - data: { results: data, text: function (item) { console.log('called with', item); return item.tag; } }, - formatSelection: format, - formatResult: format -}); -var movieFormatResult, movieFormatSelection; -$("#e6").select2({ - placeholder: "Search for a movie", - minimumInputLength: 1, - ajax: { - url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", - dataType: 'jsonp', - cache: false, - data: function (term, page) { - return { - q: term, - page_limit: 10, - apikey: "ju6z9mjyajq2djue3gbvv26t" - }; - }, - results: function (data, page) { - return { results: data.movies }; - } - }, - formatResult: movieFormatResult, - formatSelection: movieFormatSelection, - dropdownCssClass: "bigdrop" -}); -$("#e6").select2({ - placeholder: "Search for a movie", - minimumInputLength: 1, - ajax: { - url: () => { return "http://api.rottentomatoes.com/api/public/v1.0/movies.json"; }, - dataType: 'jsonp', - data: function (term, page) { - return { - q: term, - page_limit: 10, - apikey: "ju6z9mjyajq2djue3gbvv26t" - }; - }, - results: function (data, page) { - return { results: data.movies }; - } - }, - formatResult: movieFormatResult, - formatSelection: movieFormatSelection, - dropdownCssClass: "bigdrop" -}); -$("#e7").select2({ - placeholder: "Search for a movie", - minimumInputLength: 3, - ajax: { - url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", - dataType: 'jsonp', - quietMillis: 100, - data: function (term, page) { - return { - q: term, - page_limit: 10, - page: page, - apikey: "ju6z9mjyajq2djue3gbvv26t" - }; - }, - results: function (data, page) { - var more = (page * 10) < data.total; - return { results: data.movies, more: more }; - } - }, - formatResult: movieFormatResult, - formatSelection: movieFormatSelection, - dropdownCssClass: "bigdrop" -}); - -$("#e8").select2(); -$("#e8_get").click(function () { alert("Selected value is: " + $("#e8").select2("val")); }); -$("#e8_set").click(function () { $("#e8").select2("val", "CA"); }); -$("#e8_cl").click(function () { $("#e8").select2("val", ""); }); -$("#e8_get2").click(function () { alert("Selected data is: " + JSON.stringify($("#e8").select2("data"))); }); -$("#e8_set2").click(function () { $("#e8").select2("data", { id: "CA", text: "California" }); }); -$("#e8_open").click(function () { $("#e8").select2("open"); }); -$("#e8_close").click(function () { $("#e8").select2("close"); }); -$("#e8_2").select2(); -$("#e8_2_get").click(function () { alert("Selected value is: " + $("#e8_2").select2("val")); }); -$("#e8_2_set").click(function () { $("#e8_2").select2("val", ["CA", "MA"]); }); -$("#e8_2_get2").click(function () { alert("Selected value is: " + JSON.stringify($("#e8_2").select2("data"))); }); -$("#e8_2_set2").click(function () { $("#e8_2").select2("data", [{ id: "CA", text: "California" }, { id: "MA", text: "Massachusetts" }]); }); -$("#e8_2_cl").click(function () { $("#e8_2").select2("val", ""); }); -$("#e8_2_open").click(function () { $("#e8_2").select2("open"); }); -$("#e8_2_close").click(function () { $("#e8_2").select2("close"); }); -$("#e11").select2({ - placeholder: "Select report type", - allowClear: true, - data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] -}); -$("#e11_2").select2({ - createSearchChoice: function (term, data) { if ($(data).filter(function () { return this.text.localeCompare(term) === 0; }).length === 0) { return { id: term, text: term }; } }, - multiple: true, - data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] -}); -function log(e) { - var item = $("
      • " + e + "
      • "); - $("#events_11").append(item); - item.animate({ opacity: 1 }, 10000, 'linear', function () { item.animate({ opacity: 0 }, 2000, 'linear', function () { item.remove(); }); }); -} -$("#e11") - // TS 0.9.5: correct overload not resolved https://typescript.codeplex.com/discussions/472172 - .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) - .on("open", function () { log("open"); }); -$("#e11_2") - .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) - .on("open", function () { log("open"); }); -$("#e12").select2({ tags: ["red", "green", "blue"] }); -$("#e20").select2({ - tags: ["red", "green", "blue"], - tokenSeparators: [",", " "] -}); -$("#e13").select2(); -$("#e13_ca").click(function () { $("#e13").val("CA").trigger("change"); }); -$("#e13_ak_co").click(function () { $("#e13").val(["AK", "CO"]).trigger("change"); }); -$("#e14").val(["AL", "AZ"]).select2(); -$("#e14_init").click(function () { $("#e14").select2(); }); -$("#e14_destroy").click(function () { $("#e14").select2("destroy"); }); -$("#e15").select2({ tags: ["red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"] }); -$("#e15").on("change", function () { $("#e15_val").html($("#e15").val()); }); - -$("#e16").select2(); -$("#e16_2").select2(); -$("#e16_enable").click(function () { $("#e16,#e16_2").select2("enable"); }); -$("#e16_disable").click(function () { $("#e16,#e16_2").select2("disable"); }); -$("#e17").select2({ - matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) == 0; } -}); -$("#e17_2").select2({ - matcher: function (term, text, opt) { - return text.toUpperCase().indexOf(term.toUpperCase()) >= 0 - || opt.attr("alt").toUpperCase().indexOf(term.toUpperCase()) >= 0; - } -}); -$("#e18,#e18_2").select2(); -alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); - -$("#e8").select2("val"); -$("#e8").select2("val", "CA"); -$("#e8").select2("data"); -$("#e8").select2("data", { id: "CA", text: "Califoria" }); -$("#e8").select2("destroy"); -$("#e8").select2("open"); -$("#e8").select2("enable", false); -$("#e8").select2("readonly", false); -$("#e8").select2('container'); -$("#e8").select2('onSortStart'); -$("#e8").select2('onSortEnd'); +/// +/// + +$("#e9").select2(); +$("#e2").select2({ + placeholder: "Select a State", + allowClear: true +}); +$("#e2_2").select2({ + placeholder: "Select a State" +}); +$("#e3").select2({ + minimumInputLength: 2 +}); +function format(state) { + if (!state.id) return state.text; + return "" + state.text; +} +$("#e4").select2({ + formatResult: format, + formatSelection: format +}); +$("#e5").select2({ + minimumInputLength: 1, + query: function (query) { + var data = { results: [] }, i, j, s; + for (i = 1; i < 5; i++) { + s = ""; + for (j = 0; j < i; j++) { s = s + query.term; } + data.results.push({ id: query.term + i, text: s }); + } + } +}); +$("#e19").select2({ maximumSelectionSize: 3 }); +$("#e10").select2({ + data: [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }] +}); + +var data = [{ id: 0, tag: 'enhancement' }, { id: 1, tag: 'bug' }, { id: 2, tag: 'duplicate' }, { id: 3, tag: 'invalid' }, { id: 4, tag: 'wontfix' }]; + +$("#e10_2").select2({ + data: { results: data, text: 'tag' }, + formatSelection: format, + formatResult: format +}); + +$("#e10_3").select2({ + data: { results: data, text: function (item) { console.log('called with', item); return item.tag; } }, + formatSelection: format, + formatResult: format +}); +var movieFormatResult, movieFormatSelection; +$("#e6").select2({ + placeholder: "Search for a movie", + minimumInputLength: 1, + ajax: { + url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", + dataType: 'jsonp', + cache: false, + data: function (term, page) { + return { + q: term, + page_limit: 10, + apikey: "ju6z9mjyajq2djue3gbvv26t" + }; + }, + results: function (data, page) { + return { results: data.movies }; + } + }, + formatResult: movieFormatResult, + formatSelection: movieFormatSelection, + dropdownCssClass: "bigdrop" +}); +$("#e6").select2({ + placeholder: "Search for a movie", + minimumInputLength: 1, + ajax: { + url: () => { return "http://api.rottentomatoes.com/api/public/v1.0/movies.json"; }, + dataType: 'jsonp', + data: function (term, page) { + return { + q: term, + page_limit: 10, + apikey: "ju6z9mjyajq2djue3gbvv26t" + }; + }, + results: function (data, page) { + return { results: data.movies }; + } + }, + formatResult: movieFormatResult, + formatSelection: movieFormatSelection, + dropdownCssClass: "bigdrop" +}); +$("#e7").select2({ + placeholder: "Search for a movie", + minimumInputLength: 3, + ajax: { + url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", + dataType: 'jsonp', + quietMillis: 100, + data: function (term, page) { + return { + q: term, + page_limit: 10, + page: page, + apikey: "ju6z9mjyajq2djue3gbvv26t" + }; + }, + results: function (data, page) { + var more = (page * 10) < data.total; + return { results: data.movies, more: more }; + } + }, + formatResult: movieFormatResult, + formatSelection: movieFormatSelection, + dropdownCssClass: "bigdrop" +}); + +$("#e8").select2(); +$("#e8_get").click(function () { alert("Selected value is: " + $("#e8").select2("val")); }); +$("#e8_set").click(function () { $("#e8").select2("val", "CA"); }); +$("#e8_cl").click(function () { $("#e8").select2("val", ""); }); +$("#e8_get2").click(function () { alert("Selected data is: " + JSON.stringify($("#e8").select2("data"))); }); +$("#e8_set2").click(function () { $("#e8").select2("data", { id: "CA", text: "California" }); }); +$("#e8_open").click(function () { $("#e8").select2("open"); }); +$("#e8_close").click(function () { $("#e8").select2("close"); }); +$("#e8_2").select2(); +$("#e8_2_get").click(function () { alert("Selected value is: " + $("#e8_2").select2("val")); }); +$("#e8_2_set").click(function () { $("#e8_2").select2("val", ["CA", "MA"]); }); +$("#e8_2_get2").click(function () { alert("Selected value is: " + JSON.stringify($("#e8_2").select2("data"))); }); +$("#e8_2_set2").click(function () { $("#e8_2").select2("data", [{ id: "CA", text: "California" }, { id: "MA", text: "Massachusetts" }]); }); +$("#e8_2_cl").click(function () { $("#e8_2").select2("val", ""); }); +$("#e8_2_open").click(function () { $("#e8_2").select2("open"); }); +$("#e8_2_close").click(function () { $("#e8_2").select2("close"); }); +$("#e11").select2({ + placeholder: "Select report type", + allowClear: true, + data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] +}); +$("#e11_2").select2({ + createSearchChoice: function (term, data) { if ($(data).filter(function () { return this.text.localeCompare(term) === 0; }).length === 0) { return { id: term, text: term }; } }, + multiple: true, + data: [{ id: 0, text: 'story' }, { id: 1, text: 'bug' }, { id: 2, text: 'task' }] +}); +function log(e) { + var item = $("
      • " + e + "
      • "); + $("#events_11").append(item); + item.animate({ opacity: 1 }, 10000, 'linear', function () { item.animate({ opacity: 0 }, 2000, 'linear', function () { item.remove(); }); }); +} +$("#e11") + // TS 0.9.5: correct overload not resolved https://typescript.codeplex.com/discussions/472172 + .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) + .on("open", function () { log("open"); }); +$("#e11_2") + .on("change", function (e: Select2JQueryEventObject) { log(JSON.stringify({ val: e.val, added: e.added, removed: e.removed })); }) + .on("open", function () { log("open"); }); +$("#e12").select2({ tags: ["red", "green", "blue"] }); +$("#e20").select2({ + tags: ["red", "green", "blue"], + tokenSeparators: [",", " "] +}); +$("#e13").select2(); +$("#e13_ca").click(function () { $("#e13").val("CA").trigger("change"); }); +$("#e13_ak_co").click(function () { $("#e13").val(["AK", "CO"]).trigger("change"); }); +$("#e14").val(["AL", "AZ"]).select2(); +$("#e14_init").click(function () { $("#e14").select2(); }); +$("#e14_destroy").click(function () { $("#e14").select2("destroy"); }); +$("#e15").select2({ tags: ["red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"] }); +$("#e15").on("change", function () { $("#e15_val").html($("#e15").val()); }); + +$("#e16").select2(); +$("#e16_2").select2(); +$("#e16_enable").click(function () { $("#e16,#e16_2").select2("enable"); }); +$("#e16_disable").click(function () { $("#e16,#e16_2").select2("disable"); }); +$("#e17").select2({ + matcher: function (term, text) { return text.toUpperCase().indexOf(term.toUpperCase()) == 0; } +}); +$("#e17_2").select2({ + matcher: function (term, text, opt) { + return text.toUpperCase().indexOf(term.toUpperCase()) >= 0 + || opt.attr("alt").toUpperCase().indexOf(term.toUpperCase()) >= 0; + } +}); +$("#e18,#e18_2").select2(); +alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); + +$("#e8").select2("val"); +$("#e8").select2("val", "CA"); +$("#e8").select2("data"); +$("#e8").select2("data", { id: "CA", text: "Califoria" }); +$("#e8").select2("destroy"); +$("#e8").select2("open"); +$("#e8").select2("enable", false); +$("#e8").select2("readonly", false); +$("#e8").select2('container'); +$("#e8").select2('onSortStart'); +$("#e8").select2('onSortEnd'); diff --git a/select2/select2-tests.ts.tscparams b/select2/select2-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/select2/select2-tests.ts.tscparams +++ b/select2/select2-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/sencha_touch/SenchaTouch-Tests.ts.tscparams b/sencha_touch/SenchaTouch-Tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sencha_touch/SenchaTouch-Tests.ts.tscparams +++ b/sencha_touch/SenchaTouch-Tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 0bf3d6d9e..cbfc3db18 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -5365,6 +5365,11 @@ declare module "sequelize" { */ new ( uri : string, options? : Options ) : Sequelize; + /** + * Provide access to continuation-local-storage (http://docs.sequelizejs.com/en/latest/api/sequelize/#transactionoptions-promise) + */ + cls: any; + } interface QueryOptionsTransactionRequired { } diff --git a/sharepoint/SharePoint-tests.ts b/sharepoint/SharePoint-tests.ts index 0e6b53e54..5b73493b3 100644 --- a/sharepoint/SharePoint-tests.ts +++ b/sharepoint/SharePoint-tests.ts @@ -1,2566 +1,2566 @@ -/// -/// -/// -/// - - -//code from http://sptypescript.codeplex.com/ -//BasicTasksJSOM.ts -// Website tasks -function retrieveWebsite(resultpanel:HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - clientContext.load(oWebsite); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Web site title: " + oWebsite.get_title(); - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function retrieveWebsiteProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - clientContext.load(oWebsite, "Description", "Created"); - - clientContext.executeQueryAsync(successHandler,errorHandler); - - function successHandler() { - resultpanel.innerHTML = "Description: " + oWebsite.get_description() + - "
        Date created: " + oWebsite.get_created(); - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function writeWebsiteProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - oWebsite.set_description("This is an updated description."); - oWebsite.update(); - - clientContext.load(oWebsite, "Description"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - - function successHandler() { - resultpanel.innerHTML = "Web site description: " + oWebsite.get_description(); - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Lists tasks -function readAllProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var collList = oWebsite.get_lists(); - clientContext.load(collList); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - - var listEnumerator = collList.getEnumerator(); - - var listInfo = ""; - while (listEnumerator.moveNext()) { - var oList = listEnumerator.get_current(); - listInfo += "Title: " + oList.get_title() + " Created: " + - oList.get_created().toString() + "
        "; - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readSpecificProps(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var collList = oWebsite.get_lists(); - - clientContext.load(collList, "Include(Title, Id)"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - - var listEnumerator = collList.getEnumerator(); - - var listInfo = ""; - while (listEnumerator.moveNext()) { - var oList = listEnumerator.get_current(); - listInfo += "Title: " + oList.get_title() + - " ID: " + oList.get_id().toString() + "
        "; - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readColl(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var collList = oWebsite.get_lists(); - - var listInfoCollection = clientContext.loadQuery(collList, "Include(Title, Id)"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - var listInfo = ""; - for (var i = 0; i < listInfoCollection.length; i++) { - var oList = listInfoCollection[i]; - listInfo += "Title: " + oList.get_title() + - " ID: " + oList.get_id().toString() + "
        "; - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readFilter(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var collList = oWebsite.get_lists(); - - var listInfoArray = clientContext.loadQuery(collList, - "Include(Title,Fields.Include(Title,InternalName))"); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - - for (var i = 0; i < listInfoArray.length; i++) { - var oList = listInfoArray[i]; - var collField = oList.get_fields(); - var fieldEnumerator = collField.getEnumerator(); - - var listInfo = ""; - while (fieldEnumerator.moveNext()) { - var oField = fieldEnumerator.get_current(); - var regEx = new RegExp("name", "ig"); - - if (regEx.test(oField.get_internalName())) { - listInfo += "List: " + oList.get_title() + - "
            Field Title: " + oField.get_title() + - "
            Field Internal name: " + oField.get_internalName(); - } - } - } - - resultpanel.innerHTML = listInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Create, update and delete lists -function createList(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var listCreationInfo = new SP.ListCreationInformation(); - listCreationInfo.set_title("My Announcements List"); - listCreationInfo.set_templateType(SP.ListTemplateType.announcements); - - var oList = oWebsite.get_lists().add(listCreationInfo); - clientContext.load(oList); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function updateList(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - - var oList = oWebsite.get_lists().getByTitle("My Announcements List"); - oList.set_description("New Announcements List"); - oList.update(); - - clientContext.load(oList); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Check the description in the list."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function addField(resultpanel: HTMLElement) { - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("My Announcements List"); - - var oField = oList.get_fields().addFieldAsXml( - "", - true, - SP.AddFieldOptions.defaultValue - ); - - var fieldNumber = clientContext.castTo(oField, SP.FieldNumber); - fieldNumber.set_maximumValue(100); - fieldNumber.set_minimumValue(35); - fieldNumber.update(); - - clientContext.load(oField); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "The list with a new field."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function deleteList(resultpanel: HTMLElement) { - var listTitle = "My Announcements List"; - - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle(listTitle); - oList.deleteObject(); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = listTitle + " deleted."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Create, update and delete folders -function createFolder(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Shared Documents"); - - var itemCreateInfo = new SP.ListItemCreationInformation(); - itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder); - itemCreateInfo.set_leafName("My new folder!"); - var oListItem = oList.addItem(itemCreateInfo); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the document library to see your new folder."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function updateFolder(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Shared Documents"); - - var oListItem = oList.getItemById(1); - oListItem.set_item("FileLeafRef", "My updated folder"); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the document library to see your updated folder."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function deleteFolder(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Shared Documents"); - - var oListItem = oList.getItemById(1); - oListItem.deleteObject(); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the document library to make sure the folder is no longer there."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// List item tasks -function readItems(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - var camlQuery = new SP.CamlQuery(); - camlQuery.set_viewXml( - '' + - '1' + - '10' - ); - var collListItem = oList.getItems(camlQuery); - - clientContext.load(collListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - var listItemEnumerator = collListItem.getEnumerator(); - - var listItemInfo = ""; - while (listItemEnumerator.moveNext()) { - var oListItem = listItemEnumerator.get_current(); - listItemInfo += "ID: " + oListItem.get_id() + "
        " + - "Title: " + oListItem.get_item("Title") + "
        " + - "Body: " + oListItem.get_item("Body") + "
        "; - } - - resultpanel.innerHTML = listItemInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function readInclude(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - var camlQuery = new SP.CamlQuery(); - camlQuery.set_viewXml('100'); - - var collListItem = oList.getItems(camlQuery); - - clientContext.load(collListItem, "Include(Id, DisplayName, HasUniqueRoleAssignments)"); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - var listItemEnumerator = collListItem.getEnumerator(); - - var listItemInfo = ""; - while (listItemEnumerator.moveNext()) { - var oListItem = listItemEnumerator.get_current(); - listItemInfo += "ID: " + oListItem.get_id() + "
        " + - "Display name: " + oListItem.get_displayName() + "
        " + - "Unique role assignments: " + oListItem.get_hasUniqueRoleAssignments() + "
        "; - } - - resultpanel.innerHTML = listItemInfo; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -// Create, update and delete list items -function createListItem(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - - var itemCreateInfo = new SP.ListItemCreationInformation(); - var oListItem = oList.addItem(itemCreateInfo); - oListItem.set_item("Title", "My New Item!"); - oListItem.set_item("Body", "Hello World!"); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list to see your new item."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function updateListItem(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - - var oListItem = oList.getItemById(1); - oListItem.set_item("Title", "My updated title"); - oListItem.update(); - - clientContext.load(oListItem); - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list to see your updated item."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - -function deleteListItem(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); - var oWebsite = clientContext.get_web(); - var oList = oWebsite.get_lists().getByTitle("Announcements"); - - var oListItem = oList.getItemById(1); - oListItem.deleteObject(); - - clientContext.executeQueryAsync( - successHandler, - errorHandler - ); - - function successHandler() { - resultpanel.innerHTML = "Go to the list to make sure the item is no longer there."; - } - - function errorHandler() { - resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); - } -} - - - -/** Lightweight client-side rendering template overrides.*/ -module CSR { - - export interface UpdatedValueCallback { - (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; - } - - /** Creates new overrides. Call .register() at the end.*/ - export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { - return new csr(listTemplateType, baseViewId) - .onPreRender(hookFormContext) - .onPostRender(fixCsrCustomLayout); - - function hookFormContext(ctx: IFormRenderContexWithHook) { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - - for (var i = 0; i < ctx.ListSchema.Field.length; i++) { - var fieldSchemaInForm = ctx.ListSchema.Field[i]; - - if (!ctx.FormContextHook) { - ctx.FormContextHook = {} - - var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; - ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { - ctx.FormContextHook[fieldName].getValue = callback; - oldRegisterGetValueCallback(fieldName, callback); - }; - - var oldUpdateControlValue = ctx.FormContext.updateControlValue; - ctx.FormContext.updateControlValue = (fieldName: string, value: any) => { - oldUpdateControlValue(fieldName, value); - - var hookedContext = ensureFormContextHookField(ctx.FormContextHook, fieldName); - hookedContext.lastValue = value; - - var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; - for (var i = 0; i < updatedCallbacks.length; i++) { - updatedCallbacks[i](value, hookedContext.fieldSchema); - } - - } - } - ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; - } - } - } - - function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid - || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - return; - } - - if (ctx.ListSchema.Field.length > 1) { - var wpq = ctx.FormUniqueId; - var webpart = $get('WebPart' + wpq); - var forms = webpart.getElementsByClassName('ms-formtable'); - - if (forms.length > 0) { - var placeholder = $get(wpq + 'ClientFormTopContainer'); - var fragment = document.createDocumentFragment(); - for (var i = 0; i < placeholder.children.length; i++) { - fragment.appendChild(placeholder.children.item(i)); - } - - var form = forms.item(0); - form.parentNode.replaceChild(fragment, form); - } - - var old = ctx.CurrentItem; - ctx.CurrentItem = ctx.ListData.Items[0]; - var fields = ctx.ListSchema.Field; - for (var j = 0; j < fields.length; j++) { - var field = fields[j]; - var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; - var span = $get(pHolderId); - if (span) { - span.outerHTML = ctx.RenderFieldByName(ctx, field.Name); - } - } - ctx.CurrentItem = old; - } - - } - - - } - - -//typescripttempltes.ts - declare var Strings:any; - export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook - && contextWithHook.FormContextHook[fieldName] - && contextWithHook.FormContextHook[fieldName].getValue) { - return contextWithHook.FormContextHook[fieldName].getValue(); - } - } - return null; - } - - export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook - && contextWithHook.FormContextHook[fieldName]) { - return contextWithHook.FormContextHook[fieldName].fieldSchema; - } - } - return null; - } - - export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook) { - var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); - var callbacks = f.updatedValueCallbacks; - if (callbacks.indexOf(callback) == -1) { - callbacks.push(callback); - if (f.lastValue) { - callback(f.lastValue, f.fieldSchema); - } - } - } - } - - } - - export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; - if (contextWithHook.FormContextHook) { - var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; - var index = callbacks.indexOf(callback); - if (index != -1) { - callbacks.splice(index, 1); - } - } - } - } - - export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { - var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; - //TODO: Handle different input types - return $get(id); - } - - export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { - var ctx = { ListSchema: { Field: [field] }, FieldControlModes: {} }; - ctx.FieldControlModes[field.Name] = mode; - var templates = SPClientTemplates.TemplateManager.GetTemplates(ctx); - return templates.Fields[field.Name]; - } - - - class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { - - public Templates: SPClientTemplates.TemplateOverrides; - public OnPreRender: SPClientTemplates.RenderCallback[]; - public OnPostRender: SPClientTemplates.RenderCallback[]; - private IsRegistered: boolean; - - - constructor(public ListTemplateType?: number, public BaseViewID?: any) { - this.Templates = { Fields: {} }; - this.OnPreRender = [] ; - this.OnPostRender = []; - this.IsRegistered = false; - } - - /* tier 1 methods */ - view(template: any): ICSR { - this.Templates.View = template; - return this; - } - - item(template: any): ICSR { - this.Templates.Item = template; - return this; - } - - header(template: any): ICSR { - this.Templates.Header = template; - return this; - } - - body(template: any): ICSR { - this.Templates.Body = template; - return this; - } - - footer(template: any): ICSR { - this.Templates.Footer = template; - return this; - } - - fieldView(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].View = template; - return this; - } - - fieldDisplay(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].DisplayForm = template; - return this; - } - - fieldNew(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].NewForm = template; - return this; - } - - fieldEdit(fieldName: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName].EditForm = template; - return this; - } - - /* tier 2 methods */ - template(name: string, template: any): ICSR { - this.Templates[name] = template; - return this; - } - - fieldTemplate(fieldName: string, name: string, template: any): ICSR { - this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; - this.Templates.Fields[fieldName][name] = template; - return this; - } - - /* common */ - onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { - for (var i = 0; i < callbacks.length; i++) { - this.OnPreRender.push(callbacks[i]); - } - return this; - } - - onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { - for (var i = 0; i < callbacks.length; i++) { - this.OnPostRender.push(callbacks[i]); - } - return this; - } - - onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { - return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { - var ctxInView = ctx; - - //ListSchema schma exists in Form and in View render context - var fields = ctxInView.ListSchema.Field; - if (fields) { - for (var i = 0; i < fields.length; i++) { - if (fields[i].Name === field) { - callback(fields[i], ctx); - } - } - } - }); - } - - onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { - return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { - var ctxInView = ctx; - - //ListSchema schma exists in Form and in View render context - var fields = ctxInView.ListSchema.Field; - if (fields) { - for (var i = 0; i < fields.length; i++) { - if (fields[i].Name === field) { - callback(fields[i], ctx); - } - } - } - }); - } - - makeReadOnly(fieldName: string): ICSR { - return this - .onPreRenderField(fieldName, (schema, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid - || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; - (schema).ReadOnlyField = true; - (schema).ReadOnly = "TRUE"; - - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - var ctxInView = ctx; - if (ctxInView.inGridMode) { - //TODO: Disable editing in grid mode - - } - - } else { - var ctxInForm = ctx; - if (schema.Type != 'User' && schema.Type != 'UserMulti') { - - var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); - ctxInForm.Templates.Fields[fieldName] = template; - ctxInForm.FormContext.registerGetValueCallback(fieldName, () => ctxInForm.ListData.Items[0][fieldName]); - - } - } - - }) - .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - if (schema.Type == 'User' || schema.Type == 'UserMulti') { - SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { - var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; - var retryCount = 10; - var callback = () => { - var pp = SPClientPeoplePicker.SPClientPeoplePickerDict[topSpanId]; - if (!pp) { - if (retryCount--) setTimeout(callback, 1); - } else { - pp.SetEnabledState(false); - pp.DeleteProcessedUser = function () { }; - } - }; - callback(); - }); - } - } - }); - } - - makeHidden(fieldName: string): ICSR { - return this.onPreRenderField(fieldName, (schema, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; - (schema).Hidden = true; - - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - var ctxInView = ctx; - - if (ctxInView.inGridMode) { - //TODO: Hide item in grid mode - } else { - ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); - } - - } else { - var ctxInForm = ctx; - - var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; - var placeholder = $get(pHolderId); - var current = placeholder; - while (current.tagName.toUpperCase() !== "TR") { - current = current.parentElement; - } - var row = current; - row.style.display = 'none'; - - } - - }); - } - - filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { - - - return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) - .fieldNew(fieldName, SPFieldCascadedLookup_Edit); - - - function SPFieldCascadedLookup_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { - - var parseRegex = /\{[^\}]+\}/g; - var dependencyExpressions: string[] = []; - var result: RegExpExecArray; - while ((result = parseRegex.exec(camlFilter))) { - dependencyExpressions.push(stripBraces(result[0])); - } - var dependencyValues: { [expr: string]: string } = {}; - - var _dropdownElt: HTMLSelectElement; - var _myData: SPClientTemplates.ClientFormContext; - - - if (rCtx == null) - return ''; - _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); - - if (_myData == null || _myData.fieldSchema == null) - return ''; - - - var _schema = _myData.fieldSchema; - - var validators = new SPClientForms.ClientValidation.ValidatorSet(); - validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); - - if (_myData.fieldSchema.Required) { - validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); - } - _myData.registerClientValidator(_myData.fieldName, validators); - - var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; - var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; - var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; - var _noValueSelected = _selectedValue == 0; - var _optionsLoaded = false; - var pendingLoads = 0; - - if (_noValueSelected) - _valueStr = ''; - - _myData.registerInitCallback(_myData.fieldName, InitLookupControl); - - _myData.registerFocusCallback(_myData.fieldName, function () { - if (_dropdownElt != null) - _dropdownElt.focus(); - }); - _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { - SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); - }); - _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); - _myData.updateControlValue(_myData.fieldName, _valueStr); - - return BuildLookupDropdownControl(); - - function InitLookupControl() { - _dropdownElt = document.getElementById(_dropdownId); - if (_dropdownElt != null) - AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); - - SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => { - bindDependentControls(dependencyExpressions); - loadOptions(true); - }); - } - - - function BuildLookupDropdownControl() { - var result = ''; - result += '
        '; - return result; - } - - - function OnLookupValueChanged() { - if (_optionsLoaded) { - if (_dropdownElt != null) { - _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); - _selectedValue = parseInt(_dropdownElt.value, 10); - } - } - } - - function GetCurrentLookupValue() { - if (_dropdownElt == null) - return ''; - return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + _dropdownElt.options[_dropdownElt.selectedIndex].text; - } - - function stripBraces(input: string): string { - return input.substring(1, input.length - 1); - } - - function getDependencyValue(expr: string, value: string, listId: string, expressionParts: string[], callback: () => void) { - var isLookupValue = !!listId; - if (isLookupValue) { - var lookup = SPClientTemplates.Utility.ParseLookupValue(value); - if (expressionParts.length == 1 && expressionParts[0] == 'Value') { - value = lookup.LookupValue; - expressionParts.shift(); - } else { - value = lookup.LookupId.toString(); - } - } - - if (expressionParts.length == 0) { - dependencyValues[expr] = value; - callback(); - } else { - var ctx = SP.ClientContext.get_current(); - var web = ctx.get_web(); - //TODO: Handle lookup to another web - var list = web.get_lists().getById(listId); - var item = list.getItemById(parseInt(value, 10)); - var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); - ctx.load(item); - ctx.load(field); - - ctx.executeQueryAsync((o, e) => { - var value = item.get_item(field.get_internalName()); - - if (field.get_typeAsString() == 'Lookup') { - field = ctx.castTo(field, SP.FieldLookup); - var lookup = (value); - value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); - listId = (field).get_lookupList(); - } - - getDependencyValue(expr, value, listId, expressionParts, callback); - - }, (o, args) => { console.log(args.get_message()); }); - } - } - - function bindDependentControls(dependencyExpressions: string[]) { - dependencyExpressions.forEach(expr => { - var exprParts = expr.split("."); - var field = exprParts.shift(); - - CSR.addUpdatedValueCallback(rCtx, field, - (v, s) => { - getDependencyValue(expr, v, - (s).LookupListId, - exprParts.slice(0), - loadOptions); - }); - - }); - } - - - function loadOptions(isFirstLoad?: boolean) { - _optionsLoaded = false; - pendingLoads++; - - var ctx = SP.ClientContext.get_current(); - //TODO: Handle lookup to another web - var web = ctx.get_web(); - var listId = _schema.LookupListId; - var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); - var query = new SP.CamlQuery(); - - var predicate = camlFilter.replace(parseRegex, (v, a) => { - var expr = stripBraces(v); - return dependencyValues[expr] ? dependencyValues[expr] : ''; - }); - - //TODO: Handle ShowField attribure - if (predicate.substr(0, 5) == '' + - predicate + - ' ' + - ''); - } - var results = list.getItems(query); - ctx.load(results); - - - ctx.executeQueryAsync((o, e) => { - var selected = false; - - while (_dropdownElt.options.length) { - _dropdownElt.options.remove(0); - } - - if (!_schema.Required) { - var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); - _dropdownElt.options.add(defaultOpt); - selected = _selectedValue == 0; - } - var isEmptyList = true; - - var enumerator = results.getEnumerator(); - while (enumerator.moveNext()) { - var c = enumerator.get_current(); - var id: number; - var text: string; - - if (!lookupField) { - id = c.get_id(); - text = c.get_item('Title'); - } else { - var value = c.get_item(lookupField); - id = value.get_lookupId(); - text = value.get_lookupValue(); - } - var isSelected = _selectedValue == id; - if (isSelected) { - selected = true; - } - var opt = new Option(text, id.toString(), isSelected, isSelected); - _dropdownElt.options.add(opt); - isEmptyList = false; - } - pendingLoads--; - _optionsLoaded = true; - if (!pendingLoads) { - if (isFirstLoad) { - if (_selectedValue == 0 && !selected) { - _dropdownElt.selectedIndex = 0; - OnLookupValueChanged(); - } - } else { - if (_selectedValue != 0 && !selected) { - _dropdownElt.selectedIndex = 0; - } - OnLookupValueChanged(); - } - } - - - }, (o, args) => { console.log(args.get_message()); }); - } - } - - } - - koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { - return this.fieldEdit(fieldName, koEditField_Edit) - .fieldNew(fieldName, koEditField_Edit); - - - function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { - if (rCtx == null) - return ''; - var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); - - if (_myData == null || _myData.fieldSchema == null) - return ''; - var elementId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type; - - vm.renderingContext = rCtx; - - - if (dependencyFields) { - dependencyFields.forEach(dependencyField => { - if (!vm[dependencyField]) { - vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); - } - CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { - vm[dependencyField](v); - }); - }); - } - - - if (!vm.value) { - vm.value = ko.observable(); - } - - vm.value.subscribe(v => { _myData.updateControlValue(fieldName, v); }); - _myData.registerGetValueCallback(fieldName, () => vm.value()); - - - _myData.registerInitCallback(fieldName, () => { - ko.applyBindings(vm, $get(elementId)); - }); - - return '
        '+template+'
        '; - } - } - - computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { - var dependentValues: { [field: string]: string } = {}; - - return this.onPostRenderField(targetField, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var targetControl = CSR.getControl(schema); - sourceField.forEach((field) => { - CSR.addUpdatedValueCallback(ctx, field, v => { - dependentValues[field] = v; - targetControl.value = transform.apply(this, - sourceField.map(n => dependentValues[n] || '')); - - }); - }); - } - }); - } - - setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { - if (value || !ignoreNull) { - return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - ctx.ListData.Items[0][fieldName] = value; - }); - } else { - return this; - } - } - - - autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { - return this - .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) - .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); - - function SPFieldLookup_Autofill_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { - if (rCtx == null) - return ''; - var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); - - if (_myData == null || _myData.fieldSchema == null) - return ''; - - var _autoFillControl: SPClientAutoFill; - var _textInputElt: HTMLInputElement; - var _textInputId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type + 'Field'; - var _autofillContainerId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$AutoFill'; - - var validators = new SPClientForms.ClientValidation.ValidatorSet(); - if (_myData.fieldSchema.Required) { - validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); - } - _myData.registerClientValidator(_myData.fieldName, validators); - - _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); - _myData.registerFocusCallback(_myData.fieldName, function () { - if (_textInputElt != null) - _textInputElt.focus(); - }); - _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { - SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); - }); - _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); - _myData.updateControlValue(_myData.fieldName, _myData.fieldValue); - - return buildAutoFillControl(); - - function initAutoFillControl() { - _textInputElt = document.getElementById(_textInputId); - - SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { - _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); - var callback = init({ - renderContext: rCtx, - fieldContext: _myData, - autofill: _autoFillControl, - control: _textInputElt, - }); - - //_autoFillControl.AutoFillMinTextLength = 2; - //_autoFillControl.VisibleItemCount = 15; - //_autoFillControl.AutoFillTimeout = 500; - }); - - } - //function OnPopulate(targetElement: HTMLInputElement) { - - //} - - //function OnLookupValueChanged() { - // _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); - //} - //function GetCurrentLookupValue() { - // return _valueStr; - //} - function buildAutoFillControl() { - var result: string[] = []; - result.push('
        '); - result.push(''); - - result.push("
        "); - result.push("
        "); - - return result.join(""); - } - } - - - } - - seachLookup(fieldName: string): ICSR { - return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { - var _myData = ctx.fieldContext; - var _schema = _myData.fieldSchema; - if (_myData.fieldSchema.Type != 'Lookup') { - return null; - } - - var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; - var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); - var _noValueSelected = _selectedValue.LookupId == 0; - ctx.control.value = _selectedValue.LookupValue; - $addHandler(ctx.control, "blur", _ => { - if (ctx.control.value == '') { - _myData.fieldValue = ''; - _myData.updateControlValue(fieldName, _myData.fieldValue); - } - }); - - if (_noValueSelected) - _myData.fieldValue = ''; - - var _autoFillControl = ctx.autofill; - _autoFillControl.AutoFillMinTextLength = 2; - _autoFillControl.VisibleItemCount = 15; - _autoFillControl.AutoFillTimeout = 500; - - return () => { - var value = ctx.control.value; - _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildLoadingItem('Please wait...')], onSelectItem); - - SP.SOD.executeFunc("sp.search.js", "Microsoft.SharePoint.Client.Search.Query", () => { - var Search = Microsoft.SharePoint.Client.Search.Query; - var ctx = SP.ClientContext.get_current(); - var query = new Search.KeywordQuery(ctx); - query.set_rowLimit(_autoFillControl.VisibleItemCount); - query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); - var selectProps = query.get_selectProperties(); - selectProps.clear(); - //TODO: Handle ShowField attribute - selectProps.add('Title'); - selectProps.add('ListItemId'); - var executor = new Search.SearchExecutor(ctx); - var result = executor.executeQuery(query); - ctx.executeQueryAsync( - () => { - //TODO: Discover proper way to load collection - var tableCollection = new Search.ResultTableCollection(); - tableCollection.initPropertiesFromJson(result.get_value()); - - var relevantResults = tableCollection.get_item(0); - var rows = relevantResults.get_resultRows(); - - var items = []; - for (var i = 0; i < rows.length; i++) { - items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); - } - - items.push(AutoFillOptionBuilder.buildSeparatorItem()); - - if (relevantResults.get_totalRows() == 0) - items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); - else - items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); - - _autoFillControl.PopulateAutoFill(items, onSelectItem); - - }, - (sender, args) => { - _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildFooterItem("Error executing query/ See log for details.")], onSelectItem); - console.log(args.get_message()); - }); - }); - } - - function onSelectItem(targetInputId, item: ISPClientAutoFillData) { - var targetElement = ctx.control; - targetElement.value = item[SPClientAutoFill.DisplayTextProperty]; - _selectedValue.LookupId = item[SPClientAutoFill.KeyProperty]; - _selectedValue.LookupValue = item[SPClientAutoFill.DisplayTextProperty]; - _myData.fieldValue = item[SPClientAutoFill.KeyProperty] + ';#' + item[SPClientAutoFill.TitleTextProperty]; - _myData.updateControlValue(_myData.fieldSchema.Name, _myData.fieldValue); - } - - }); - } - - lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { - return this.onPostRenderField(fieldName, - (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) - - var control = CSR.getControl(schema); - if (control) { - var weburl = _spPageContextInfo.webServerRelativeUrl; - if (weburl[weburl.length - 1] == '/') { - weburl = weburl.substring(0, weburl.length - 1); - } - var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' - + "&ListId=" + encodeURIComponent('{' + schema.LookupListId + '}'); - if (contentTypeId) { - newFormUrl += '&ContentTypeId=' + contentTypeId; - } - - var link = document.createElement('a'); - link.href = "javascript:NewItem2(event, \'" + newFormUrl + "&Source=" + encodeURIComponent(document.location.href) + "')"; - link.textContent = prompt; - if (control.nextElementSibling) { - control.parentElement.insertBefore(link, control.nextElementSibling); - } else { - control.parentElement.appendChild(link); - } - - if (showDialog) { - $addHandler(link, "click", (e: Sys.UI.DomEvent) => { - SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.ShowPopupDialog', () => { - SP.UI.ModalDialog.ShowPopupDialog(newFormUrl); - }); - e.stopPropagation(); - e.preventDefault(); - }); - } - } - }); - } - - register() { - if (!this.IsRegistered) { - SPClientTemplates.TemplateManager.RegisterTemplateOverrides(this); - this.IsRegistered = true; - } - } - } - - export class AutoFillOptionBuilder { - - static buildFooterItem(title: string): ISPClientAutoFillData { - var item = {}; - - item[SPClientAutoFill.DisplayTextProperty] = title; - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer; - - return item; - } - - static buildOptionItem(id: number, title: string, displayText?: string, subDisplayText?: string): ISPClientAutoFillData { - - var item = {}; - - item[SPClientAutoFill.KeyProperty] = id; - item[SPClientAutoFill.DisplayTextProperty] = displayText || title; - item[SPClientAutoFill.SubDisplayTextProperty] = subDisplayText; - item[SPClientAutoFill.TitleTextProperty] = title; - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option; - - return item; - } - - static buildSeparatorItem(): ISPClientAutoFillData { - var item = {}; - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator; - return item; - } - - static buildLoadingItem(title: string): ISPClientAutoFillData { - var item = {}; - - item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Loading; - item[SPClientAutoFill.DisplayTextProperty] = title; - return item; - } - - } - - /** Lightweight client-side rendering template overrides.*/ - export interface ICSR { - /** Override rendering template. - @param name Name of template to override. - @param template New template. - */ - template(name: string, template: string): ICSR; - - /** Override rendering template. - @param name Name of template to override. - @param template New template. - */ - template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override field rendering template. - @param name Internal name of field to override. - @param name Name of template to override. - @param template New template. - */ - fieldTemplate(field: string, name: string, template: string): ICSR; - - /** Override field rendering template. - @param name Internal name of field to override. - @param name Name of template to override. - @param template New template. - */ - fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Sets pre-render callbacks. Callback called before rendering starts. - @param callbacks pre-render callbacks. - */ - onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; - - /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. - @param callbacks post-render callbacks. - */ - onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; - - /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. - @param fieldName Internal name of the field. - @param callbacks pre-render callbacks. - */ - onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; - - /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. - @param fieldName Internal name of the field. - @param callbacks post-render callbacks. - */ - onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; - - /** Registers overrides in client-side templating engine.*/ - register(): void; - - /** Override View rendering template. - @param template New view template. - */ - view(template: string): ICSR; - - /** Override View rendering template. - @param template New view template. - */ - view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; - view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; - - /** Override Item rendering template. - @param template New item template. - */ - item(template: string): ICSR; - - /** Override Item rendering template. - @param template New item template. - */ - item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; - item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; - - /** Override Header rendering template. - @param template New header template. - */ - header(template: string): ICSR; - - /** Override Header rendering template. - @param template New header template. - */ - header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override Body rendering template. - @param template New body template. - */ - body(template: string): ICSR; - - /** Override Body rendering template. - @param template New body template. - */ - body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override Footer rendering template. - @param template New footer template. - */ - footer(template: string): ICSR; - - /** Override Footer rendering template. - @param template New footer template. - */ - footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; - - /** Override View rendering template for specified field. - @param fieldName Internal name of the field. - @param template New View template. - */ - fieldView(fieldName: string, template: string): ICSR; - - /** Override View rendering template for specified field. - @param fieldName Internal name of the field. - @param template New View template. - */ - fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; - - /** Override DisplyForm rendering template for specified field. - @param fieldName Internal name of the field. - @param template New DisplyForm template. - */ - fieldDisplay(fieldName: string, template: string): ICSR; - - /** Override DisplyForm rendering template. - @param fieldName Internal name of the field. - @param template New DisplyForm template. - */ - fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; - - /** Override EditForm rendering template for specified field. - @param fieldName Internal name of the field. - @param template New EditForm template. - */ - fieldEdit(fieldName: string, template: string): ICSR; - - /** Override EditForm rendering template. - @param fieldName Internal name of the field. - @param template New EditForm template. - */ - fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; - - /** Override NewForm rendering template for specified field. - @param fieldName Internal name of the field. - @param template New NewForm template. - */ - fieldNew(fieldName: string, template: string): ICSR; - - /** Override NewForm rendering template. - @param fieldName Internal name of the field. - @param template New NewForm template. - */ - fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; - - - /** Set initial value for field. - @param fieldName Internal name of the field. - @param value Initial value for field. - */ - setInitialValue(fieldName: string, value: any): ICSR; - - /** Make field hidden in list view and standard forms. - @param fieldName Internal name of the field. - */ - makeHidden(fieldName: string): ICSR - - - /** Replace New and Edit templates for field to Display template. - @param fieldName Internal name of the field. - */ - makeReadOnly(fieldName: string): ICSR - - /** Create cascaded Lookup Field. - @param fieldName Internal name of the field. - @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. - */ - filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR - - /** Auto computes text-based field value based on another fields. - @param targetField Internal name of the field. - @param transform Function combines source field values. - @param sourceField Internal names of source fields. - */ - computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR - - /** Field text value with autocomplete based on autofill.js - @param fieldName Internal name of the field. - @param ctx AutoFill context. - */ - autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR - - /** Replace defult dropdown to search-based autocomplete for Lookup field. - @param fieldName Internal name of the field. - */ - seachLookup(fieldName: string): ICSR; - - /** Adds link to add new value to lookup list. - @param fieldName Internal name of the field. - @param prompt Text to display as a link to add new value. - @param contentTypeID Default content type for new item. - */ - lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; - - koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; - - - } - - export interface IAutoFillFieldContext { - renderContext: SPClientTemplates.RenderContext_FieldInForm; - fieldContext: SPClientTemplates.ClientFormContext; - autofill: SPClientAutoFill; - control: HTMLInputElement; - } - - export interface IKoFieldInForm { - renderingContext?:SPClientTemplates.RenderContext_FieldInForm; - value?:KnockoutObservable; - } - - - interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { - FormContextHook: IFormContextHook; - } - - interface IFormContextHook { - [fieldName: string]: IFormContextHookField; - } - - interface IFormContextHookField { - fieldSchema?: SPClientTemplates.FieldSchema_InForm; - lastValue?: any; - getValue?: () => any; - updatedValueCallbacks: UpdatedValueCallback[]; - } - - - function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { - return hook[fieldName] = hook[fieldName] || { - updatedValueCallbacks: [] - }; - - } - - class BooleanValueValidator implements SPClientForms.ClientValidation.IValidator { - constructor(public valueGetter: () => boolean, public validationMessage: string) { } - - Validate(value: any): SPClientForms.ClientValidation.ValidationResult { - return new SPClientForms.ClientValidation.ValidationResult(!this.valueGetter(), this.validationMessage); - } - } - -} - -if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { - SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); -} - - -//mquery.ts - - - - -module spdevlab { - export module mQuery { - export class DynamicTable { - - // private fields - _domContainer:HTMLElement; - _tableContainer:MQueryResultSetElements; - - _rowTemplateId:string = null; - _rowTemplateContent:string = null; - - _options = { - tableCnt: '.spdev-rep-tb', - addCnt: '.spdev-rep-tb-add', - removeCnt: '.spdev-rep-tb-del' - }; - - // public methods - init(domContainer: HTMLElement, options) { - - if (m$.isDefinedAndNotNull(options)) { - m$.extend(this._options, options); - } - - this._initContainers(domContainer); - - this._initRowTemplate(); - this._initEvents(); - this._showUI(); - } - - // private methods - _initContainers(domContainer) { - - this._domContainer = domContainer; - this._tableContainer = m$(this._options.tableCnt, this._domContainer); - } - - _showUI() { - m$(this._domContainer).css("display", ""); - } - - _initEvents() { - - m$(this._options.addCnt, this._domContainer).click(() => { - - if (m$.isDefinedAndNotNull(this._rowTemplateContent)) { - - m$(this._tableContainer).append(this._rowTemplateContent); - - m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { - - var targetElement = e.currentTarget; - var parentRow = m$(targetElement).parents("tr").first(); - - m$(parentRow).remove(); - }); - } - - return false; - }); - } - - _initRowTemplate() { - var templateId = m$(this._tableContainer).attr("template-id"); - - if (m$.isDefinedAndNotNull(templateId)) { - this._rowTemplateId = templateId; - this._rowTemplateContent = DynamicTable._templates[templateId]; - } - } - - static _templates:string[] = []; - static initTables() { - // init templates - m$('script').forEach((template:HTMLElement) => { - - var id = m$(template).attr("dynamic-table-template-id"); - - if (m$.isDefinedAndNotNull(id)) { - DynamicTable._templates[id] = template.innerHTML; - } - }); - - // init tables - m$(".spdev-rep-tb-cnt").forEach( divContainer => { - - var dynamicTable = new DynamicTable(); - - dynamicTable.init(divContainer, { - removeCnt: '.spdev-rep-tb-del-override' - }); - }); - } - - }; - - - } -} - -m$.ready(() => { - spdevlab.mQuery.DynamicTable.initTables(); -}); - - -//whoisapppart.ts - - -module _ { - var queryString = parseQueryString(); - var isIframe = queryString['DisplayMode'] == 'iframe' - var spHostUrl = queryString['SPHostUrl']; - var editmode = Number(queryString['editmode']); - var includeDetails = queryString['boolProp'] == 'true'; - - prepareVisual(); - m$.ready(() => { - loadPeoplePicker('peoplePicker'); - partProperties(); - - if (isIframe) { - partResize(); - } - }); - - //Load the people picker - function loadPeoplePicker(peoplePickerElementId: string) { - var schema: ISPClientPeoplePickerSchema = { - PrincipalAccountType: "User", - AllowMultipleValues: false, - Width: 300, - OnUserResolvedClientScript: onUserResolvedClientScript - } - - SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); - } - - function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { - if (users.length > 0) { - var person = users[0]; - var accountName = person.Key; - - var context = SP.ClientContext.get_current(); - - var peopleManager = new SP.UserProfiles.PeopleManager(context); - var personProperties = peopleManager.getPropertiesFor(accountName); - - context.load(personProperties); - context.executeQueryAsync((sender, args) => { - - $get("basicInfo").style.display = 'block'; - - var userPic = personProperties.get_userProfileProperties()["PictureURL"]; - $get("pic").innerHTML = ' + personProperties.get_displayName() + '; - - $get("name").innerHTML = '' + personProperties.get_displayName() + ''; - $get("email").innerHTML = '' + personProperties.get_email() + ''; - $get("title").innerHTML = personProperties.get_title(); - $get("department").innerHTML = person.EntityData.Department; - $get("phone").innerHTML = person.EntityData.MobilePhone; - - var properties = personProperties.get_userProfileProperties(); - var messageText = ""; - for (var key in properties) { - messageText += "
        [" + key + "]: \"" + properties[key] + "\""; - } - $get("detailInfo").innerHTML = messageText; - - if (isIframe) { - partResize(); - } - - }, (sender, args) => { alert('Error: ' + args.get_message()); }); - - } - } - - function partProperties() { - - if (editmode == 1) { - $get("editmodehdr").style.display = "inline"; - $get("content").style.display = "none"; - } - else if (includeDetails) { - $get('detailInfo').style.display = 'block'; - - $get("editmodehdr").style.display = "none"; - $get("content").style.display = "inline"; - } - } - - function partResize() { - var bounds = Sys.UI.DomElement.getBounds(document.body); - parent.postMessage('resize(' + bounds.width + ',' + bounds.height + ')', '*'); - } - - function prepareVisual() { - if (isIframe) { - //Create a Link element for the defaultcss.ashx resource - var linkElement = document.createElement('link'); - linkElement.setAttribute('rel', 'stylesheet'); - linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); - - //Add the linkElement as a child to the head section of the html - document.head.appendChild(linkElement); - } else { - - m$.ready(() => { - var nav = new SP.UI.Controls.Navigation('navigation', { - appIconUrl: queryString['SPHostLogo'], - appTitle: document.title - }); - nav.setVisible(true); - $get('apppart-notification').style.display = 'block'; - document.body.style.overflow = 'visible'; - }); - } - } - - function parseQueryString() { - var result = {}; - var qs = document.location.search.split('?')[1]; - if (qs) { - var parts = qs.split('&'); - for (var i = 0; i < parts.length; i++) { - if (parts[i]) { - var pair = parts[i].split('='); - result[pair[0]] = decodeURIComponent(pair[1]); - } - } - } - return result; - } -} - -//taxonomy -module SP { - - // Class - export class ClientContextPromise extends SP.ClientContext { - /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ - executeQueryPromise(): JQueryPromise { - var deferred = jQuery.Deferred(); - this.executeQueryAsync(function (sender, args) { - deferred.resolve(sender, args); - }, - function (sender, args) { - deferred.reject(sender, args); - }) - return deferred.promise(); - } - - constructor(serverRelativeUrlOrFullUrl: string) { - super(serverRelativeUrlOrFullUrl); - } - - static get_current(): ClientContextPromise { - return new ClientContextPromise(_spPageContextInfo.siteServerRelativeUrl); - } - - } - -} - -SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); - -module _ { - var context: SP.ClientContextPromise; - var web: SP.Web; - var site: SP.Site; - var session: SP.Taxonomy.TaxonomySession; - var termStore: SP.Taxonomy.TermStore; - var groups: SP.Taxonomy.TermGroupCollection; - - // This code runs when the DOM is ready and creates a context object - // which is needed to use the SharePoint object model. - // It also wires up the click handlers for the two HTML buttons in Default.aspx. - $(document).ready(function () { - context = SP.ClientContextPromise.get_current(); - site = context.get_site(); - web = context.get_web(); - $('#listExisting').click(function () { listGroups(); }); - $('#createTerms').click(function () { createTerms(); }); - }); - - // When the listExisting button is clicked, start by loading - // a TaxonomySession for the current context. Also get and load - // the associated term store. - function listGroups() { - session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); - termStore = session.getDefaultSiteCollectionTermStore(); - context.load(session); - context.load(termStore); - context.executeQueryAsync(onListTaxonomySession, onFailListTaxonomySession); - } - - // Runs when the executeQueryAsync method in the listGroups function has succeeded. - // In this case, get and load the groups associated with the term store that we - // know we now have a reference to. - function onListTaxonomySession() { - groups = termStore.get_groups(); - context.load(groups); - context.executeQueryAsync(onRetrieveGroups, onFailRetrieveGroups); - } - - // Runs when the executeQueryAsync method in the onListTaxonomySession function has succeeded. - // In this case, loop through all the groups and add a clickable div element to the report area - // for each group. - // NOTE: We clear the report area first to ensure we have a clean place to write to. - // Also note how we create a click event handler for each div on-the-fly, and that we pass in the - // current group ID to that function. So when the user clicks one of these divs, we will know which - // one was clicked. - function onRetrieveGroups() { - $('#report').children().remove(); - - var groupEnum = groups.getEnumerator(); - - // For each group, we'll build a clickable div. - while (groupEnum.moveNext()) { - (() => { - var currentGroup = groupEnum.get_current(); - var groupName = document.createElement("div"); - groupName.setAttribute("style", "float:none;cursor:pointer"); - var groupID = currentGroup.get_id(); - groupName.setAttribute("id", groupID.toString()); - $(groupName).click(() => showTermSets(groupID)); - groupName.appendChild(document.createTextNode(currentGroup.get_name())); - $('#report').append(groupName); - })(); - } - } - - // This is the function that runs when the user clicks one of the divs - // that we created in the onRetrieveGroups function. We can know which - // div was clicked by interrogating the groupID parameter. So what we'll - // do is retrieve a reference to the group with the same ID as the div, and - // then add the term sets that belong to that group under the div that was clicked. - function showTermSets(groupID: SP.Guid) { - - // First thing is to remnove the divs under the group DIV to ensure we have a clean place to write to. - // The reason we don't clear them all is becuase we want to retain the text node of the - // group div. I.E. that's why we use "parentDiv.childNodes.length>1" as our loop - // controller. - var parentDiv = document.getElementById(groupID.toString()); - while (parentDiv.childNodes.length > 1) { - parentDiv.removeChild(parentDiv.lastChild); - } - - // For each term set, we'll build a clickable div - var currentGroup = groups.getById(groupID); - - // We need to load and populate the matching group first, or the - // term sets that it contains will be inaccessible to our code. - context.load(currentGroup); - var termSets: SP.Taxonomy.TermSetCollection; - context.executeQueryPromise() - .then( - () => { - // The group is now available becuase this is the - // success callback. So now we'll load and populate the - // term set collection. We have to do this before we can - // iterate through the collection, so we can do this - // with the following nested executeQueryAsync method call. - termSets = currentGroup.get_termSets(); - context.load(termSets); - return context.executeQueryPromise() - }) - .then(() => { - // The term sets are now available becuase this is the - // success callback. So now we'll iterate through the collection - // and create the clickable div. Also note how we create a - // click event handler for each div on-the-fly, and that we pass in the - // current group ID and term set ID to that function. So when the user - // clicks one of these divs, we will know which - // one was clicked by its term set ID, and to which group it belongs by its - // group ID. We also pass in the event object, so that we can cancel the bubble - // because this clickable div will be inside a parent clickable div and we - // don't want the parent's event to fire. - var termSetEnum = termSets.getEnumerator(); - while (termSetEnum.moveNext()) { - (() => { - var currentTermSet = termSetEnum.get_current(); - var termSetName = document.createElement("div"); - termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); - termSetName.setAttribute("style", "float:none;cursor:pointer;"); - var termSetID = currentTermSet.get_id(); - termSetName.setAttribute("id", termSetID.toString()); - $(termSetName).click(e => showTerms(e, groupID, termSetID)); - parentDiv.appendChild(termSetName); - })(); - } - - }) - .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); - } - - - // This is the function that runs when the user clicks one of the divs - // that we created in the showTermSets function. We can know which - // div was clicked by interrogating the termSetID parameter. So what we'll - // do is retrieve a reference to the term set with the same ID as the div, and - // then add the term that belong to that term set under the div that was clicked. - - function showTerms(event: JQueryEventObject, groupID: SP.Guid, termSetID: SP.Guid) { - - // First, cancel the bubble so that the group div click handler does not also fire - // because that removes all term set divs and we don't want that here. - event.cancelBubble = true; - - // Get a reference to the term set div that was click and - // remove its children (apart from the TextNode that is currently - // showing the term set name. - var parentDiv = document.getElementById(termSetID.toString()); - while (parentDiv.childNodes.length > 1) { - parentDiv.removeChild(parentDiv.lastChild); - } - - // We need to load and populate the matching group first, or the - // term sets that it contains will be inaccessible to our code. - var currentGroup = groups.getById(groupID); - var termSets:SP.Taxonomy.TermSetCollection; - var currentTermSet:SP.Taxonomy.TermSet; - var terms:SP.Taxonomy.TermCollection; - - context.load(currentGroup); - context - .executeQueryPromise() - .then(() => { - // The group is now available becuase this is the - // success callback. So now we'll load and populate the - // term set collection. We have to do this before we can - // iterate through the collection, so we can do this - // with the following nested executeQueryAsync method call. - termSets = currentGroup.get_termSets(); - context.load(termSets); - return context.executeQueryPromise(); - }) - .then(() => { - currentTermSet = termSets.getById(termSetID); - context.load(currentTermSet); - return context.executeQueryPromise(); - }) - .then(() => { - terms = currentTermSet.get_terms(); - context.load(terms); - return context.executeQueryPromise(); - }) - .then(() => { - var termsEnum = terms.getEnumerator(); - while (termsEnum.moveNext()) { - var currentTerm = termsEnum.get_current(); - - var term = document.createElement("div"); - term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); - term.setAttribute("style", "float:none;margin-left:10px;"); - parentDiv.appendChild(term); - } - }) - .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); - } - - // Runs when the executeQueryAsync method in the onListTaxonomySession function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailRetrieveGroups(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to retrieve groups. Error:" + args.get_message()); - } - - // Runs when the executeQueryAsync method in the listGroups function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailListTaxonomySession(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to get session. Error: " + args.get_message()); - } - - - // When the createTerms button is clicked, start by loading - // a TaxonomySession for the current context. Also get and load - // the associated term store. - function createTerms() { - session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); - termStore = session.getDefaultSiteCollectionTermStore(); - context.load(session); - context.load(termStore); - context.executeQueryAsync(onGetTaxonomySession, onFailTaxonomySession); - } - - - // This function is the success callback for loading the session and store from the createTerms function - function onGetTaxonomySession() { - // Create six GUIDs that we will need when we create a new group, term set, and associated terms - var guidGroupValue = SP.Guid.newGuid(); - var guidTermSetValue = SP.Guid.newGuid(); - var guidTerm1 = SP.Guid.newGuid(); - var guidTerm2 = SP.Guid.newGuid(); - var guidTerm3 = SP.Guid.newGuid(); - var guidTerm4 = SP.Guid.newGuid(); - - // Create a new group - var myGroup = termStore.createGroup("CustomTerms", guidGroupValue); - - // Create a new term set in the newly-created group - var myTermSet = myGroup.createTermSet("Privacy", guidTermSetValue, 1033); - - // Create four new terms in the newly-created term set - myTermSet.createTerm("Top Secret", 1033, guidTerm1); - myTermSet.createTerm("Company Confidential", 1033, guidTerm2); - myTermSet.createTerm("Partners Only", 1033, guidTerm3); - myTermSet.createTerm("Public", 1033, guidTerm4); - - // Ensure the groups variable has been set, because when this all succeeds we will - // effectively run the same code as if the user had clicked the listGroups button - groups = termStore.get_groups(); - context.load(groups); - - // Execute all the preceeding statements in this function - context.executeQueryAsync(onAddTerms, onFailAddTerms); - - } - - // If all is well with creating the terms, then this function will run. - // Effectively this runs the same code as if the user had clicked the listGroups button - // so the user will see their newly-created group - function onAddTerms() { - listGroups(); - } - - // Runs when the executeQueryAsync method in the onGetTaxonomySession function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailAddTerms(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to add terms. Error: " + args.get_message()); - } - - // Runs when the executeQueryAsync method in the createTerms function has failed. - // In this case, clear the report area in the page and tell the user what went wrong. - function onFailTaxonomySession(sender, args) { - $('#report').children().remove(); - $('#report').append("Failed to get session. Error: " + args.get_message()); - } - -}; - -//publishing.ts -// Variables used in various callbacks -JSRequest.EnsureSetup(); - -SP.SOD.execute('mquery.js', 'm$.ready', () => { - var context = SP.ClientContext.get_current(); - var web = context.get_web(); - m$('#CreatePage').click(createPage); -}); - -function createPage(evt) { - SP.SOD.execute('sp.js', 'SP.ClientConext', () => { - SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { - var context = SP.ClientContext.get_current(); - - - var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); - var hostcontext = new SP.AppContextSite(context, hostUrl); - var web = hostcontext.get_web(); - var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); - context.load(web); - context.load(pubWeb); - context.executeQueryAsync( - // Success callback after getting the host Web as a PublishingWeb. - // We now want to add a new Publishing Page. - function () { - var pageInfo = new SP.Publishing.PublishingPageInformation(); - var newPage = pubWeb.addPublishingPage(pageInfo); - context.load(newPage); - context.executeQueryAsync( - function () { - - // Success callback after adding a new Publishing Page. - // We want to get the actual list item that is represented by the Publishing Page. - var listItem = newPage.get_listItem(); - context.load(listItem); - context.executeQueryAsync( - - // Success callback after getting the actual list item that is - // represented by the Publishing Page. - // We can now get its FieldValues, one of which is its FileLeafRef value. - // We can then use that value to build the Url to the new page - // and set the href or our link to that Url. - function () { - var link = document.getElementById("linkToPage"); - link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); - link.innerText = "Go to new page!"; - }, - - // Failure callback after getting the actual list item that is - // represented by the Publishing Page. - function (sender, args) { - alert('Failed to get new page: ' + args.get_message()); - } - ); - }, - // Failure callback after trying to add a new Publishing Page. - function (sender, args) { - alert('Failed to Add Page: ' + args.get_message()); - } - ); - }, - // Failure callback after trying to get the host Web as a PublishingWeb. - function (sender, args) { - alert('Failed to get the PublishingWeb: ' + args.get_message()); - } - ); - }); - }); -} - -//likes -module SampleReputation { - - interface MyList extends SPClientTemplates.RenderContext_InView { - listId: string; - } - - class MyItem { - - id: number; - title: string; - likesCount: number; - isLikedByCurrentUser: boolean; - - constructor(public row: SPClientTemplates.Item) { - this.id = parseInt(row['ID']); - this.title = row['Title']; - this.likesCount = parseInt(row['LikesCount']) || 0; - this.isLikedByCurrentUser = this.getLike(row['LikedBy']); - } - - private getLike(likedBy): boolean { - if (likedBy && likedBy.length > 0) { - for (var i = 0; i < likedBy.length; i++) { - if (likedBy[i].id == _spPageContextInfo.userId) { - return true; - } - } - } - return false; - } - } - - function init() { - SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js'); - SP.SOD.registerSod('typescripttemplates.ts', '/SPTypeScript/Extensions/typescripttemplates.js'); - SP.SOD.executeFunc('typescripttemplates.ts', 'CSR', () => { - CSR.override(10004, 1) - .onPreRender((ctx: MyList) => { - ctx.listId = ctx.listName.substring(1, 37); - }) - .header('
          ') - .body(renderTemplate) - .footer('
        ') - .register(); - }); - - SP.SOD.execute('mQuery.js', 'm$.ready', () => { - RegisterModuleInit('/SPTypeScript/ReputationModule/likes.js', init); - }); - - - SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('likes.js'); - } - - function renderTemplate(ctx: MyList) { - var rows = ctx.ListData.Row; - var result = ''; - for (var i = 0; i < rows.length; i++) { - var item = new MyItem(rows[i]); - result += '\ -
      • ' + item.title +'\ - \ - ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ - \ -
      • '; - } - return result; - } - - function getLikeText(isLikedByCurrentUser: boolean) { - return isLikedByCurrentUser ? '\u2665' : '\u2661'; - } - - export function setLike(itemId: number, listId: string): void { - var context = SP.ClientContext.get_current(); - var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; - SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { - Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); - context.executeQueryAsync( - () => { - m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); - var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); - m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); - }, - (sender, args) => { - alert(args.get_message()); - }); - }); - } - - init(); -} - - - -//code from https://github.com/gandjustas/SharePointAngularTS -module App { - "use strict"; -var app = angular.module("app", []); -} - -// Install the angularjs.TypeScript.DefinitelyTyped NuGet package -module App { - "use strict"; - - interface Iappcontroller { - title: string; - activate: () => void; - } - - class appcontroller implements Iappcontroller { - title: string = "appcontroller"; - lists: SP.List[]; - - static $inject: string[] = ["$SharePoint", "$spnotify"]; - - constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { - this.activate(); - } - - activate() { - var loading = this.$n.showLoading(true) - this.$SharePoint - .getLists() - .then(l => this.lists = l ) - .catch((e: string) => this.$n.show(e, true)) - .finally(() => this.$n.remove(loading) ); - ; - - } - } - - angular.module("app").controller("appcontroller", appcontroller); -} - - - -module App { - "use strict"; - - export interface ISharePoint { - getLists: () => ng.IPromise; - } - - class SharePointServcie implements ISharePoint { - static $inject: string[] = ["$q"]; - - constructor(public $q: ng.IQService) { - } - - getLists() { - var promise = this.$q.defer(); - SP.SOD.executeFunc("sp.js", "SP.ClientContext", () => { - var ctx = SP.ClientContext.get_current(); - var hostUrl = decodeURIComponent(SP.ScriptHelpers.getDocumentQueryPairs()['SPHostUrl']); - var appCtx = new SP.AppContextSite(ctx, hostUrl); - var hostWeb = appCtx.get_web(); - var lists = hostWeb.get_lists(); - ctx.load(lists); - - ctx.executeQueryAsync(() => { - var result: SP.List[] = []; - for (var e = lists.getEnumerator(); e.moveNext();) { - result.push(e.get_current()); - } - promise.resolve(result); - }, - (o, args) => { promise.reject(args.get_message()); }); - }); - return promise.promise; - } - } - - angular.module("app").service("$SharePoint", SharePointServcie); -} - - -// Install the angularjs.TypeScript.DefinitelyTyped NuGet package -module App { - "use strict"; - - export interface ISpNotify { - showLoading(sticky?: boolean) : string; - show(msg: string, sticky?: boolean): string; - remove(id: string):void; - } - - class SpNotify implements ISpNotify { - static $inject: string[] = []; - - - showLoading(sticky: boolean = false) { - return SP.UI.Notify.showLoadingNotification(sticky); - } - - show(msg: string, sticky: boolean = false) { - return SP.UI.Notify.addNotification(msg, sticky); - } - - remove(id: string) { - SP.UI.Notify.removeNotification(id); - } - } - - angular.module("app").service("$spnotify", SpNotify); -} - +/// +/// +/// +/// + + +//code from http://sptypescript.codeplex.com/ +//BasicTasksJSOM.ts +// Website tasks +function retrieveWebsite(resultpanel:HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + clientContext.load(oWebsite); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Web site title: " + oWebsite.get_title(); + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function retrieveWebsiteProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + clientContext.load(oWebsite, "Description", "Created"); + + clientContext.executeQueryAsync(successHandler,errorHandler); + + function successHandler() { + resultpanel.innerHTML = "Description: " + oWebsite.get_description() + + "
        Date created: " + oWebsite.get_created(); + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function writeWebsiteProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + oWebsite.set_description("This is an updated description."); + oWebsite.update(); + + clientContext.load(oWebsite, "Description"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + + function successHandler() { + resultpanel.innerHTML = "Web site description: " + oWebsite.get_description(); + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Lists tasks +function readAllProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var collList = oWebsite.get_lists(); + clientContext.load(collList); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + + var listEnumerator = collList.getEnumerator(); + + var listInfo = ""; + while (listEnumerator.moveNext()) { + var oList = listEnumerator.get_current(); + listInfo += "Title: " + oList.get_title() + " Created: " + + oList.get_created().toString() + "
        "; + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readSpecificProps(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var collList = oWebsite.get_lists(); + + clientContext.load(collList, "Include(Title, Id)"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + + var listEnumerator = collList.getEnumerator(); + + var listInfo = ""; + while (listEnumerator.moveNext()) { + var oList = listEnumerator.get_current(); + listInfo += "Title: " + oList.get_title() + + " ID: " + oList.get_id().toString() + "
        "; + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readColl(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var collList = oWebsite.get_lists(); + + var listInfoCollection = clientContext.loadQuery(collList, "Include(Title, Id)"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + var listInfo = ""; + for (var i = 0; i < listInfoCollection.length; i++) { + var oList = listInfoCollection[i]; + listInfo += "Title: " + oList.get_title() + + " ID: " + oList.get_id().toString() + "
        "; + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readFilter(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var collList = oWebsite.get_lists(); + + var listInfoArray = clientContext.loadQuery(collList, + "Include(Title,Fields.Include(Title,InternalName))"); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + + for (var i = 0; i < listInfoArray.length; i++) { + var oList = listInfoArray[i]; + var collField = oList.get_fields(); + var fieldEnumerator = collField.getEnumerator(); + + var listInfo = ""; + while (fieldEnumerator.moveNext()) { + var oField = fieldEnumerator.get_current(); + var regEx = new RegExp("name", "ig"); + + if (regEx.test(oField.get_internalName())) { + listInfo += "List: " + oList.get_title() + + "
            Field Title: " + oField.get_title() + + "
            Field Internal name: " + oField.get_internalName(); + } + } + } + + resultpanel.innerHTML = listInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Create, update and delete lists +function createList(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var listCreationInfo = new SP.ListCreationInformation(); + listCreationInfo.set_title("My Announcements List"); + listCreationInfo.set_templateType(SP.ListTemplateType.announcements); + + var oList = oWebsite.get_lists().add(listCreationInfo); + clientContext.load(oList); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function updateList(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + + var oList = oWebsite.get_lists().getByTitle("My Announcements List"); + oList.set_description("New Announcements List"); + oList.update(); + + clientContext.load(oList); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Check the description in the list."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function addField(resultpanel: HTMLElement) { + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("My Announcements List"); + + var oField = oList.get_fields().addFieldAsXml( + "", + true, + SP.AddFieldOptions.defaultValue + ); + + var fieldNumber = clientContext.castTo(oField, SP.FieldNumber); + fieldNumber.set_maximumValue(100); + fieldNumber.set_minimumValue(35); + fieldNumber.update(); + + clientContext.load(oField); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "The list with a new field."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function deleteList(resultpanel: HTMLElement) { + var listTitle = "My Announcements List"; + + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle(listTitle); + oList.deleteObject(); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = listTitle + " deleted."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Create, update and delete folders +function createFolder(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Shared Documents"); + + var itemCreateInfo = new SP.ListItemCreationInformation(); + itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder); + itemCreateInfo.set_leafName("My new folder!"); + var oListItem = oList.addItem(itemCreateInfo); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the document library to see your new folder."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function updateFolder(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Shared Documents"); + + var oListItem = oList.getItemById(1); + oListItem.set_item("FileLeafRef", "My updated folder"); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the document library to see your updated folder."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function deleteFolder(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Shared Documents"); + + var oListItem = oList.getItemById(1); + oListItem.deleteObject(); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the document library to make sure the folder is no longer there."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// List item tasks +function readItems(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + var camlQuery = new SP.CamlQuery(); + camlQuery.set_viewXml( + '' + + '1' + + '10' + ); + var collListItem = oList.getItems(camlQuery); + + clientContext.load(collListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + var listItemEnumerator = collListItem.getEnumerator(); + + var listItemInfo = ""; + while (listItemEnumerator.moveNext()) { + var oListItem = listItemEnumerator.get_current(); + listItemInfo += "ID: " + oListItem.get_id() + "
        " + + "Title: " + oListItem.get_item("Title") + "
        " + + "Body: " + oListItem.get_item("Body") + "
        "; + } + + resultpanel.innerHTML = listItemInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function readInclude(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + var camlQuery = new SP.CamlQuery(); + camlQuery.set_viewXml('100'); + + var collListItem = oList.getItems(camlQuery); + + clientContext.load(collListItem, "Include(Id, DisplayName, HasUniqueRoleAssignments)"); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + var listItemEnumerator = collListItem.getEnumerator(); + + var listItemInfo = ""; + while (listItemEnumerator.moveNext()) { + var oListItem = listItemEnumerator.get_current(); + listItemInfo += "ID: " + oListItem.get_id() + "
        " + + "Display name: " + oListItem.get_displayName() + "
        " + + "Unique role assignments: " + oListItem.get_hasUniqueRoleAssignments() + "
        "; + } + + resultpanel.innerHTML = listItemInfo; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +// Create, update and delete list items +function createListItem(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + + var itemCreateInfo = new SP.ListItemCreationInformation(); + var oListItem = oList.addItem(itemCreateInfo); + oListItem.set_item("Title", "My New Item!"); + oListItem.set_item("Body", "Hello World!"); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list to see your new item."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function updateListItem(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + + var oListItem = oList.getItemById(1); + oListItem.set_item("Title", "My updated title"); + oListItem.update(); + + clientContext.load(oListItem); + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list to see your updated item."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + +function deleteListItem(resultpanel: HTMLElement) { + var clientContext = SP.ClientContext.get_current(); + var oWebsite = clientContext.get_web(); + var oList = oWebsite.get_lists().getByTitle("Announcements"); + + var oListItem = oList.getItemById(1); + oListItem.deleteObject(); + + clientContext.executeQueryAsync( + successHandler, + errorHandler + ); + + function successHandler() { + resultpanel.innerHTML = "Go to the list to make sure the item is no longer there."; + } + + function errorHandler() { + resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); + } +} + + + +/** Lightweight client-side rendering template overrides.*/ +module CSR { + + export interface UpdatedValueCallback { + (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; + } + + /** Creates new overrides. Call .register() at the end.*/ + export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { + return new csr(listTemplateType, baseViewId) + .onPreRender(hookFormContext) + .onPostRender(fixCsrCustomLayout); + + function hookFormContext(ctx: IFormRenderContexWithHook) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + + for (var i = 0; i < ctx.ListSchema.Field.length; i++) { + var fieldSchemaInForm = ctx.ListSchema.Field[i]; + + if (!ctx.FormContextHook) { + ctx.FormContextHook = {} + + var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; + ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { + ctx.FormContextHook[fieldName].getValue = callback; + oldRegisterGetValueCallback(fieldName, callback); + }; + + var oldUpdateControlValue = ctx.FormContext.updateControlValue; + ctx.FormContext.updateControlValue = (fieldName: string, value: any) => { + oldUpdateControlValue(fieldName, value); + + var hookedContext = ensureFormContextHookField(ctx.FormContextHook, fieldName); + hookedContext.lastValue = value; + + var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; + for (var i = 0; i < updatedCallbacks.length; i++) { + updatedCallbacks[i](value, hookedContext.fieldSchema); + } + + } + } + ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; + } + } + } + + function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + return; + } + + if (ctx.ListSchema.Field.length > 1) { + var wpq = ctx.FormUniqueId; + var webpart = $get('WebPart' + wpq); + var forms = webpart.getElementsByClassName('ms-formtable'); + + if (forms.length > 0) { + var placeholder = $get(wpq + 'ClientFormTopContainer'); + var fragment = document.createDocumentFragment(); + for (var i = 0; i < placeholder.children.length; i++) { + fragment.appendChild(placeholder.children.item(i)); + } + + var form = forms.item(0); + form.parentNode.replaceChild(fragment, form); + } + + var old = ctx.CurrentItem; + ctx.CurrentItem = ctx.ListData.Items[0]; + var fields = ctx.ListSchema.Field; + for (var j = 0; j < fields.length; j++) { + var field = fields[j]; + var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; + var span = $get(pHolderId); + if (span) { + span.outerHTML = ctx.RenderFieldByName(ctx, field.Name); + } + } + ctx.CurrentItem = old; + } + + } + + + } + + +//typescripttempltes.ts + declare var Strings:any; + export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName] + && contextWithHook.FormContextHook[fieldName].getValue) { + return contextWithHook.FormContextHook[fieldName].getValue(); + } + } + return null; + } + + export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName]) { + return contextWithHook.FormContextHook[fieldName].fieldSchema; + } + } + return null; + } + + export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); + var callbacks = f.updatedValueCallbacks; + if (callbacks.indexOf(callback) == -1) { + callbacks.push(callback); + if (f.lastValue) { + callback(f.lastValue, f.fieldSchema); + } + } + } + } + + } + + export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; + var index = callbacks.indexOf(callback); + if (index != -1) { + callbacks.splice(index, 1); + } + } + } + } + + export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { + var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; + //TODO: Handle different input types + return $get(id); + } + + export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { + var ctx = { ListSchema: { Field: [field] }, FieldControlModes: {} }; + ctx.FieldControlModes[field.Name] = mode; + var templates = SPClientTemplates.TemplateManager.GetTemplates(ctx); + return templates.Fields[field.Name]; + } + + + class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { + + public Templates: SPClientTemplates.TemplateOverrides; + public OnPreRender: SPClientTemplates.RenderCallback[]; + public OnPostRender: SPClientTemplates.RenderCallback[]; + private IsRegistered: boolean; + + + constructor(public ListTemplateType?: number, public BaseViewID?: any) { + this.Templates = { Fields: {} }; + this.OnPreRender = [] ; + this.OnPostRender = []; + this.IsRegistered = false; + } + + /* tier 1 methods */ + view(template: any): ICSR { + this.Templates.View = template; + return this; + } + + item(template: any): ICSR { + this.Templates.Item = template; + return this; + } + + header(template: any): ICSR { + this.Templates.Header = template; + return this; + } + + body(template: any): ICSR { + this.Templates.Body = template; + return this; + } + + footer(template: any): ICSR { + this.Templates.Footer = template; + return this; + } + + fieldView(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].View = template; + return this; + } + + fieldDisplay(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].DisplayForm = template; + return this; + } + + fieldNew(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].NewForm = template; + return this; + } + + fieldEdit(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].EditForm = template; + return this; + } + + /* tier 2 methods */ + template(name: string, template: any): ICSR { + this.Templates[name] = template; + return this; + } + + fieldTemplate(fieldName: string, name: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName][name] = template; + return this; + } + + /* common */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPreRender.push(callbacks[i]); + } + return this; + } + + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPostRender.push(callbacks[i]); + } + return this; + } + + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + makeReadOnly(fieldName: string): ICSR { + return this + .onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; + (schema).ReadOnlyField = true; + (schema).ReadOnly = "TRUE"; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + if (ctxInView.inGridMode) { + //TODO: Disable editing in grid mode + + } + + } else { + var ctxInForm = ctx; + if (schema.Type != 'User' && schema.Type != 'UserMulti') { + + var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); + ctxInForm.Templates.Fields[fieldName] = template; + ctxInForm.FormContext.registerGetValueCallback(fieldName, () => ctxInForm.ListData.Items[0][fieldName]); + + } + } + + }) + .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + if (schema.Type == 'User' || schema.Type == 'UserMulti') { + SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { + var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; + var retryCount = 10; + var callback = () => { + var pp = SPClientPeoplePicker.SPClientPeoplePickerDict[topSpanId]; + if (!pp) { + if (retryCount--) setTimeout(callback, 1); + } else { + pp.SetEnabledState(false); + pp.DeleteProcessedUser = function () { }; + } + }; + callback(); + }); + } + } + }); + } + + makeHidden(fieldName: string): ICSR { + return this.onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; + (schema).Hidden = true; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + + if (ctxInView.inGridMode) { + //TODO: Hide item in grid mode + } else { + ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); + } + + } else { + var ctxInForm = ctx; + + var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; + var placeholder = $get(pHolderId); + var current = placeholder; + while (current.tagName.toUpperCase() !== "TR") { + current = current.parentElement; + } + var row = current; + row.style.display = 'none'; + + } + + }); + } + + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { + + + return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) + .fieldNew(fieldName, SPFieldCascadedLookup_Edit); + + + function SPFieldCascadedLookup_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + + var parseRegex = /\{[^\}]+\}/g; + var dependencyExpressions: string[] = []; + var result: RegExpExecArray; + while ((result = parseRegex.exec(camlFilter))) { + dependencyExpressions.push(stripBraces(result[0])); + } + var dependencyValues: { [expr: string]: string } = {}; + + var _dropdownElt: HTMLSelectElement; + var _myData: SPClientTemplates.ClientFormContext; + + + if (rCtx == null) + return ''; + _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + + var _schema = _myData.fieldSchema; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); + + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; + var _noValueSelected = _selectedValue == 0; + var _optionsLoaded = false; + var pendingLoads = 0; + + if (_noValueSelected) + _valueStr = ''; + + _myData.registerInitCallback(_myData.fieldName, InitLookupControl); + + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_dropdownElt != null) + _dropdownElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); + _myData.updateControlValue(_myData.fieldName, _valueStr); + + return BuildLookupDropdownControl(); + + function InitLookupControl() { + _dropdownElt = document.getElementById(_dropdownId); + if (_dropdownElt != null) + AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); + + SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => { + bindDependentControls(dependencyExpressions); + loadOptions(true); + }); + } + + + function BuildLookupDropdownControl() { + var result = ''; + result += '
        '; + return result; + } + + + function OnLookupValueChanged() { + if (_optionsLoaded) { + if (_dropdownElt != null) { + _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + _selectedValue = parseInt(_dropdownElt.value, 10); + } + } + } + + function GetCurrentLookupValue() { + if (_dropdownElt == null) + return ''; + return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + _dropdownElt.options[_dropdownElt.selectedIndex].text; + } + + function stripBraces(input: string): string { + return input.substring(1, input.length - 1); + } + + function getDependencyValue(expr: string, value: string, listId: string, expressionParts: string[], callback: () => void) { + var isLookupValue = !!listId; + if (isLookupValue) { + var lookup = SPClientTemplates.Utility.ParseLookupValue(value); + if (expressionParts.length == 1 && expressionParts[0] == 'Value') { + value = lookup.LookupValue; + expressionParts.shift(); + } else { + value = lookup.LookupId.toString(); + } + } + + if (expressionParts.length == 0) { + dependencyValues[expr] = value; + callback(); + } else { + var ctx = SP.ClientContext.get_current(); + var web = ctx.get_web(); + //TODO: Handle lookup to another web + var list = web.get_lists().getById(listId); + var item = list.getItemById(parseInt(value, 10)); + var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); + ctx.load(item); + ctx.load(field); + + ctx.executeQueryAsync((o, e) => { + var value = item.get_item(field.get_internalName()); + + if (field.get_typeAsString() == 'Lookup') { + field = ctx.castTo(field, SP.FieldLookup); + var lookup = (value); + value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); + listId = (field).get_lookupList(); + } + + getDependencyValue(expr, value, listId, expressionParts, callback); + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + function bindDependentControls(dependencyExpressions: string[]) { + dependencyExpressions.forEach(expr => { + var exprParts = expr.split("."); + var field = exprParts.shift(); + + CSR.addUpdatedValueCallback(rCtx, field, + (v, s) => { + getDependencyValue(expr, v, + (s).LookupListId, + exprParts.slice(0), + loadOptions); + }); + + }); + } + + + function loadOptions(isFirstLoad?: boolean) { + _optionsLoaded = false; + pendingLoads++; + + var ctx = SP.ClientContext.get_current(); + //TODO: Handle lookup to another web + var web = ctx.get_web(); + var listId = _schema.LookupListId; + var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); + var query = new SP.CamlQuery(); + + var predicate = camlFilter.replace(parseRegex, (v, a) => { + var expr = stripBraces(v); + return dependencyValues[expr] ? dependencyValues[expr] : ''; + }); + + //TODO: Handle ShowField attribure + if (predicate.substr(0, 5) == '' + + predicate + + ' ' + + ''); + } + var results = list.getItems(query); + ctx.load(results); + + + ctx.executeQueryAsync((o, e) => { + var selected = false; + + while (_dropdownElt.options.length) { + _dropdownElt.options.remove(0); + } + + if (!_schema.Required) { + var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); + _dropdownElt.options.add(defaultOpt); + selected = _selectedValue == 0; + } + var isEmptyList = true; + + var enumerator = results.getEnumerator(); + while (enumerator.moveNext()) { + var c = enumerator.get_current(); + var id: number; + var text: string; + + if (!lookupField) { + id = c.get_id(); + text = c.get_item('Title'); + } else { + var value = c.get_item(lookupField); + id = value.get_lookupId(); + text = value.get_lookupValue(); + } + var isSelected = _selectedValue == id; + if (isSelected) { + selected = true; + } + var opt = new Option(text, id.toString(), isSelected, isSelected); + _dropdownElt.options.add(opt); + isEmptyList = false; + } + pendingLoads--; + _optionsLoaded = true; + if (!pendingLoads) { + if (isFirstLoad) { + if (_selectedValue == 0 && !selected) { + _dropdownElt.selectedIndex = 0; + OnLookupValueChanged(); + } + } else { + if (_selectedValue != 0 && !selected) { + _dropdownElt.selectedIndex = 0; + } + OnLookupValueChanged(); + } + } + + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + } + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { + return this.fieldEdit(fieldName, koEditField_Edit) + .fieldNew(fieldName, koEditField_Edit); + + + function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + var elementId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type; + + vm.renderingContext = rCtx; + + + if (dependencyFields) { + dependencyFields.forEach(dependencyField => { + if (!vm[dependencyField]) { + vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); + } + CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { + vm[dependencyField](v); + }); + }); + } + + + if (!vm.value) { + vm.value = ko.observable(); + } + + vm.value.subscribe(v => { _myData.updateControlValue(fieldName, v); }); + _myData.registerGetValueCallback(fieldName, () => vm.value()); + + + _myData.registerInitCallback(fieldName, () => { + ko.applyBindings(vm, $get(elementId)); + }); + + return '
        '+template+'
        '; + } + } + + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { + var dependentValues: { [field: string]: string } = {}; + + return this.onPostRenderField(targetField, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var targetControl = CSR.getControl(schema); + sourceField.forEach((field) => { + CSR.addUpdatedValueCallback(ctx, field, v => { + dependentValues[field] = v; + targetControl.value = transform.apply(this, + sourceField.map(n => dependentValues[n] || '')); + + }); + }); + } + }); + } + + setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { + if (value || !ignoreNull) { + return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + ctx.ListData.Items[0][fieldName] = value; + }); + } else { + return this; + } + } + + + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { + return this + .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) + .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); + + function SPFieldLookup_Autofill_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + var _autoFillControl: SPClientAutoFill; + var _textInputElt: HTMLInputElement; + var _textInputId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type + 'Field'; + var _autofillContainerId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$AutoFill'; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_textInputElt != null) + _textInputElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); + _myData.updateControlValue(_myData.fieldName, _myData.fieldValue); + + return buildAutoFillControl(); + + function initAutoFillControl() { + _textInputElt = document.getElementById(_textInputId); + + SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { + _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); + var callback = init({ + renderContext: rCtx, + fieldContext: _myData, + autofill: _autoFillControl, + control: _textInputElt, + }); + + //_autoFillControl.AutoFillMinTextLength = 2; + //_autoFillControl.VisibleItemCount = 15; + //_autoFillControl.AutoFillTimeout = 500; + }); + + } + //function OnPopulate(targetElement: HTMLInputElement) { + + //} + + //function OnLookupValueChanged() { + // _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + //} + //function GetCurrentLookupValue() { + // return _valueStr; + //} + function buildAutoFillControl() { + var result: string[] = []; + result.push('
        '); + result.push(''); + + result.push("
        "); + result.push("
        "); + + return result.join(""); + } + } + + + } + + seachLookup(fieldName: string): ICSR { + return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { + var _myData = ctx.fieldContext; + var _schema = _myData.fieldSchema; + if (_myData.fieldSchema.Type != 'Lookup') { + return null; + } + + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); + var _noValueSelected = _selectedValue.LookupId == 0; + ctx.control.value = _selectedValue.LookupValue; + $addHandler(ctx.control, "blur", _ => { + if (ctx.control.value == '') { + _myData.fieldValue = ''; + _myData.updateControlValue(fieldName, _myData.fieldValue); + } + }); + + if (_noValueSelected) + _myData.fieldValue = ''; + + var _autoFillControl = ctx.autofill; + _autoFillControl.AutoFillMinTextLength = 2; + _autoFillControl.VisibleItemCount = 15; + _autoFillControl.AutoFillTimeout = 500; + + return () => { + var value = ctx.control.value; + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildLoadingItem('Please wait...')], onSelectItem); + + SP.SOD.executeFunc("sp.search.js", "Microsoft.SharePoint.Client.Search.Query", () => { + var Search = Microsoft.SharePoint.Client.Search.Query; + var ctx = SP.ClientContext.get_current(); + var query = new Search.KeywordQuery(ctx); + query.set_rowLimit(_autoFillControl.VisibleItemCount); + query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); + var selectProps = query.get_selectProperties(); + selectProps.clear(); + //TODO: Handle ShowField attribute + selectProps.add('Title'); + selectProps.add('ListItemId'); + var executor = new Search.SearchExecutor(ctx); + var result = executor.executeQuery(query); + ctx.executeQueryAsync( + () => { + //TODO: Discover proper way to load collection + var tableCollection = new Search.ResultTableCollection(); + tableCollection.initPropertiesFromJson(result.get_value()); + + var relevantResults = tableCollection.get_item(0); + var rows = relevantResults.get_resultRows(); + + var items = []; + for (var i = 0; i < rows.length; i++) { + items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); + } + + items.push(AutoFillOptionBuilder.buildSeparatorItem()); + + if (relevantResults.get_totalRows() == 0) + items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); + else + items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); + + _autoFillControl.PopulateAutoFill(items, onSelectItem); + + }, + (sender, args) => { + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildFooterItem("Error executing query/ See log for details.")], onSelectItem); + console.log(args.get_message()); + }); + }); + } + + function onSelectItem(targetInputId, item: ISPClientAutoFillData) { + var targetElement = ctx.control; + targetElement.value = item[SPClientAutoFill.DisplayTextProperty]; + _selectedValue.LookupId = item[SPClientAutoFill.KeyProperty]; + _selectedValue.LookupValue = item[SPClientAutoFill.DisplayTextProperty]; + _myData.fieldValue = item[SPClientAutoFill.KeyProperty] + ';#' + item[SPClientAutoFill.TitleTextProperty]; + _myData.updateControlValue(_myData.fieldSchema.Name, _myData.fieldValue); + } + + }); + } + + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { + return this.onPostRenderField(fieldName, + (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) + + var control = CSR.getControl(schema); + if (control) { + var weburl = _spPageContextInfo.webServerRelativeUrl; + if (weburl[weburl.length - 1] == '/') { + weburl = weburl.substring(0, weburl.length - 1); + } + var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' + + "&ListId=" + encodeURIComponent('{' + schema.LookupListId + '}'); + if (contentTypeId) { + newFormUrl += '&ContentTypeId=' + contentTypeId; + } + + var link = document.createElement('a'); + link.href = "javascript:NewItem2(event, \'" + newFormUrl + "&Source=" + encodeURIComponent(document.location.href) + "')"; + link.textContent = prompt; + if (control.nextElementSibling) { + control.parentElement.insertBefore(link, control.nextElementSibling); + } else { + control.parentElement.appendChild(link); + } + + if (showDialog) { + $addHandler(link, "click", (e: Sys.UI.DomEvent) => { + SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.ShowPopupDialog', () => { + SP.UI.ModalDialog.ShowPopupDialog(newFormUrl); + }); + e.stopPropagation(); + e.preventDefault(); + }); + } + } + }); + } + + register() { + if (!this.IsRegistered) { + SPClientTemplates.TemplateManager.RegisterTemplateOverrides(this); + this.IsRegistered = true; + } + } + } + + export class AutoFillOptionBuilder { + + static buildFooterItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.DisplayTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer; + + return item; + } + + static buildOptionItem(id: number, title: string, displayText?: string, subDisplayText?: string): ISPClientAutoFillData { + + var item = {}; + + item[SPClientAutoFill.KeyProperty] = id; + item[SPClientAutoFill.DisplayTextProperty] = displayText || title; + item[SPClientAutoFill.SubDisplayTextProperty] = subDisplayText; + item[SPClientAutoFill.TitleTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option; + + return item; + } + + static buildSeparatorItem(): ISPClientAutoFillData { + var item = {}; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator; + return item; + } + + static buildLoadingItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Loading; + item[SPClientAutoFill.DisplayTextProperty] = title; + return item; + } + + } + + /** Lightweight client-side rendering template overrides.*/ + export interface ICSR { + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: string): ICSR; + + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Sets pre-render callbacks. Callback called before rendering starts. + @param callbacks pre-render callbacks. + */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. + @param callbacks post-render callbacks. + */ + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks pre-render callbacks. + */ + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks post-render callbacks. + */ + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Registers overrides in client-side templating engine.*/ + register(): void; + + /** Override View rendering template. + @param template New view template. + */ + view(template: string): ICSR; + + /** Override View rendering template. + @param template New view template. + */ + view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; + view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; + item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; + + /** Override DisplyForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: string): ICSR; + + /** Override DisplyForm rendering template. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override EditForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: string): ICSR; + + /** Override EditForm rendering template. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override NewForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: string): ICSR; + + /** Override NewForm rendering template. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + + /** Set initial value for field. + @param fieldName Internal name of the field. + @param value Initial value for field. + */ + setInitialValue(fieldName: string, value: any): ICSR; + + /** Make field hidden in list view and standard forms. + @param fieldName Internal name of the field. + */ + makeHidden(fieldName: string): ICSR + + + /** Replace New and Edit templates for field to Display template. + @param fieldName Internal name of the field. + */ + makeReadOnly(fieldName: string): ICSR + + /** Create cascaded Lookup Field. + @param fieldName Internal name of the field. + @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. + */ + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR + + /** Auto computes text-based field value based on another fields. + @param targetField Internal name of the field. + @param transform Function combines source field values. + @param sourceField Internal names of source fields. + */ + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR + + /** Field text value with autocomplete based on autofill.js + @param fieldName Internal name of the field. + @param ctx AutoFill context. + */ + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR + + /** Replace defult dropdown to search-based autocomplete for Lookup field. + @param fieldName Internal name of the field. + */ + seachLookup(fieldName: string): ICSR; + + /** Adds link to add new value to lookup list. + @param fieldName Internal name of the field. + @param prompt Text to display as a link to add new value. + @param contentTypeID Default content type for new item. + */ + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; + + + } + + export interface IAutoFillFieldContext { + renderContext: SPClientTemplates.RenderContext_FieldInForm; + fieldContext: SPClientTemplates.ClientFormContext; + autofill: SPClientAutoFill; + control: HTMLInputElement; + } + + export interface IKoFieldInForm { + renderingContext?:SPClientTemplates.RenderContext_FieldInForm; + value?:KnockoutObservable; + } + + + interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { + FormContextHook: IFormContextHook; + } + + interface IFormContextHook { + [fieldName: string]: IFormContextHookField; + } + + interface IFormContextHookField { + fieldSchema?: SPClientTemplates.FieldSchema_InForm; + lastValue?: any; + getValue?: () => any; + updatedValueCallbacks: UpdatedValueCallback[]; + } + + + function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { + return hook[fieldName] = hook[fieldName] || { + updatedValueCallbacks: [] + }; + + } + + class BooleanValueValidator implements SPClientForms.ClientValidation.IValidator { + constructor(public valueGetter: () => boolean, public validationMessage: string) { } + + Validate(value: any): SPClientForms.ClientValidation.ValidationResult { + return new SPClientForms.ClientValidation.ValidationResult(!this.valueGetter(), this.validationMessage); + } + } + +} + +if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); +} + + +//mquery.ts + + + + +module spdevlab { + export module mQuery { + export class DynamicTable { + + // private fields + _domContainer:HTMLElement; + _tableContainer:MQueryResultSetElements; + + _rowTemplateId:string = null; + _rowTemplateContent:string = null; + + _options = { + tableCnt: '.spdev-rep-tb', + addCnt: '.spdev-rep-tb-add', + removeCnt: '.spdev-rep-tb-del' + }; + + // public methods + init(domContainer: HTMLElement, options) { + + if (m$.isDefinedAndNotNull(options)) { + m$.extend(this._options, options); + } + + this._initContainers(domContainer); + + this._initRowTemplate(); + this._initEvents(); + this._showUI(); + } + + // private methods + _initContainers(domContainer) { + + this._domContainer = domContainer; + this._tableContainer = m$(this._options.tableCnt, this._domContainer); + } + + _showUI() { + m$(this._domContainer).css("display", ""); + } + + _initEvents() { + + m$(this._options.addCnt, this._domContainer).click(() => { + + if (m$.isDefinedAndNotNull(this._rowTemplateContent)) { + + m$(this._tableContainer).append(this._rowTemplateContent); + + m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { + + var targetElement = e.currentTarget; + var parentRow = m$(targetElement).parents("tr").first(); + + m$(parentRow).remove(); + }); + } + + return false; + }); + } + + _initRowTemplate() { + var templateId = m$(this._tableContainer).attr("template-id"); + + if (m$.isDefinedAndNotNull(templateId)) { + this._rowTemplateId = templateId; + this._rowTemplateContent = DynamicTable._templates[templateId]; + } + } + + static _templates:string[] = []; + static initTables() { + // init templates + m$('script').forEach((template:HTMLElement) => { + + var id = m$(template).attr("dynamic-table-template-id"); + + if (m$.isDefinedAndNotNull(id)) { + DynamicTable._templates[id] = template.innerHTML; + } + }); + + // init tables + m$(".spdev-rep-tb-cnt").forEach( divContainer => { + + var dynamicTable = new DynamicTable(); + + dynamicTable.init(divContainer, { + removeCnt: '.spdev-rep-tb-del-override' + }); + }); + } + + }; + + + } +} + +m$.ready(() => { + spdevlab.mQuery.DynamicTable.initTables(); +}); + + +//whoisapppart.ts + + +module _ { + var queryString = parseQueryString(); + var isIframe = queryString['DisplayMode'] == 'iframe' + var spHostUrl = queryString['SPHostUrl']; + var editmode = Number(queryString['editmode']); + var includeDetails = queryString['boolProp'] == 'true'; + + prepareVisual(); + m$.ready(() => { + loadPeoplePicker('peoplePicker'); + partProperties(); + + if (isIframe) { + partResize(); + } + }); + + //Load the people picker + function loadPeoplePicker(peoplePickerElementId: string) { + var schema: ISPClientPeoplePickerSchema = { + PrincipalAccountType: "User", + AllowMultipleValues: false, + Width: 300, + OnUserResolvedClientScript: onUserResolvedClientScript + } + + SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); + } + + function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { + if (users.length > 0) { + var person = users[0]; + var accountName = person.Key; + + var context = SP.ClientContext.get_current(); + + var peopleManager = new SP.UserProfiles.PeopleManager(context); + var personProperties = peopleManager.getPropertiesFor(accountName); + + context.load(personProperties); + context.executeQueryAsync((sender, args) => { + + $get("basicInfo").style.display = 'block'; + + var userPic = personProperties.get_userProfileProperties()["PictureURL"]; + $get("pic").innerHTML = ' + personProperties.get_displayName() + '; + + $get("name").innerHTML = '' + personProperties.get_displayName() + ''; + $get("email").innerHTML = '' + personProperties.get_email() + ''; + $get("title").innerHTML = personProperties.get_title(); + $get("department").innerHTML = person.EntityData.Department; + $get("phone").innerHTML = person.EntityData.MobilePhone; + + var properties = personProperties.get_userProfileProperties(); + var messageText = ""; + for (var key in properties) { + messageText += "
        [" + key + "]: \"" + properties[key] + "\""; + } + $get("detailInfo").innerHTML = messageText; + + if (isIframe) { + partResize(); + } + + }, (sender, args) => { alert('Error: ' + args.get_message()); }); + + } + } + + function partProperties() { + + if (editmode == 1) { + $get("editmodehdr").style.display = "inline"; + $get("content").style.display = "none"; + } + else if (includeDetails) { + $get('detailInfo').style.display = 'block'; + + $get("editmodehdr").style.display = "none"; + $get("content").style.display = "inline"; + } + } + + function partResize() { + var bounds = Sys.UI.DomElement.getBounds(document.body); + parent.postMessage('resize(' + bounds.width + ',' + bounds.height + ')', '*'); + } + + function prepareVisual() { + if (isIframe) { + //Create a Link element for the defaultcss.ashx resource + var linkElement = document.createElement('link'); + linkElement.setAttribute('rel', 'stylesheet'); + linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); + + //Add the linkElement as a child to the head section of the html + document.head.appendChild(linkElement); + } else { + + m$.ready(() => { + var nav = new SP.UI.Controls.Navigation('navigation', { + appIconUrl: queryString['SPHostLogo'], + appTitle: document.title + }); + nav.setVisible(true); + $get('apppart-notification').style.display = 'block'; + document.body.style.overflow = 'visible'; + }); + } + } + + function parseQueryString() { + var result = {}; + var qs = document.location.search.split('?')[1]; + if (qs) { + var parts = qs.split('&'); + for (var i = 0; i < parts.length; i++) { + if (parts[i]) { + var pair = parts[i].split('='); + result[pair[0]] = decodeURIComponent(pair[1]); + } + } + } + return result; + } +} + +//taxonomy +module SP { + + // Class + export class ClientContextPromise extends SP.ClientContext { + /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ + executeQueryPromise(): JQueryPromise { + var deferred = jQuery.Deferred(); + this.executeQueryAsync(function (sender, args) { + deferred.resolve(sender, args); + }, + function (sender, args) { + deferred.reject(sender, args); + }) + return deferred.promise(); + } + + constructor(serverRelativeUrlOrFullUrl: string) { + super(serverRelativeUrlOrFullUrl); + } + + static get_current(): ClientContextPromise { + return new ClientContextPromise(_spPageContextInfo.siteServerRelativeUrl); + } + + } + +} + +SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); + +module _ { + var context: SP.ClientContextPromise; + var web: SP.Web; + var site: SP.Site; + var session: SP.Taxonomy.TaxonomySession; + var termStore: SP.Taxonomy.TermStore; + var groups: SP.Taxonomy.TermGroupCollection; + + // This code runs when the DOM is ready and creates a context object + // which is needed to use the SharePoint object model. + // It also wires up the click handlers for the two HTML buttons in Default.aspx. + $(document).ready(function () { + context = SP.ClientContextPromise.get_current(); + site = context.get_site(); + web = context.get_web(); + $('#listExisting').click(function () { listGroups(); }); + $('#createTerms').click(function () { createTerms(); }); + }); + + // When the listExisting button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function listGroups() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onListTaxonomySession, onFailListTaxonomySession); + } + + // Runs when the executeQueryAsync method in the listGroups function has succeeded. + // In this case, get and load the groups associated with the term store that we + // know we now have a reference to. + function onListTaxonomySession() { + groups = termStore.get_groups(); + context.load(groups); + context.executeQueryAsync(onRetrieveGroups, onFailRetrieveGroups); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has succeeded. + // In this case, loop through all the groups and add a clickable div element to the report area + // for each group. + // NOTE: We clear the report area first to ensure we have a clean place to write to. + // Also note how we create a click event handler for each div on-the-fly, and that we pass in the + // current group ID to that function. So when the user clicks one of these divs, we will know which + // one was clicked. + function onRetrieveGroups() { + $('#report').children().remove(); + + var groupEnum = groups.getEnumerator(); + + // For each group, we'll build a clickable div. + while (groupEnum.moveNext()) { + (() => { + var currentGroup = groupEnum.get_current(); + var groupName = document.createElement("div"); + groupName.setAttribute("style", "float:none;cursor:pointer"); + var groupID = currentGroup.get_id(); + groupName.setAttribute("id", groupID.toString()); + $(groupName).click(() => showTermSets(groupID)); + groupName.appendChild(document.createTextNode(currentGroup.get_name())); + $('#report').append(groupName); + })(); + } + } + + // This is the function that runs when the user clicks one of the divs + // that we created in the onRetrieveGroups function. We can know which + // div was clicked by interrogating the groupID parameter. So what we'll + // do is retrieve a reference to the group with the same ID as the div, and + // then add the term sets that belong to that group under the div that was clicked. + function showTermSets(groupID: SP.Guid) { + + // First thing is to remnove the divs under the group DIV to ensure we have a clean place to write to. + // The reason we don't clear them all is becuase we want to retain the text node of the + // group div. I.E. that's why we use "parentDiv.childNodes.length>1" as our loop + // controller. + var parentDiv = document.getElementById(groupID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // For each term set, we'll build a clickable div + var currentGroup = groups.getById(groupID); + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + context.load(currentGroup); + var termSets: SP.Taxonomy.TermSetCollection; + context.executeQueryPromise() + .then( + () => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise() + }) + .then(() => { + // The term sets are now available becuase this is the + // success callback. So now we'll iterate through the collection + // and create the clickable div. Also note how we create a + // click event handler for each div on-the-fly, and that we pass in the + // current group ID and term set ID to that function. So when the user + // clicks one of these divs, we will know which + // one was clicked by its term set ID, and to which group it belongs by its + // group ID. We also pass in the event object, so that we can cancel the bubble + // because this clickable div will be inside a parent clickable div and we + // don't want the parent's event to fire. + var termSetEnum = termSets.getEnumerator(); + while (termSetEnum.moveNext()) { + (() => { + var currentTermSet = termSetEnum.get_current(); + var termSetName = document.createElement("div"); + termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); + termSetName.setAttribute("style", "float:none;cursor:pointer;"); + var termSetID = currentTermSet.get_id(); + termSetName.setAttribute("id", termSetID.toString()); + $(termSetName).click(e => showTerms(e, groupID, termSetID)); + parentDiv.appendChild(termSetName); + })(); + } + + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); + } + + + // This is the function that runs when the user clicks one of the divs + // that we created in the showTermSets function. We can know which + // div was clicked by interrogating the termSetID parameter. So what we'll + // do is retrieve a reference to the term set with the same ID as the div, and + // then add the term that belong to that term set under the div that was clicked. + + function showTerms(event: JQueryEventObject, groupID: SP.Guid, termSetID: SP.Guid) { + + // First, cancel the bubble so that the group div click handler does not also fire + // because that removes all term set divs and we don't want that here. + event.cancelBubble = true; + + // Get a reference to the term set div that was click and + // remove its children (apart from the TextNode that is currently + // showing the term set name. + var parentDiv = document.getElementById(termSetID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + var currentGroup = groups.getById(groupID); + var termSets:SP.Taxonomy.TermSetCollection; + var currentTermSet:SP.Taxonomy.TermSet; + var terms:SP.Taxonomy.TermCollection; + + context.load(currentGroup); + context + .executeQueryPromise() + .then(() => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise(); + }) + .then(() => { + currentTermSet = termSets.getById(termSetID); + context.load(currentTermSet); + return context.executeQueryPromise(); + }) + .then(() => { + terms = currentTermSet.get_terms(); + context.load(terms); + return context.executeQueryPromise(); + }) + .then(() => { + var termsEnum = terms.getEnumerator(); + while (termsEnum.moveNext()) { + var currentTerm = termsEnum.get_current(); + + var term = document.createElement("div"); + term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); + term.setAttribute("style", "float:none;margin-left:10px;"); + parentDiv.appendChild(term); + } + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailRetrieveGroups(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to retrieve groups. Error:" + args.get_message()); + } + + // Runs when the executeQueryAsync method in the listGroups function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailListTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + + + // When the createTerms button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function createTerms() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onGetTaxonomySession, onFailTaxonomySession); + } + + + // This function is the success callback for loading the session and store from the createTerms function + function onGetTaxonomySession() { + // Create six GUIDs that we will need when we create a new group, term set, and associated terms + var guidGroupValue = SP.Guid.newGuid(); + var guidTermSetValue = SP.Guid.newGuid(); + var guidTerm1 = SP.Guid.newGuid(); + var guidTerm2 = SP.Guid.newGuid(); + var guidTerm3 = SP.Guid.newGuid(); + var guidTerm4 = SP.Guid.newGuid(); + + // Create a new group + var myGroup = termStore.createGroup("CustomTerms", guidGroupValue); + + // Create a new term set in the newly-created group + var myTermSet = myGroup.createTermSet("Privacy", guidTermSetValue, 1033); + + // Create four new terms in the newly-created term set + myTermSet.createTerm("Top Secret", 1033, guidTerm1); + myTermSet.createTerm("Company Confidential", 1033, guidTerm2); + myTermSet.createTerm("Partners Only", 1033, guidTerm3); + myTermSet.createTerm("Public", 1033, guidTerm4); + + // Ensure the groups variable has been set, because when this all succeeds we will + // effectively run the same code as if the user had clicked the listGroups button + groups = termStore.get_groups(); + context.load(groups); + + // Execute all the preceeding statements in this function + context.executeQueryAsync(onAddTerms, onFailAddTerms); + + } + + // If all is well with creating the terms, then this function will run. + // Effectively this runs the same code as if the user had clicked the listGroups button + // so the user will see their newly-created group + function onAddTerms() { + listGroups(); + } + + // Runs when the executeQueryAsync method in the onGetTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailAddTerms(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to add terms. Error: " + args.get_message()); + } + + // Runs when the executeQueryAsync method in the createTerms function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + +}; + +//publishing.ts +// Variables used in various callbacks +JSRequest.EnsureSetup(); + +SP.SOD.execute('mquery.js', 'm$.ready', () => { + var context = SP.ClientContext.get_current(); + var web = context.get_web(); + m$('#CreatePage').click(createPage); +}); + +function createPage(evt) { + SP.SOD.execute('sp.js', 'SP.ClientConext', () => { + SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { + var context = SP.ClientContext.get_current(); + + + var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); + var hostcontext = new SP.AppContextSite(context, hostUrl); + var web = hostcontext.get_web(); + var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); + context.load(web); + context.load(pubWeb); + context.executeQueryAsync( + // Success callback after getting the host Web as a PublishingWeb. + // We now want to add a new Publishing Page. + function () { + var pageInfo = new SP.Publishing.PublishingPageInformation(); + var newPage = pubWeb.addPublishingPage(pageInfo); + context.load(newPage); + context.executeQueryAsync( + function () { + + // Success callback after adding a new Publishing Page. + // We want to get the actual list item that is represented by the Publishing Page. + var listItem = newPage.get_listItem(); + context.load(listItem); + context.executeQueryAsync( + + // Success callback after getting the actual list item that is + // represented by the Publishing Page. + // We can now get its FieldValues, one of which is its FileLeafRef value. + // We can then use that value to build the Url to the new page + // and set the href or our link to that Url. + function () { + var link = document.getElementById("linkToPage"); + link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); + link.innerText = "Go to new page!"; + }, + + // Failure callback after getting the actual list item that is + // represented by the Publishing Page. + function (sender, args) { + alert('Failed to get new page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to add a new Publishing Page. + function (sender, args) { + alert('Failed to Add Page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to get the host Web as a PublishingWeb. + function (sender, args) { + alert('Failed to get the PublishingWeb: ' + args.get_message()); + } + ); + }); + }); +} + +//likes +module SampleReputation { + + interface MyList extends SPClientTemplates.RenderContext_InView { + listId: string; + } + + class MyItem { + + id: number; + title: string; + likesCount: number; + isLikedByCurrentUser: boolean; + + constructor(public row: SPClientTemplates.Item) { + this.id = parseInt(row['ID']); + this.title = row['Title']; + this.likesCount = parseInt(row['LikesCount']) || 0; + this.isLikedByCurrentUser = this.getLike(row['LikedBy']); + } + + private getLike(likedBy): boolean { + if (likedBy && likedBy.length > 0) { + for (var i = 0; i < likedBy.length; i++) { + if (likedBy[i].id == _spPageContextInfo.userId) { + return true; + } + } + } + return false; + } + } + + function init() { + SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js'); + SP.SOD.registerSod('typescripttemplates.ts', '/SPTypeScript/Extensions/typescripttemplates.js'); + SP.SOD.executeFunc('typescripttemplates.ts', 'CSR', () => { + CSR.override(10004, 1) + .onPreRender((ctx: MyList) => { + ctx.listId = ctx.listName.substring(1, 37); + }) + .header('
          ') + .body(renderTemplate) + .footer('
        ') + .register(); + }); + + SP.SOD.execute('mQuery.js', 'm$.ready', () => { + RegisterModuleInit('/SPTypeScript/ReputationModule/likes.js', init); + }); + + + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('likes.js'); + } + + function renderTemplate(ctx: MyList) { + var rows = ctx.ListData.Row; + var result = ''; + for (var i = 0; i < rows.length; i++) { + var item = new MyItem(rows[i]); + result += '\ +
      • ' + item.title +'\ + \ + ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ + \ +
      • '; + } + return result; + } + + function getLikeText(isLikedByCurrentUser: boolean) { + return isLikedByCurrentUser ? '\u2665' : '\u2661'; + } + + export function setLike(itemId: number, listId: string): void { + var context = SP.ClientContext.get_current(); + var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; + SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { + Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); + context.executeQueryAsync( + () => { + m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); + var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); + m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); + }, + (sender, args) => { + alert(args.get_message()); + }); + }); + } + + init(); +} + + + +//code from https://github.com/gandjustas/SharePointAngularTS +module App { + "use strict"; +var app = angular.module("app", []); +} + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + interface Iappcontroller { + title: string; + activate: () => void; + } + + class appcontroller implements Iappcontroller { + title: string = "appcontroller"; + lists: SP.List[]; + + static $inject: string[] = ["$SharePoint", "$spnotify"]; + + constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { + this.activate(); + } + + activate() { + var loading = this.$n.showLoading(true) + this.$SharePoint + .getLists() + .then(l => this.lists = l ) + .catch((e: string) => this.$n.show(e, true)) + .finally(() => this.$n.remove(loading) ); + ; + + } + } + + angular.module("app").controller("appcontroller", appcontroller); +} + + + +module App { + "use strict"; + + export interface ISharePoint { + getLists: () => ng.IPromise; + } + + class SharePointServcie implements ISharePoint { + static $inject: string[] = ["$q"]; + + constructor(public $q: ng.IQService) { + } + + getLists() { + var promise = this.$q.defer(); + SP.SOD.executeFunc("sp.js", "SP.ClientContext", () => { + var ctx = SP.ClientContext.get_current(); + var hostUrl = decodeURIComponent(SP.ScriptHelpers.getDocumentQueryPairs()['SPHostUrl']); + var appCtx = new SP.AppContextSite(ctx, hostUrl); + var hostWeb = appCtx.get_web(); + var lists = hostWeb.get_lists(); + ctx.load(lists); + + ctx.executeQueryAsync(() => { + var result: SP.List[] = []; + for (var e = lists.getEnumerator(); e.moveNext();) { + result.push(e.get_current()); + } + promise.resolve(result); + }, + (o, args) => { promise.reject(args.get_message()); }); + }); + return promise.promise; + } + } + + angular.module("app").service("$SharePoint", SharePointServcie); +} + + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + export interface ISpNotify { + showLoading(sticky?: boolean) : string; + show(msg: string, sticky?: boolean): string; + remove(id: string):void; + } + + class SpNotify implements ISpNotify { + static $inject: string[] = []; + + + showLoading(sticky: boolean = false) { + return SP.UI.Notify.showLoadingNotification(sticky); + } + + show(msg: string, sticky: boolean = false) { + return SP.UI.Notify.addNotification(msg, sticky); + } + + remove(id: string) { + SP.UI.Notify.removeNotification(id); + } + } + + angular.module("app").service("$spnotify", SpNotify); +} + diff --git a/sharepoint/SharePoint-tests.ts.tscparams b/sharepoint/SharePoint-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/sharepoint/SharePoint-tests.ts.tscparams +++ b/sharepoint/SharePoint-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index e1a096084..ddc9cae0f 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -182,6 +182,7 @@ declare class _spPageContextInfo { } declare function STSHtmlEncode(value: string): string; +declare function STSHtmlDecode(value: string): string; declare function AddEvtHandler(element: HTMLElement, event: string, func: EventListener): void; diff --git a/siesta/siesta-tests.ts.tscparams b/siesta/siesta-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/siesta/siesta-tests.ts.tscparams +++ b/siesta/siesta-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/siesta/siesta.d.ts.tscparams b/siesta/siesta.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/siesta/siesta.d.ts.tscparams +++ b/siesta/siesta.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/signalr/signalr-tests.ts b/signalr/signalr-tests.ts index 3ef8cad87..5c79f8270 100644 --- a/signalr/signalr-tests.ts +++ b/signalr/signalr-tests.ts @@ -1,137 +1,137 @@ -/// - -function test_client() { - var connection = $.connection('/echo'); - connection.received(function (data) { - console.log(data); - }); - connection.error(function (error) { - console.warn(error); - }); - connection.stateChanged(function (change) { - if (change.newState === $.signalR.connectionState.reconnecting) { - console.log('Re-connecting'); - } - else if (change.newState === $.signalR.connectionState.connected) { - console.log('The server is online'); - } - }); - connection.reconnected(function () { - console.log('Reconnected'); - }); - connection.start(); - connection.start(function () { - console.log("connection started!"); - }); - connection.stop(); - connection.start().done(function () { - console.log("connection started!"); - }); - connection.start({ transport: 'longPolling' }); - connection.start({ transport: $.signalR.transports.webSockets }); - connection.start({ transport: ['longPolling', 'webSockets'] }); - connection.start({ waitForPageLoad: false }); - connection.start({ transport: 'longPolling' }, function () { - console.log('connection started!'); - }); - connection.send("Hello World"); - var connection = $.connection('http://localhost:8081/echo'); - connection.start({ jsonp: true }); -} - -function test_connection() { - var connection = $.connection('/echo'); - connection.received(function (data) { - $('#messages').append('
      • ' + data + '
      • '); - }); - connection.start(); - $("#broadcast").click(function () { - connection.send($('#msg').val()); - }); -} - -interface MyHubConnection extends HubConnection { - someState: string; - SomeFunction: Function; - - // My Hubs Client functions: - client: { - addMessage: (message: string) => void; - }; - // My Hubs Server function: - server: { - send(message: string): any; - }; -} - -interface SignalR { - chat: MyHubConnection; - myHub: MyHubConnection; -} - -function test_hubs() { - var chat = $.connection.chat; - $.connection.hub.start() - .done(function () { alert("Now connected!"); }) - .fail(function () { alert("Could not Connect!"); }); - - $.connection.hub.logging = true; - var myHub = $.connection.myHub; - myHub.someState = "SomeValue"; - function connectionReady() { - alert("Done calling first hub serverside-function"); - }; - myHub.SomeFunction = function () { - alert("serverside called 'Clients.SomeClientFunction()'"); - }; - $.connection.hub.error(function () { - alert("An error occured"); - }); - $.connection.hub.start() - .done(function () { - myHub.SomeFunction("whatever") - .done(connectionReady); - }) - .fail(function () { - alert("Could not Connect!"); - }); - - $.connection.hub.url = 'http://localhost:8081/signalr' - $.connection.hub.start(); - - var connection = $.hubConnection(); - var proxy = connection.createHubProxy('chat'); - var proxy = connection.createHubProxy('chat'), - msg = 'hello', - room = 'main'; - proxy.invoke('send', msg); - proxy.invoke('send', msg, room); - proxy.invoke('add', 1, 2) - .done(function (result: any) { - console.log('The result is ' + result); - }); - proxy.on('addMessage', function (msg?) { - console.log(msg); - }); - var connection = $.hubConnection('http://localhost:8081/'); - connection.start({ jsonp: true }); -} - -// Sample from : https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs#javascript--html -$(function () { - // Proxy created on the fly - var chat = $.connection.chat; - - // Declare a function on the chat hub so the server can invoke it - chat.client.addMessage = function (message) { - $('#messages').append('
      • ' + message + '
      • '); - }; - - // Start the connection - $.connection.hub.start().done(function () { - $("#broadcast").click(function () { - // Call the chat method on the server - chat.server.send($('#msg').val()); - }); - }); +/// + +function test_client() { + var connection = $.connection('/echo'); + connection.received(function (data) { + console.log(data); + }); + connection.error(function (error) { + console.warn(error); + }); + connection.stateChanged(function (change) { + if (change.newState === $.signalR.connectionState.reconnecting) { + console.log('Re-connecting'); + } + else if (change.newState === $.signalR.connectionState.connected) { + console.log('The server is online'); + } + }); + connection.reconnected(function () { + console.log('Reconnected'); + }); + connection.start(); + connection.start(function () { + console.log("connection started!"); + }); + connection.stop(); + connection.start().done(function () { + console.log("connection started!"); + }); + connection.start({ transport: 'longPolling' }); + connection.start({ transport: $.signalR.transports.webSockets }); + connection.start({ transport: ['longPolling', 'webSockets'] }); + connection.start({ waitForPageLoad: false }); + connection.start({ transport: 'longPolling' }, function () { + console.log('connection started!'); + }); + connection.send("Hello World"); + var connection = $.connection('http://localhost:8081/echo'); + connection.start({ jsonp: true }); +} + +function test_connection() { + var connection = $.connection('/echo'); + connection.received(function (data) { + $('#messages').append('
      • ' + data + '
      • '); + }); + connection.start(); + $("#broadcast").click(function () { + connection.send($('#msg').val()); + }); +} + +interface MyHubConnection extends HubConnection { + someState: string; + SomeFunction: Function; + + // My Hubs Client functions: + client: { + addMessage: (message: string) => void; + }; + // My Hubs Server function: + server: { + send(message: string): any; + }; +} + +interface SignalR { + chat: MyHubConnection; + myHub: MyHubConnection; +} + +function test_hubs() { + var chat = $.connection.chat; + $.connection.hub.start() + .done(function () { alert("Now connected!"); }) + .fail(function () { alert("Could not Connect!"); }); + + $.connection.hub.logging = true; + var myHub = $.connection.myHub; + myHub.someState = "SomeValue"; + function connectionReady() { + alert("Done calling first hub serverside-function"); + }; + myHub.SomeFunction = function () { + alert("serverside called 'Clients.SomeClientFunction()'"); + }; + $.connection.hub.error(function () { + alert("An error occured"); + }); + $.connection.hub.start() + .done(function () { + myHub.SomeFunction("whatever") + .done(connectionReady); + }) + .fail(function () { + alert("Could not Connect!"); + }); + + $.connection.hub.url = 'http://localhost:8081/signalr' + $.connection.hub.start(); + + var connection = $.hubConnection(); + var proxy = connection.createHubProxy('chat'); + var proxy = connection.createHubProxy('chat'), + msg = 'hello', + room = 'main'; + proxy.invoke('send', msg); + proxy.invoke('send', msg, room); + proxy.invoke('add', 1, 2) + .done(function (result: any) { + console.log('The result is ' + result); + }); + proxy.on('addMessage', function (msg?) { + console.log(msg); + }); + var connection = $.hubConnection('http://localhost:8081/'); + connection.start({ jsonp: true }); +} + +// Sample from : https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs#javascript--html +$(function () { + // Proxy created on the fly + var chat = $.connection.chat; + + // Declare a function on the chat hub so the server can invoke it + chat.client.addMessage = function (message) { + $('#messages').append('
      • ' + message + '
      • '); + }; + + // Start the connection + $.connection.hub.start().done(function () { + $("#broadcast").click(function () { + // Call the chat method on the server + chat.server.send($('#msg').val()); + }); + }); }); \ No newline at end of file diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index 515b1864f..d899416dd 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -1,113 +1,113 @@ -// Type definitions for SignalR 1.0 -// Project: http://www.asp.net/signalr -// Definitions by: Boris Yankov , T. Michael Keesey -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -interface HubMethod { - (callback: (data: string) => void ): any; -} - -interface SignalREvents { - onStart: string; - onStarting: string; - onReceived: string; - onError: string; - onConnectionSlow: string; - onReconnect: string; - onStateChanged: string; - onDisconnect: string; -} - -interface SignalRStateChange { - oldState: number; - newState: number; -} - -interface SignalR { - events: SignalREvents; - connectionState: any; - transports: any; - - hub: HubConnection; - id: string; - logging: boolean; - messageId: string; - url: string; - qs: any; - state: number; - - (url: string, queryString?: any, logging?: boolean): SignalR; - hubConnection(url?: string): SignalR; - - log(msg: string, logging: boolean): void; - isCrossDomain(url: string): boolean; - changeState(connection: SignalR, expectedState: number, newState: number): boolean; - isDisconnecting(connection: SignalR): boolean; - - // createHubProxy(hubName: string): SignalR; - - start(): JQueryPromise; - start(callback: () => void ): JQueryPromise; - start(settings: ConnectionSettings): JQueryPromise; - start(settings: ConnectionSettings, callback: () => void ): JQueryPromise; - - - send(data: string): void; - stop(async?: boolean, notifyServer?: boolean): void; - - starting(handler: () => void ): SignalR; - received(handler: (data: any) => void ): SignalR; - error(handler: (error: Error) => void ): SignalR; - stateChanged(handler: (change: SignalRStateChange) => void ): SignalR; - disconnected(handler: () => void ): SignalR; - connectionSlow(handler: () => void ): SignalR; - sending(handler: () => void ): SignalR; - reconnecting(handler: () => void): SignalR; - reconnected(handler: () => void): SignalR; -} - -interface HubProxy { - (connection: HubConnection, hubName: string): HubProxy; - state: any; - connection: HubConnection; - hubName: string; - init(connection: HubConnection, hubName: string): void; - hasSubscriptions(): boolean; - on(eventName: string, callback: (...msg: any[]) => void ): HubProxy; - off(eventName: string, callback: (msg: any) => void ): HubProxy; - invoke(methodName: string, ...args: any[]): JQueryDeferred; -} - -interface HubConnectionSettings { - queryString?: string; - logging?: boolean; - useDefaultPath?: boolean; -} - -interface HubConnection extends SignalR { - //(url?: string, queryString?: any, logging?: boolean): HubConnection; - proxies: any; - transport: { name: string, supportsKeepAlive: () => boolean }; - received(callback: (data: { Id: any; Method: any; Hub: any; State: any; Args: any; }) => void ): HubConnection; - createHubProxy(hubName: string): HubProxy; -} - -interface SignalRfn { - init(url: any, qs: any, logging: any): any; -} - -interface ConnectionSettings { - transport?: any; - callback?: any; - waitForPageLoad?: boolean; - jsonp?: boolean; -} - -interface JQueryStatic { - signalR: SignalR; - connection: SignalR; - hubConnection(url?: string, options?: HubConnectionSettings): HubConnection; -} +// Type definitions for SignalR 1.0 +// Project: http://www.asp.net/signalr +// Definitions by: Boris Yankov , T. Michael Keesey +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface HubMethod { + (callback: (data: string) => void ): any; +} + +interface SignalREvents { + onStart: string; + onStarting: string; + onReceived: string; + onError: string; + onConnectionSlow: string; + onReconnect: string; + onStateChanged: string; + onDisconnect: string; +} + +interface SignalRStateChange { + oldState: number; + newState: number; +} + +interface SignalR { + events: SignalREvents; + connectionState: any; + transports: any; + + hub: HubConnection; + id: string; + logging: boolean; + messageId: string; + url: string; + qs: any; + state: number; + + (url: string, queryString?: any, logging?: boolean): SignalR; + hubConnection(url?: string): SignalR; + + log(msg: string, logging: boolean): void; + isCrossDomain(url: string): boolean; + changeState(connection: SignalR, expectedState: number, newState: number): boolean; + isDisconnecting(connection: SignalR): boolean; + + // createHubProxy(hubName: string): SignalR; + + start(): JQueryPromise; + start(callback: () => void ): JQueryPromise; + start(settings: ConnectionSettings): JQueryPromise; + start(settings: ConnectionSettings, callback: () => void ): JQueryPromise; + + + send(data: string): void; + stop(async?: boolean, notifyServer?: boolean): void; + + starting(handler: () => void ): SignalR; + received(handler: (data: any) => void ): SignalR; + error(handler: (error: Error) => void ): SignalR; + stateChanged(handler: (change: SignalRStateChange) => void ): SignalR; + disconnected(handler: () => void ): SignalR; + connectionSlow(handler: () => void ): SignalR; + sending(handler: () => void ): SignalR; + reconnecting(handler: () => void): SignalR; + reconnected(handler: () => void): SignalR; +} + +interface HubProxy { + (connection: HubConnection, hubName: string): HubProxy; + state: any; + connection: HubConnection; + hubName: string; + init(connection: HubConnection, hubName: string): void; + hasSubscriptions(): boolean; + on(eventName: string, callback: (...msg: any[]) => void ): HubProxy; + off(eventName: string, callback: (msg: any) => void ): HubProxy; + invoke(methodName: string, ...args: any[]): JQueryDeferred; +} + +interface HubConnectionSettings { + queryString?: string; + logging?: boolean; + useDefaultPath?: boolean; +} + +interface HubConnection extends SignalR { + //(url?: string, queryString?: any, logging?: boolean): HubConnection; + proxies: any; + transport: { name: string, supportsKeepAlive: () => boolean }; + received(callback: (data: { Id: any; Method: any; Hub: any; State: any; Args: any; }) => void ): HubConnection; + createHubProxy(hubName: string): HubProxy; +} + +interface SignalRfn { + init(url: any, qs: any, logging: any): any; +} + +interface ConnectionSettings { + transport?: any; + callback?: any; + waitForPageLoad?: boolean; + jsonp?: boolean; +} + +interface JQueryStatic { + signalR: SignalR; + connection: SignalR; + hubConnection(url?: string, options?: HubConnectionSettings): HubConnection; +} diff --git a/sinon-chrome/sinon-chrome.d.ts b/sinon-chrome/sinon-chrome.d.ts index f5aa2344f..3057f7837 100644 --- a/sinon-chrome/sinon-chrome.d.ts +++ b/sinon-chrome/sinon-chrome.d.ts @@ -31,7 +31,7 @@ declare module SinonChrome { } declare module SinonChrome.events { - interface Event extends chrome.events.Event { + interface Event extends chrome.events.Event { trigger(...args: any[]): void; triggerAsync(...args: any[]): void; diff --git a/socket.io-client/socket.io-client-tests.ts b/socket.io-client/socket.io-client-tests.ts index cd9be6d3d..f2563fc46 100644 --- a/socket.io-client/socket.io-client-tests.ts +++ b/socket.io-client/socket.io-client-tests.ts @@ -1,61 +1,61 @@ -/// - -function testUsingWithNodeHTTPServer() { - var socket = io('http://localhost'); - socket.on('news', function (data: any) { - console.log(data); - socket.emit('my other event', { my: 'data' }); - }); -} - -function testUsingWithExpress() { - var socket = io.connect('http://localhost'); - socket.on('news', function (data: any) { - console.log(data); - socket.emit('my other event', { my: 'data' }); - }); -} - -function testUsingWithTheExpressFramework() { - var socket = io.connect('http://localhost'); - socket.on('news', function (data: any) { - console.log(data); - socket.emit('my other event', { my: 'data' }); - }); -} - -function testRestrictingYourselfToANamespace() { - var chat = io.connect('http://localhost/chat') - , news = io.connect('http://localhost/news'); - - chat.on('connect', function () { - chat.emit('hi!'); - }); - - news.on('news', function () { - news.emit('woot'); - }); -} - -function testSendingAndGettingData() { - var socket = io(); - socket.on('connect', function () { - socket.emit('ferret', 'tobi', function (data: any) { - console.log(data); - }); - }); -} - -function testUsingItJustAsACrossBrowserWebSocket() { - var socket = io('http://localhost/'); - socket.on('connect', function () { - socket.emit('hi'); - - socket.on('message', function (msg: any) { - }); - }); -} - -function testSettingReconnectionAttempts() { - var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 }); -} +/// + +function testUsingWithNodeHTTPServer() { + var socket = io('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithExpress() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithTheExpressFramework() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testRestrictingYourselfToANamespace() { + var chat = io.connect('http://localhost/chat') + , news = io.connect('http://localhost/news'); + + chat.on('connect', function () { + chat.emit('hi!'); + }); + + news.on('news', function () { + news.emit('woot'); + }); +} + +function testSendingAndGettingData() { + var socket = io(); + socket.on('connect', function () { + socket.emit('ferret', 'tobi', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var socket = io('http://localhost/'); + socket.on('connect', function () { + socket.emit('hi'); + + socket.on('message', function (msg: any) { + }); + }); +} + +function testSettingReconnectionAttempts() { + var manager = io.Manager({ reconnection: true, timeout: 0, reconnectionAttempts: 2, reconnectionDelay: 10 }); +} diff --git a/sortablejs/sortablejs-tests.ts b/sortablejs/sortablejs-tests.ts index 56b8b0a32..8c45596cb 100755 --- a/sortablejs/sortablejs-tests.ts +++ b/sortablejs/sortablejs-tests.ts @@ -1,299 +1,299 @@ -// Examples from project repo used for tests. - -/// - -var simpleList = document.getElementById('list'); -var list = simpleList; -var el = document.getElementById('el'); -var sortable = new Sortable(simpleList, {}); -var order = sortable.toArray(); -var angular: any; -var Ply: any; - -sortable.sort(order.reverse()); - -Sortable.create(list, { - delay: 500, - chosenClass: "chosen" -}); - -Sortable.create(el, { - handle: ".my-handle" -}); - -Sortable.create(list, { - filter: ".js-remove, .js-edit", - onFilter: function(event) { - var item = event.item, - control = event.target; - - if (Sortable.utils.is(control, ".js-remove")) { - item.parentNode.removeChild(item); - } - else if (Sortable.utils.is(control, ".js-edit")) { - // .. - } - } -}); - -Sortable.create(el, { - group: "localStorage-example", - store: { - get: function(sortable) { - var order = localStorage.getItem(sortable.options.group); - - return order ? order.split('|') : []; - }, - set: function(sortable) { - var order = sortable.toArray(); - - localStorage.setItem(sortable.options.group, order.join('|')); - } - } -}); - -Sortable.create(simpleList, { - forceFallback: true -}); - -Sortable.create(simpleList, { - ghostClass: 'ghost' -}); - -simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { - return `
        item ${iterator + 1}
        `; -}).join(''); - -Sortable.create(simpleList, { - delay: 500, - chosenClass: 'chosen' -}); - -simpleList.innerHTML = Array.apply(null, new Array(10)).map(function(value: any, iterator: number) { - return '
        item ' + - (iterator + 1) + - '
        '; -}).join(''); - -Sortable.create(simpleList, {}); - -simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { - return '
        item ' + - (iterator + 1) + - '
        '; -}).join(''); - -(function() { - 'use strict'; - - var byId = function(id: string) { return document.getElementById(id); }, - - loadScripts = function(desc: any, callback: any) { - var deps: string[] = []; - var key: string; - var idx = 0; - - for (key in desc) { - deps.push(key); - } - - (function _next() { - var pid: number, - name = deps[idx], - script = document.createElement('script'); - - script.type = 'text/javascript'; - script.src = desc[deps[idx]]; - - document.getElementsByTagName('head')[0].appendChild(script); - })() - }, - - console = window.console; - - - if (!console.log) { - console.log = function() { - alert([].join.apply(arguments, ' ')); - }; - } - - - Sortable.create(byId('foo'), { - group: "words", - animation: 150, - store: { - get: function(sortable) { - var order = localStorage.getItem(sortable.options.group); - return order ? order.split('|') : []; - }, - set: function(sortable) { - var order = sortable.toArray(); - localStorage.setItem(sortable.options.group, order.join('|')); - } - }, - onAdd: function(evt) { console.log('onAdd.foo:', [evt.item, evt.from]); }, - onUpdate: function(evt) { console.log('onUpdate.foo:', [evt.item, evt.from]); }, - onRemove: function(evt) { console.log('onRemove.foo:', [evt.item, evt.from]); }, - onStart: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, - onSort: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, - onEnd: function(evt) { console.log('onEnd.foo:', [evt.item, evt.from]); } - }); - - - Sortable.create(byId('bar'), { - group: "words", - animation: 150, - onAdd: function(evt) { console.log('onAdd.bar:', evt.item); }, - onUpdate: function(evt) { console.log('onUpdate.bar:', evt.item); }, - onRemove: function(evt) { console.log('onRemove.bar:', evt.item); }, - onStart: function(evt) { console.log('onStart.foo:', evt.item); }, - onEnd: function(evt) { console.log('onEnd.foo:', evt.item); } - }); - - - // Multi groups - Sortable.create(byId('multi'), { - animation: 150, - draggable: '.tile', - handle: '.tile__name' - }); - - [].forEach.call(byId('multi').getElementsByClassName('tile__list'), function(el: any) { - Sortable.create(el, { - group: 'photo', - animation: 150 - }); - }); - - - // Editable list - var editableList = Sortable.create(byId('editable'), { - animation: 150, - filter: '.js-remove', - onFilter: function(evt) { - evt.item.parentNode.removeChild(evt.item); - } - }); - - - byId('addUser').onclick = function() { - Ply.dialog('prompt', { - title: 'Add', - form: { name: 'name' } - }).done(function(ui: any) { - var el = document.createElement('li'); - el.innerHTML = ui.data.name + ''; - editableList.el.appendChild(el); - }); - }; - - - // Advanced groups - [{ - name: 'advanced', - pull: true, - put: true - }, - { - name: 'advanced', - pull: 'clone', - put: false - }, { - name: 'advanced', - pull: false, - put: true - }].forEach(function(groupOpts, i) { - Sortable.create(byId('advanced-' + (i + 1)), { - sort: (i != 1), - group: groupOpts, - animation: 150 - }); - }); - - - // 'handle' option - Sortable.create(byId('handle-1'), { - handle: '.drag-handle', - animation: 150 - }); - - - // Angular example - angular.module('todoApp', ['ng-sortable']) - .constant('ngSortableConfig', { - onEnd: function() { - console.log('default onEnd()'); - } - }) - .controller('TodoController', ['$scope', function($scope: any) { - $scope.todos = [ - { text: 'learn angular', done: true }, - { text: 'build an angular app', done: false } - ]; - - $scope.addTodo = function() { - $scope.todos.push({ text: $scope.todoText, done: false }); - $scope.todoText = ''; - }; - - $scope.remaining = function() { - var count = 0; - angular.forEach($scope.todos, function(todo: any) { - count += todo.done ? 0 : 1; - }); - return count; - }; - - $scope.archive = function() { - var oldTodos = $scope.todos; - $scope.todos = []; - angular.forEach(oldTodos, function(todo: any) { - if (!todo.done) $scope.todos.push(todo); - }); - }; - }]) - .controller('TodoControllerNext', ['$scope', function($scope: any) { - $scope.todos = [ - { text: 'learn Sortable', done: true }, - { text: 'use ng-sortable', done: false }, - { text: 'Enjoy', done: false } - ]; - - $scope.remaining = function() { - var count = 0; - angular.forEach($scope.todos, function(todo: any) { - count += todo.done ? 0 : 1; - }); - return count; - }; - - $scope.sortableConfig = { group: 'todo', animation: 150 }; - 'Start End Add Update Remove Sort'.split(' ').forEach(function(name: string) { - $scope.sortableConfig['on' + name] = console.log.bind(console, name); - }); - }]); -})(); - -// Background -document.addEventListener("DOMContentLoaded", function() { - function setNoiseBackground(el: any, width: number, height: number, opacity: number) { - var canvas = document.createElement("canvas"); - var context = canvas.getContext("2d"); - - canvas.width = width; - canvas.height = height; - - for (var i = 0; i < width; i++) { - for (var j = 0; j < height; j++) { - var val = Math.floor(Math.random() * 255); - context.fillStyle = "rgba(" + val + "," + val + "," + val + "," + opacity + ")"; - context.fillRect(i, j, 1, 1); - } - } - - el.style.background = "url(" + canvas.toDataURL("image/png") + ")"; - } - - setNoiseBackground(document.getElementsByTagName('body')[0], 50, 50, 0.02); -}, false); +// Examples from project repo used for tests. + +/// + +var simpleList = document.getElementById('list'); +var list = simpleList; +var el = document.getElementById('el'); +var sortable = new Sortable(simpleList, {}); +var order = sortable.toArray(); +var angular: any; +var Ply: any; + +sortable.sort(order.reverse()); + +Sortable.create(list, { + delay: 500, + chosenClass: "chosen" +}); + +Sortable.create(el, { + handle: ".my-handle" +}); + +Sortable.create(list, { + filter: ".js-remove, .js-edit", + onFilter: function(event) { + var item = event.item, + control = event.target; + + if (Sortable.utils.is(control, ".js-remove")) { + item.parentNode.removeChild(item); + } + else if (Sortable.utils.is(control, ".js-edit")) { + // .. + } + } +}); + +Sortable.create(el, { + group: "localStorage-example", + store: { + get: function(sortable) { + var order = localStorage.getItem(sortable.options.group); + + return order ? order.split('|') : []; + }, + set: function(sortable) { + var order = sortable.toArray(); + + localStorage.setItem(sortable.options.group, order.join('|')); + } + } +}); + +Sortable.create(simpleList, { + forceFallback: true +}); + +Sortable.create(simpleList, { + ghostClass: 'ghost' +}); + +simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { + return `
        item ${iterator + 1}
        `; +}).join(''); + +Sortable.create(simpleList, { + delay: 500, + chosenClass: 'chosen' +}); + +simpleList.innerHTML = Array.apply(null, new Array(10)).map(function(value: any, iterator: number) { + return '
        item ' + + (iterator + 1) + + '
        '; +}).join(''); + +Sortable.create(simpleList, {}); + +simpleList.innerHTML = Array.apply(null, new Array(100)).map(function(value: any, iterator: number) { + return '
        item ' + + (iterator + 1) + + '
        '; +}).join(''); + +(function() { + 'use strict'; + + var byId = function(id: string) { return document.getElementById(id); }, + + loadScripts = function(desc: any, callback: any) { + var deps: string[] = []; + var key: string; + var idx = 0; + + for (key in desc) { + deps.push(key); + } + + (function _next() { + var pid: number, + name = deps[idx], + script = document.createElement('script'); + + script.type = 'text/javascript'; + script.src = desc[deps[idx]]; + + document.getElementsByTagName('head')[0].appendChild(script); + })() + }, + + console = window.console; + + + if (!console.log) { + console.log = function() { + alert([].join.apply(arguments, ' ')); + }; + } + + + Sortable.create(byId('foo'), { + group: "words", + animation: 150, + store: { + get: function(sortable) { + var order = localStorage.getItem(sortable.options.group); + return order ? order.split('|') : []; + }, + set: function(sortable) { + var order = sortable.toArray(); + localStorage.setItem(sortable.options.group, order.join('|')); + } + }, + onAdd: function(evt) { console.log('onAdd.foo:', [evt.item, evt.from]); }, + onUpdate: function(evt) { console.log('onUpdate.foo:', [evt.item, evt.from]); }, + onRemove: function(evt) { console.log('onRemove.foo:', [evt.item, evt.from]); }, + onStart: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, + onSort: function(evt) { console.log('onStart.foo:', [evt.item, evt.from]); }, + onEnd: function(evt) { console.log('onEnd.foo:', [evt.item, evt.from]); } + }); + + + Sortable.create(byId('bar'), { + group: "words", + animation: 150, + onAdd: function(evt) { console.log('onAdd.bar:', evt.item); }, + onUpdate: function(evt) { console.log('onUpdate.bar:', evt.item); }, + onRemove: function(evt) { console.log('onRemove.bar:', evt.item); }, + onStart: function(evt) { console.log('onStart.foo:', evt.item); }, + onEnd: function(evt) { console.log('onEnd.foo:', evt.item); } + }); + + + // Multi groups + Sortable.create(byId('multi'), { + animation: 150, + draggable: '.tile', + handle: '.tile__name' + }); + + [].forEach.call(byId('multi').getElementsByClassName('tile__list'), function(el: any) { + Sortable.create(el, { + group: 'photo', + animation: 150 + }); + }); + + + // Editable list + var editableList = Sortable.create(byId('editable'), { + animation: 150, + filter: '.js-remove', + onFilter: function(evt) { + evt.item.parentNode.removeChild(evt.item); + } + }); + + + byId('addUser').onclick = function() { + Ply.dialog('prompt', { + title: 'Add', + form: { name: 'name' } + }).done(function(ui: any) { + var el = document.createElement('li'); + el.innerHTML = ui.data.name + ''; + editableList.el.appendChild(el); + }); + }; + + + // Advanced groups + [{ + name: 'advanced', + pull: true, + put: true + }, + { + name: 'advanced', + pull: 'clone', + put: false + }, { + name: 'advanced', + pull: false, + put: true + }].forEach(function(groupOpts, i) { + Sortable.create(byId('advanced-' + (i + 1)), { + sort: (i != 1), + group: groupOpts, + animation: 150 + }); + }); + + + // 'handle' option + Sortable.create(byId('handle-1'), { + handle: '.drag-handle', + animation: 150 + }); + + + // Angular example + angular.module('todoApp', ['ng-sortable']) + .constant('ngSortableConfig', { + onEnd: function() { + console.log('default onEnd()'); + } + }) + .controller('TodoController', ['$scope', function($scope: any) { + $scope.todos = [ + { text: 'learn angular', done: true }, + { text: 'build an angular app', done: false } + ]; + + $scope.addTodo = function() { + $scope.todos.push({ text: $scope.todoText, done: false }); + $scope.todoText = ''; + }; + + $scope.remaining = function() { + var count = 0; + angular.forEach($scope.todos, function(todo: any) { + count += todo.done ? 0 : 1; + }); + return count; + }; + + $scope.archive = function() { + var oldTodos = $scope.todos; + $scope.todos = []; + angular.forEach(oldTodos, function(todo: any) { + if (!todo.done) $scope.todos.push(todo); + }); + }; + }]) + .controller('TodoControllerNext', ['$scope', function($scope: any) { + $scope.todos = [ + { text: 'learn Sortable', done: true }, + { text: 'use ng-sortable', done: false }, + { text: 'Enjoy', done: false } + ]; + + $scope.remaining = function() { + var count = 0; + angular.forEach($scope.todos, function(todo: any) { + count += todo.done ? 0 : 1; + }); + return count; + }; + + $scope.sortableConfig = { group: 'todo', animation: 150 }; + 'Start End Add Update Remove Sort'.split(' ').forEach(function(name: string) { + $scope.sortableConfig['on' + name] = console.log.bind(console, name); + }); + }]); +})(); + +// Background +document.addEventListener("DOMContentLoaded", function() { + function setNoiseBackground(el: any, width: number, height: number, opacity: number) { + var canvas = document.createElement("canvas"); + var context = canvas.getContext("2d"); + + canvas.width = width; + canvas.height = height; + + for (var i = 0; i < width; i++) { + for (var j = 0; j < height; j++) { + var val = Math.floor(Math.random() * 255); + context.fillStyle = "rgba(" + val + "," + val + "," + val + "," + opacity + ")"; + context.fillRect(i, j, 1, 1); + } + } + + el.style.background = "url(" + canvas.toDataURL("image/png") + ")"; + } + + setNoiseBackground(document.getElementsByTagName('body')[0], 50, 50, 0.02); +}, false); diff --git a/sortablejs/sortablejs.d.ts b/sortablejs/sortablejs.d.ts index 6a745ab31..e633830e5 100755 --- a/sortablejs/sortablejs.d.ts +++ b/sortablejs/sortablejs.d.ts @@ -1,208 +1,208 @@ -// Type definitions for Sortable.js v1.3.0-rc1 -// Project: https://github.com/RubaXa/Sortable -// Definitions by: Maw-Fox -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module Sortablejs { - interface SortableOptions { - group?: any; - sort?: boolean; - delay?: number; - disabled?: boolean; - store?: { - get: (sortable: Sortable) => any[]; - set: (sortable: Sortable) => any; - }; - animation?: number; - handle?: string; - filter?: any; - draggable?: string; - ghostClass?: string; - chosenClass?: string; - dataIdAttr?: string; - forceFallback?: boolean; - fallbackClass?: string; - fallbackOnBody?: boolean; - scroll?: boolean; - scrollSensitivity?: number; - scrollSpeed?: number; - setData?: (dataTransfer: any, draggedElement: any) => any; - onStart?: (event: any) => any; - onEnd?: (event: any) => any; - onAdd?: (event: any) => any; - onUpdate?: (event: any) => any; - onSort?: (event: any) => any; - onRemove?: (event: any) => any; - onFilter?: (event: any) => any; - onMove?: (event: any) => boolean; - } - - interface SortableUtils { - /** - * Attach an event handler function - * @param {HTMLElement} element an HTMLElement. - * @param {string} event an Event context. - * @param {Function} fn - */ - on(element: any, event: string, fn: (event: any) => any): void; - - /** - * Remove an event handler function - * @param {HTMLElement} element an HTMLElement. - * @param {string} event an Event context. - * @param {Function} fn a callback. - */ - off(element: any, event: string, fn: (event: any) => any): void; - - /** - * Get the values of all the CSS properties. - * @param {HTMLElement} element an HTMLElement. - * @returns {Object} - */ - css(element: any): any; - - /** - * Get the value of style properties. - * @param {HTMLElement} element an HTMLElement. - * @param {string} prop a property key. - * @returns {*} - */ - css(element: any, prop: string): any; - - /** - * Set one CSS property. - * @param {HTMLElement} element an HTMLElement. - * @param {string} prop a property key. - * @param {string} value a property value. - */ - css(element: any, prop: string, value: string): void; - - /** - * Set CSS properties. - * @param {HTMLElement} element an HTMLElement. - * @param {Object} props a properties object. - */ - css(element: any, props: any): void; - - /** - * Get elements by tag name. - * @param {HTMLElement} context an HTMLElement. - * @param {string} tagName A tag name. - * @param {function} [iterator] An iterator. - * @returns {HTMLElement[]} - */ - find(context: any, tagName: string, iterator?: (value: any) => any): any[]; - - /** - * Takes a function and returns a new one that will always have a particular context. - * @param {*} context an HTMLElement. - * @param {function} fn a function. - * @returns {function} - */ - bind(context: any, fn: () => any): () => any; - - /** - * Check the current matched set of elements against a selector. - * @param {HTMLElement} element an HTMLElement. - * @param {string} selector an element selector. - * @returns {boolean} - */ - is(element: any, selector: string): boolean; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * @param {HTMLElement} element an HTMLElement. - * @param {string} selector an element seletor. - * @param {HTMLElement} [context] a specific element's context. - * @returns {HTMLElement} - */ - closest(element: any, selector: string, context?: any): any; - - /** - * Add or remove one classes from each element - * @param {HTMLElement} element an HTMLElement. - * @param {string} name a class name. - * @param {boolean} state a class's state. - */ - toggleClass(element: any, name: string, state: boolean): void; - } - - class DOMRect { - public bottom: number; - public height: number; - public left: number; - public right: number; - public top: number; - public width: number; - public x: number; - public y: number; - } - - class Sortable { - public options: SortableOptions; - public el: any; - - /** - * Sortable's main constructor. - * @param {HTMLElement} element Any variety of HTMLElement. - * @param {SortableOptions} options Sortable options object. - */ - constructor(element: any, options: SortableOptions); - - static active: Sortable; - static utils: SortableUtils; - - /** - * Creation of new instances. - * @param {HTMLElement} element Any variety of HTMLElement. - * @param {SortableOptions} options Sortable options object. - * @returns {Sortable} - */ - static create(element: any, options: SortableOptions): Sortable; - - /** - * Options getter/setter - * @param {string} name a SortableOptions property. - * @param {*} [value] a Value. - * @returns {*} - */ - option(name: string, value: any): any; - option(name: string): any; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * @param {string|HTMLElement} element an HTMLElement or selector string. - * @returns {HTMLElement} - */ - closest(element: any): any; - - /** - * Sorts the elements according to the array. - * @param {string[]} order an array of strings to sort. - */ - sort(order: string[]): void; - - /** - * Saving and restoring of the sort. - */ - save(): void; - - /** - * Removes the sortable functionality completely. - */ - destroy(): void; - - /** - * Serializes the sortable's item data-id's (dataIdAttr option) into an array of string. - * @returns {string[]} - */ - toArray(): string[]; - } -} - -import Sortable = Sortablejs.Sortable; - -declare module 'Sortable' { - import Sortable = Sortablejs.Sortable; - export = Sortable; -} +// Type definitions for Sortable.js v1.3.0-rc1 +// Project: https://github.com/RubaXa/Sortable +// Definitions by: Maw-Fox +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Sortablejs { + interface SortableOptions { + group?: any; + sort?: boolean; + delay?: number; + disabled?: boolean; + store?: { + get: (sortable: Sortable) => any[]; + set: (sortable: Sortable) => any; + }; + animation?: number; + handle?: string; + filter?: any; + draggable?: string; + ghostClass?: string; + chosenClass?: string; + dataIdAttr?: string; + forceFallback?: boolean; + fallbackClass?: string; + fallbackOnBody?: boolean; + scroll?: boolean; + scrollSensitivity?: number; + scrollSpeed?: number; + setData?: (dataTransfer: any, draggedElement: any) => any; + onStart?: (event: any) => any; + onEnd?: (event: any) => any; + onAdd?: (event: any) => any; + onUpdate?: (event: any) => any; + onSort?: (event: any) => any; + onRemove?: (event: any) => any; + onFilter?: (event: any) => any; + onMove?: (event: any) => boolean; + } + + interface SortableUtils { + /** + * Attach an event handler function + * @param {HTMLElement} element an HTMLElement. + * @param {string} event an Event context. + * @param {Function} fn + */ + on(element: any, event: string, fn: (event: any) => any): void; + + /** + * Remove an event handler function + * @param {HTMLElement} element an HTMLElement. + * @param {string} event an Event context. + * @param {Function} fn a callback. + */ + off(element: any, event: string, fn: (event: any) => any): void; + + /** + * Get the values of all the CSS properties. + * @param {HTMLElement} element an HTMLElement. + * @returns {Object} + */ + css(element: any): any; + + /** + * Get the value of style properties. + * @param {HTMLElement} element an HTMLElement. + * @param {string} prop a property key. + * @returns {*} + */ + css(element: any, prop: string): any; + + /** + * Set one CSS property. + * @param {HTMLElement} element an HTMLElement. + * @param {string} prop a property key. + * @param {string} value a property value. + */ + css(element: any, prop: string, value: string): void; + + /** + * Set CSS properties. + * @param {HTMLElement} element an HTMLElement. + * @param {Object} props a properties object. + */ + css(element: any, props: any): void; + + /** + * Get elements by tag name. + * @param {HTMLElement} context an HTMLElement. + * @param {string} tagName A tag name. + * @param {function} [iterator] An iterator. + * @returns {HTMLElement[]} + */ + find(context: any, tagName: string, iterator?: (value: any) => any): any[]; + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param {*} context an HTMLElement. + * @param {function} fn a function. + * @returns {function} + */ + bind(context: any, fn: () => any): () => any; + + /** + * Check the current matched set of elements against a selector. + * @param {HTMLElement} element an HTMLElement. + * @param {string} selector an element selector. + * @returns {boolean} + */ + is(element: any, selector: string): boolean; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param {HTMLElement} element an HTMLElement. + * @param {string} selector an element seletor. + * @param {HTMLElement} [context] a specific element's context. + * @returns {HTMLElement} + */ + closest(element: any, selector: string, context?: any): any; + + /** + * Add or remove one classes from each element + * @param {HTMLElement} element an HTMLElement. + * @param {string} name a class name. + * @param {boolean} state a class's state. + */ + toggleClass(element: any, name: string, state: boolean): void; + } + + class DOMRect { + public bottom: number; + public height: number; + public left: number; + public right: number; + public top: number; + public width: number; + public x: number; + public y: number; + } + + class Sortable { + public options: SortableOptions; + public el: any; + + /** + * Sortable's main constructor. + * @param {HTMLElement} element Any variety of HTMLElement. + * @param {SortableOptions} options Sortable options object. + */ + constructor(element: any, options: SortableOptions); + + static active: Sortable; + static utils: SortableUtils; + + /** + * Creation of new instances. + * @param {HTMLElement} element Any variety of HTMLElement. + * @param {SortableOptions} options Sortable options object. + * @returns {Sortable} + */ + static create(element: any, options: SortableOptions): Sortable; + + /** + * Options getter/setter + * @param {string} name a SortableOptions property. + * @param {*} [value] a Value. + * @returns {*} + */ + option(name: string, value: any): any; + option(name: string): any; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param {string|HTMLElement} element an HTMLElement or selector string. + * @returns {HTMLElement} + */ + closest(element: any): any; + + /** + * Sorts the elements according to the array. + * @param {string[]} order an array of strings to sort. + */ + sort(order: string[]): void; + + /** + * Saving and restoring of the sort. + */ + save(): void; + + /** + * Removes the sortable functionality completely. + */ + destroy(): void; + + /** + * Serializes the sortable's item data-id's (dataIdAttr option) into an array of string. + * @returns {string[]} + */ + toArray(): string[]; + } +} + +import Sortable = Sortablejs.Sortable; + +declare module 'Sortable' { + import Sortable = Sortablejs.Sortable; + export = Sortable; +} diff --git a/soundjs/soundjs.d.ts b/soundjs/soundjs.d.ts index 445006cab..37af7431e 100644 --- a/soundjs/soundjs.d.ts +++ b/soundjs/soundjs.d.ts @@ -1,147 +1,147 @@ -// Type definitions for SoundJS 0.6.0 -// Project: http://www.createjs.com/#!/SoundJS -// Definitions by: Pedro Ferreira -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* - Copyright (c) 2012 Pedro Ferreira - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -// Library documentation : http://www.createjs.com/Docs/SoundJS/modules/SoundJS.html - -/// -/// - -declare module createjs { - - export class AbstractPlugin - { - // methods - create(src: string, startTime: number, duration: number): AbstractSoundInstance; - getVolume(): number; - isPreloadComplete(src: string): boolean; - isPreloadStarted(src: string): boolean; - isSupported(): boolean; - preload(loader: Object): void; - register(loadItem: string, instances: number): Object; - removeAllSounds(src: string): void; - removeSound(src: string): void; - setMute(value: boolean): boolean; - setVolume(value: number): boolean; - } - - export class AbstractSoundInstance extends EventDispatcher - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - - // properties - duration: number; - loop: number; - muted: boolean; - pan: number; - paused: boolean; - playbackResource: Object; - playState: string; - position: number; - src: string; - uniqueId: number | string; - volume: number; - - // methods - destroy(): void; - getDuration(): number; - getLoop(): number; - getMute(): boolean; - getPan(): number; - getPaused(): boolean; - getPosition(): number; - getVolume(): number; - play(interrupt?: string | Object, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; - setDuration(value: number): AbstractSoundInstance; - setLoop(value: number): void; - setMute(value: boolean): AbstractSoundInstance; - setPan(value: number): AbstractSoundInstance; - setPlayback(value: Object): AbstractSoundInstance; - setPosition(value: number): AbstractSoundInstance; - setVolume(value: number): AbstractSoundInstance; - stop(): AbstractSoundInstance; - } - - export class FlashAudioLoader extends AbstractLoader - { - // properties - flashId: string; - - // methods - setFlash(flash: Object): void; - } - - export class FlashAudioPlugin extends AbstractPlugin - { - // properties - flashReady: boolean; - showOutput: boolean; - static swfPath: string; - - // methods - static isSupported(): boolean; - } - - export class FlashAudioSoundInstance extends AbstractSoundInstance - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - } - - /** - * @deprecated - use FlashAudioPlugin - */ - export class FlashPlugin { - constructor(); - - // properties - static buildDate: string; - flashReady: boolean; - showOutput: boolean; - static swfPath: string; - static version: string; - - // methods - create(src: string): AbstractSoundInstance; - getVolume(): number; - isPreloadStarted(src: string): boolean; - static isSupported(): boolean; - preload(src: string, instance: Object): void; - register(src: string, instances: number): Object; - removeAllSounds (): void; - removeSound(src: string): void; - setMute(value: boolean): boolean; - setVolume(value: number): boolean; - } - - export class HTMLAudioPlugin extends AbstractPlugin - { - constructor(); - - // properties - defaultNumChannels: number; - enableIOS: boolean; // deprecated - static MAX_INSTANCES: number; - - // methods - static isSupported(): boolean; - } - - export class HTMLAudioSoundInstance extends AbstractSoundInstance - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - } - - export class HTMLAudioTagPool - { - +// Type definitions for SoundJS 0.6.0 +// Project: http://www.createjs.com/#!/SoundJS +// Definitions by: Pedro Ferreira +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* + Copyright (c) 2012 Pedro Ferreira + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +// Library documentation : http://www.createjs.com/Docs/SoundJS/modules/SoundJS.html + +/// +/// + +declare module createjs { + + export class AbstractPlugin + { + // methods + create(src: string, startTime: number, duration: number): AbstractSoundInstance; + getVolume(): number; + isPreloadComplete(src: string): boolean; + isPreloadStarted(src: string): boolean; + isSupported(): boolean; + preload(loader: Object): void; + register(loadItem: string, instances: number): Object; + removeAllSounds(src: string): void; + removeSound(src: string): void; + setMute(value: boolean): boolean; + setVolume(value: number): boolean; + } + + export class AbstractSoundInstance extends EventDispatcher + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + + // properties + duration: number; + loop: number; + muted: boolean; + pan: number; + paused: boolean; + playbackResource: Object; + playState: string; + position: number; + src: string; + uniqueId: number | string; + volume: number; + + // methods + destroy(): void; + getDuration(): number; + getLoop(): number; + getMute(): boolean; + getPan(): number; + getPaused(): boolean; + getPosition(): number; + getVolume(): number; + play(interrupt?: string | Object, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; + setDuration(value: number): AbstractSoundInstance; + setLoop(value: number): void; + setMute(value: boolean): AbstractSoundInstance; + setPan(value: number): AbstractSoundInstance; + setPlayback(value: Object): AbstractSoundInstance; + setPosition(value: number): AbstractSoundInstance; + setVolume(value: number): AbstractSoundInstance; + stop(): AbstractSoundInstance; + } + + export class FlashAudioLoader extends AbstractLoader + { + // properties + flashId: string; + + // methods + setFlash(flash: Object): void; + } + + export class FlashAudioPlugin extends AbstractPlugin + { + // properties + flashReady: boolean; + showOutput: boolean; + static swfPath: string; + + // methods + static isSupported(): boolean; + } + + export class FlashAudioSoundInstance extends AbstractSoundInstance + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + } + + /** + * @deprecated - use FlashAudioPlugin + */ + export class FlashPlugin { + constructor(); + + // properties + static buildDate: string; + flashReady: boolean; + showOutput: boolean; + static swfPath: string; + static version: string; + + // methods + create(src: string): AbstractSoundInstance; + getVolume(): number; + isPreloadStarted(src: string): boolean; + static isSupported(): boolean; + preload(src: string, instance: Object): void; + register(src: string, instances: number): Object; + removeAllSounds (): void; + removeSound(src: string): void; + setMute(value: boolean): boolean; + setVolume(value: number): boolean; + } + + export class HTMLAudioPlugin extends AbstractPlugin + { + constructor(); + + // properties + defaultNumChannels: number; + enableIOS: boolean; // deprecated + static MAX_INSTANCES: number; + + // methods + static isSupported(): boolean; + } + + export class HTMLAudioSoundInstance extends AbstractSoundInstance + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + } + + export class HTMLAudioTagPool + { + } export class PlayPropsConfig @@ -156,110 +156,110 @@ declare module createjs { volume:number; static create( value:PlayPropsConfig|any ): PlayPropsConfig; set ( props:any ): PlayPropsConfig; - } - - export class Sound extends EventDispatcher - { - // properties - static activePlugin: Object; - static alternateExtensions: any[]; - static defaultInterruptBehavior: string; - static EXTENSION_MAP: Object; - static INTERRUPT_ANY: string; - static INTERRUPT_EARLY: string; - static INTERRUPT_LATE: string; - static INTERRUPT_NONE: string; - static PLAY_FAILED: string; - static PLAY_FINISHED: string; - static PLAY_INITED: string; - static PLAY_INTERRUPTED: string; - static PLAY_SUCCEEDED: string; + } + + export class Sound extends EventDispatcher + { + // properties + static activePlugin: Object; + static alternateExtensions: any[]; + static defaultInterruptBehavior: string; + static EXTENSION_MAP: Object; + static INTERRUPT_ANY: string; + static INTERRUPT_EARLY: string; + static INTERRUPT_LATE: string; + static INTERRUPT_NONE: string; + static PLAY_FAILED: string; + static PLAY_FINISHED: string; + static PLAY_INITED: string; + static PLAY_INTERRUPTED: string; + static PLAY_SUCCEEDED: string; static SUPPORTED_EXTENSIONS: string[]; static muted: boolean; - static volume: number; - static capabilities: any; - - // methods - static createInstance(src: string): AbstractSoundInstance; - static getCapabilities(): Object; - static getCapability(key: string): number | boolean; - static getMute(): boolean; - static getVolume(): number; - static initializeDefaultPlugins(): boolean; - static isReady(): boolean; - static loadComplete(src: string): boolean; - static play(src: string, interrupt?: any, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; - static registerManifest(manifest: Object[], basePath: string): Object; - static registerPlugins(plugins: any[]): boolean; - static registerSound(src: string | Object, id?: string, data?: number | Object, basePath?: string): Object; - static registerSounds(sounds: Object[], basePath?: string): Object[]; - static removeAllSounds(): void; - static removeManifest(manifest: any[], basePath: string): Object; - static removeSound(src: string | Object, basePath: string): boolean; - static setMute(value: boolean): boolean; - static setVolume(value: number): void; - static stop(): void; - - // EventDispatcher mixins - static addEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; - static addEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; - static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; - static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; - static dispatchEvent(eventObj: Object | string | Event, target?: Object): boolean; - static hasEventListener(type: string): boolean; - static off(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; - static off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; - static off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; - static off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - static off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" - static on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; - static on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; - static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; - static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; - static removeAllEventListeners(type?: string): void; - static removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; - static removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; - static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; - static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; - static removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" - static toString(): string; - static willTrigger(type: string): boolean; - } - - export class SoundJS { - static buildDate: string; - static version: string; - } - - export class WebAudioLoader - { - static context: AudioContext; - } - - export class WebAudioPlugin extends AbstractPlugin - { - constructor(); - - // properties - static context: AudioContext; - context: AudioContext; - dynamicsCompressorNode: DynamicsCompressorNode; - gainNode: GainNode; - - // methods - static isSupported(): boolean; - static playEmptySound(): void; - } - - export class WebAudioSoundInstance extends AbstractSoundInstance - { - constructor(src: string, startTime: number, duration: number, playbackResource: Object); - - // properties - static context: AudioContext; - static destinationNode: AudioNode; - gainNode: GainNode; - panNode: PannerNode; - sourceNode: AudioNode; - } -} + static volume: number; + static capabilities: any; + + // methods + static createInstance(src: string): AbstractSoundInstance; + static getCapabilities(): Object; + static getCapability(key: string): number | boolean; + static getMute(): boolean; + static getVolume(): number; + static initializeDefaultPlugins(): boolean; + static isReady(): boolean; + static loadComplete(src: string): boolean; + static play(src: string, interrupt?: any, delay?: number, offset?: number, loop?: number, volume?: number, pan?: number): AbstractSoundInstance; + static registerManifest(manifest: Object[], basePath: string): Object; + static registerPlugins(plugins: any[]): boolean; + static registerSound(src: string | Object, id?: string, data?: number | Object, basePath?: string): Object; + static registerSounds(sounds: Object[], basePath?: string): Object[]; + static removeAllSounds(): void; + static removeManifest(manifest: any[], basePath: string): Object; + static removeSound(src: string | Object, basePath: string): boolean; + static setMute(value: boolean): boolean; + static setVolume(value: number): void; + static stop(): void; + + // EventDispatcher mixins + static addEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): Function; + static addEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): Function; + static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): Object; + static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): Object; + static dispatchEvent(eventObj: Object | string | Event, target?: Object): boolean; + static hasEventListener(type: string): boolean; + static off(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; + static off(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; + static off(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; + static off(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + static off(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static on(type: string, listener: (eventObj: Object) => boolean, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: (eventObj: Object) => void, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Function; + static on(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + static on(type: string, listener: { handleEvent: (eventObj: Object) => void; }, scope?: Object, once?: boolean, data?: any, useCapture?: boolean): Object; + static removeAllEventListeners(type?: string): void; + static removeEventListener(type: string, listener: (eventObj: Object) => boolean, useCapture?: boolean): void; + static removeEventListener(type: string, listener: (eventObj: Object) => void, useCapture?: boolean): void; + static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => boolean; }, useCapture?: boolean): void; + static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }, useCapture?: boolean): void; + static removeEventListener(type: string, listener: Function, useCapture?: boolean): void; // It is necessary for "arguments.callee" + static toString(): string; + static willTrigger(type: string): boolean; + } + + export class SoundJS { + static buildDate: string; + static version: string; + } + + export class WebAudioLoader + { + static context: AudioContext; + } + + export class WebAudioPlugin extends AbstractPlugin + { + constructor(); + + // properties + static context: AudioContext; + context: AudioContext; + dynamicsCompressorNode: DynamicsCompressorNode; + gainNode: GainNode; + + // methods + static isSupported(): boolean; + static playEmptySound(): void; + } + + export class WebAudioSoundInstance extends AbstractSoundInstance + { + constructor(src: string, startTime: number, duration: number, playbackResource: Object); + + // properties + static context: AudioContext; + static destinationNode: AudioNode; + gainNode: GainNode; + panNode: PannerNode; + sourceNode: AudioNode; + } +} diff --git a/spin/spin-tests.ts b/spin/spin-tests.ts index 4751b2076..1816b784b 100644 --- a/spin/spin-tests.ts +++ b/spin/spin-tests.ts @@ -1,34 +1,34 @@ -/// - -var spinner = new Spinner().spin(); -target.appendChild(spinner.el); - -var target = document.getElementById('foo'); -var opts = { speed: 5, color: '#abcdef' }; -var spinner2 = new Spinner(opts).spin(target); - -var opts2 = { - lines: 10, - length: 20, - width: 7, - radius: 14, - corners: 0.6, - rotate: 0, - direction: 1, - color: ['#aaa', '#fedcba', '#fff', '#aef02b'], - speed: 1.5, - trail: 50, - shadow: true, - hwaccel: true, - className: 'spinner', - zIndex: 5, - top: '28', - left: 'auto', - scale: 1, - opacity: 0.25, - fps: 20, - position: 'absolute' -}; - -var newTarget = document.getElementById('bar'); -var spinner3 = new Spinner(opts2).spin(newTarget); +/// + +var spinner = new Spinner().spin(); +target.appendChild(spinner.el); + +var target = document.getElementById('foo'); +var opts = { speed: 5, color: '#abcdef' }; +var spinner2 = new Spinner(opts).spin(target); + +var opts2 = { + lines: 10, + length: 20, + width: 7, + radius: 14, + corners: 0.6, + rotate: 0, + direction: 1, + color: ['#aaa', '#fedcba', '#fff', '#aef02b'], + speed: 1.5, + trail: 50, + shadow: true, + hwaccel: true, + className: 'spinner', + zIndex: 5, + top: '28', + left: 'auto', + scale: 1, + opacity: 0.25, + fps: 20, + position: 'absolute' +}; + +var newTarget = document.getElementById('bar'); +var spinner3 = new Spinner(opts2).spin(newTarget); diff --git a/spin/spin.d.ts b/spin/spin.d.ts index 9924aa2c1..4fcfb6b68 100644 --- a/spin/spin.d.ts +++ b/spin/spin.d.ts @@ -1,50 +1,50 @@ -// Type definitions for Spin.js 2.3.2 -// Project: http://fgnass.github.com/spin.js/ -// Definitions by: Boris Yankov , Theodore Brown -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface SpinnerOptions { - lines?: number; // The number of lines to draw - length?: number; // The length of each line - width?: number; // The line thickness - radius?: number; // The radius of the inner circle - corners?: number; // Corner roundness (0..1) - rotate?: number; // The rotation offset - direction?: number; // 1: clockwise, -1: counterclockwise - color?: any; // #rgb or #rrggbb or array of colors - speed?: number; // Rounds per second - trail?: number; // Afterglow percentage - shadow?: boolean; // Whether to render a shadow - hwaccel?: boolean; // Whether to use hardware acceleration - className?: string; // The CSS class to assign to the spinner - zIndex?: number; // The z-index (defaults to 2000000000) - top?: string; // Top position relative to parent in px - left?: string; // Left position relative to parent in px - scale?: number; // Scales overall size of the spinner - opacity?: number; // Opacity of the lines - fps?: number; // Frames per second when using setTimeout() as a fallback for CSS - position?: string; // Element positioning -} - - -declare class Spinner { - /** The Spinner's HTML element - can be used to manually insert the spinner into the DOM */ - public el: HTMLElement; - constructor(options?: SpinnerOptions); - - /** - * Adds the spinner to the given target element. If this instance is already - * spinning, it is automatically removed from its previous target by calling - * stop() internally. - */ - spin(target?: HTMLElement): Spinner; - - /** - * Stops and removes the Spinner. - * Stopped spinners may be reused by calling spin() again. - */ - stop(): Spinner; - lines(el:HTMLElement, o:SpinnerOptions):HTMLElement; - opacity(el:HTMLElement, i:number, val:number, o:SpinnerOptions):void; -} +// Type definitions for Spin.js 2.3.2 +// Project: http://fgnass.github.com/spin.js/ +// Definitions by: Boris Yankov , Theodore Brown +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface SpinnerOptions { + lines?: number; // The number of lines to draw + length?: number; // The length of each line + width?: number; // The line thickness + radius?: number; // The radius of the inner circle + corners?: number; // Corner roundness (0..1) + rotate?: number; // The rotation offset + direction?: number; // 1: clockwise, -1: counterclockwise + color?: any; // #rgb or #rrggbb or array of colors + speed?: number; // Rounds per second + trail?: number; // Afterglow percentage + shadow?: boolean; // Whether to render a shadow + hwaccel?: boolean; // Whether to use hardware acceleration + className?: string; // The CSS class to assign to the spinner + zIndex?: number; // The z-index (defaults to 2000000000) + top?: string; // Top position relative to parent in px + left?: string; // Left position relative to parent in px + scale?: number; // Scales overall size of the spinner + opacity?: number; // Opacity of the lines + fps?: number; // Frames per second when using setTimeout() as a fallback for CSS + position?: string; // Element positioning +} + + +declare class Spinner { + /** The Spinner's HTML element - can be used to manually insert the spinner into the DOM */ + public el: HTMLElement; + constructor(options?: SpinnerOptions); + + /** + * Adds the spinner to the given target element. If this instance is already + * spinning, it is automatically removed from its previous target by calling + * stop() internally. + */ + spin(target?: HTMLElement): Spinner; + + /** + * Stops and removes the Spinner. + * Stopped spinners may be reused by calling spin() again. + */ + stop(): Spinner; + lines(el:HTMLElement, o:SpinnerOptions):HTMLElement; + opacity(el:HTMLElement, i:number, val:number, o:SpinnerOptions):void; +} diff --git a/ss-utils/ss-utils-tests.ts b/ss-utils/ss-utils-tests.ts index 5ecaaef96..0282aef21 100644 --- a/ss-utils/ss-utils-tests.ts +++ b/ss-utils/ss-utils-tests.ts @@ -58,12 +58,15 @@ function test_ssutils_Static(){ dateFmt = $.ss.dfmt(new Date(2001,1,1)); dateFmt = $.ss.dfmthm(new Date(2001,1,1)); dateFmt = $.ss.tfmt12(new Date(2001,1,1)); - var parts:string[] = $.ss.splitOnFirst("A,B,C"); - parts = $.ss.splitOnLast("A,B,C"); + var parts:string[] = $.ss.splitOnFirst("A;B;C",";"); + parts = $.ss.splitOnLast("A;B;C", ";"); var selectedText = $.ss.getSelection(); var qs:{ [index: string]: string } = $.ss.queryString("http://google.com?a=b&c=d"); var relativePath = $.ss.createUrl("/path/to/{File}", {File:"file.js"}); var readableText = $.ss.humanize("TheVariableName"); + $.ss.normalizeKey("aAa"); + $.ss.normalize({"AA":1,"bB":2,"C":{"A":11,"B":22},"D":[1,2],"E":[{"A":111,"B":222}]}); + $.ss.normalize({"AA":1,"bB":2,"C":{"A":11,"B":22},"D":[1,2],"E":[{"A":111,"B":222}]}, true); $.ss.parseResponseStatus('{"message":"test"}'); $.ss.postJSON("/path/to/url", {json:"data"}, function(r:any) {}); diff --git a/ss-utils/ss-utils.d.ts b/ss-utils/ss-utils.d.ts index 9154e478f..d86f227c7 100644 --- a/ss-utils/ss-utils.d.ts +++ b/ss-utils/ss-utils.d.ts @@ -17,12 +17,16 @@ declare namespace ssutils { dfmt: (d: Date) => string; dfmthm: (d: Date) => string; tfmt12: (d: Date) => string; - splitOnFirst: (s: string) => string[]; - splitOnLast: (s: string) => string[]; + splitOnFirst: (s: string, delimiter:string) => string[]; + splitOnLast: (s: string, delimiter: string) => string[]; getSelection: () => string; + combinePaths: (...paths:string[]) => string; queryString: (url: string) => { [index: string]: string }; - createUrl: (route: string, args?: any) => string; + createPath: (route: string, args: any) => string; + createUrl: (route: string, args: any) => string; humanize: (s: string) => string; + normalizeKey: (key: string) => string; + normalize: (dto: any, deep?:boolean) => any; parseResponseStatus: (json: string, defaultMsg?: string) => any; postJSON: (url: string, data: Object | String, success?: Function, error?: Function) => any; diff --git a/stack-mapper/stack-mapper-tests.ts b/stack-mapper/stack-mapper-tests.ts index 98dd70ef1..734b7ab3c 100644 --- a/stack-mapper/stack-mapper-tests.ts +++ b/stack-mapper/stack-mapper-tests.ts @@ -1,8 +1,8 @@ -/// - -import stackMapper = require("stack-mapper"); - -var map: any = {}; -var sm: stackMapper.StackMapper = stackMapper(map); -var input: stackMapper.Callsite[] = [{ filename: "boo", line: 1, column: 10 }]; -var cs: stackMapper.Callsite[] = sm.map(input); +/// + +import stackMapper = require("stack-mapper"); + +var map: any = {}; +var sm: stackMapper.StackMapper = stackMapper(map); +var input: stackMapper.Callsite[] = [{ filename: "boo", line: 1, column: 10 }]; +var cs: stackMapper.Callsite[] = sm.map(input); diff --git a/stack-mapper/stack-mapper.d.ts b/stack-mapper/stack-mapper.d.ts index 3426f5b9d..ed0afdf7f 100644 --- a/stack-mapper/stack-mapper.d.ts +++ b/stack-mapper/stack-mapper.d.ts @@ -1,46 +1,46 @@ -// Type definitions for stack-mapper 0.2.2 -// Project: https://github.com/thlorenz/stack-mapper -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "stack-mapper" { - - module stackMapper { - - export class StackMapper { - - /** - * Maps the trace statements of the given error stack and replaces locations - * referencing code in the generated file with the locations inside the original files. - * - * @name map - * @function - * @param {Array} array of callsite objects (see readme for details about Callsite object) - * @return {Array.} info about the error stack with adapted locations, each with the following properties - * - filename: original filename - * - line: origial line in that filename of the trace - * - column: origial column on that line of the trace - */ - public map(stack: Callsite[]): Callsite[]; - } - - export interface Callsite { - filename: string; - line: number; - column: number; - } - - } - - /** - * Returns a Stackmapper that will use the given source map to map error trace locations. - * - * @name stackMapper - * @function - * @param {Object} sourcemap source map for the generated file - * @return {StackMapper} stack mapper for the particular source map - */ - function stackMapper(sourcemap: any): stackMapper.StackMapper; - - export = stackMapper; -} +// Type definitions for stack-mapper 0.2.2 +// Project: https://github.com/thlorenz/stack-mapper +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "stack-mapper" { + + module stackMapper { + + export class StackMapper { + + /** + * Maps the trace statements of the given error stack and replaces locations + * referencing code in the generated file with the locations inside the original files. + * + * @name map + * @function + * @param {Array} array of callsite objects (see readme for details about Callsite object) + * @return {Array.} info about the error stack with adapted locations, each with the following properties + * - filename: original filename + * - line: origial line in that filename of the trace + * - column: origial column on that line of the trace + */ + public map(stack: Callsite[]): Callsite[]; + } + + export interface Callsite { + filename: string; + line: number; + column: number; + } + + } + + /** + * Returns a Stackmapper that will use the given source map to map error trace locations. + * + * @name stackMapper + * @function + * @param {Object} sourcemap source map for the generated file + * @return {StackMapper} stack mapper for the particular source map + */ + function stackMapper(sourcemap: any): stackMapper.StackMapper; + + export = stackMapper; +} diff --git a/state-machine/state-machine-tests.ts b/state-machine/state-machine-tests.ts index 24321fc60..7c7c705e3 100644 --- a/state-machine/state-machine-tests.ts +++ b/state-machine/state-machine-tests.ts @@ -1,30 +1,30 @@ -/// - -interface StateMachineTest extends StateMachine { - warn?: StateMachineEvent; - panic?: StateMachineEvent; - calm?: StateMachineEvent; - clear?: StateMachineEvent; -} - -var fsm: StateMachineTest = StateMachine.create({ - initial: 'green', - events: [ - { name: 'warn', from: 'green', to: 'yellow' }, - { name: 'panic', from: 'yellow', to: 'red' }, - { name: 'calm', from: 'red', to: 'yellow' }, - { name: 'clear', from: 'yellow', to: 'green' } - ], - callbacks: { - onpanic: function (event?, from?, to?, msg?) { alert('panic! ' + msg); }, - onclear: function (event?, from?, to?, msg?) { alert('thanks to ' + msg); }, - ongreen: function (event?, from?, to?) { document.body.className = 'green'; }, - onyellow: function (event?, from?, to?) { document.body.className = 'yellow'; }, - onred: function (event?, from?, to?) { document.body.className = 'red'; }, - } -}); - -//fsm.warn(); // transition from green to yellow -//fsm.panic("ERROR ALERT"); // transition from yellow to red -//fsm.calm(); // transition from red to yellow -//fsm.clear("All clear"); // transition from yellow to green +/// + +interface StateMachineTest extends StateMachine { + warn?: StateMachineEvent; + panic?: StateMachineEvent; + calm?: StateMachineEvent; + clear?: StateMachineEvent; +} + +var fsm: StateMachineTest = StateMachine.create({ + initial: 'green', + events: [ + { name: 'warn', from: 'green', to: 'yellow' }, + { name: 'panic', from: 'yellow', to: 'red' }, + { name: 'calm', from: 'red', to: 'yellow' }, + { name: 'clear', from: 'yellow', to: 'green' } + ], + callbacks: { + onpanic: function (event?, from?, to?, msg?) { alert('panic! ' + msg); }, + onclear: function (event?, from?, to?, msg?) { alert('thanks to ' + msg); }, + ongreen: function (event?, from?, to?) { document.body.className = 'green'; }, + onyellow: function (event?, from?, to?) { document.body.className = 'yellow'; }, + onred: function (event?, from?, to?) { document.body.className = 'red'; }, + } +}); + +//fsm.warn(); // transition from green to yellow +//fsm.panic("ERROR ALERT"); // transition from yellow to red +//fsm.calm(); // transition from red to yellow +//fsm.clear("All clear"); // transition from yellow to green diff --git a/state-machine/state-machine.d.ts b/state-machine/state-machine.d.ts index d17c58dc6..2253cdeec 100644 --- a/state-machine/state-machine.d.ts +++ b/state-machine/state-machine.d.ts @@ -1,83 +1,83 @@ -// Type definitions for Finite State Machine 2.2 -// Project: https://github.com/jakesgordon/javascript-state-machine -// Definitions by: Boris Yankov , Maarten Docter , William Sears -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface StateMachineErrorCallback { - (eventName?: string, from?: string, to?: string, args?: any[], errorCode?: number, errorMessage?: string, ex?: Error): void; // NB. errorCode? See: StateMachine.Error -} - -interface StateMachineEventDef { - name: string; - from: any; // string or string[] - to: string; -} - -interface StateMachineEvent { - (...args: any[]): void; -} - -interface StateMachineConfig { - initial?: any; // string or { state: 'foo', event: 'setup', defer: true|false } - events?: StateMachineEventDef[]; - callbacks?: { - [s: string]: (event?: string, from?: string, to?: string, ...args: any[]) => any; - }; - target?: StateMachine; - error?: StateMachineErrorCallback; -} - -interface StateMachineStatic { - - VERSION: string; // = "2.2.0" - WILDCARD: string; // = '*' - ASYNC: string; // = 'async' - - Result: { - SUCCEEDED: number; // = 1, the event transitioned successfully from one state to another - NOTRANSITION: number; // = 2, the event was successfull but no state transition was necessary - CANCELLED: number; // = 3, the event was cancelled by the caller in a beforeEvent callback - ASYNC: number; // = 4, the event is asynchronous and the caller is in control of when the transition occurs - }; - - Error: { - INVALID_TRANSITION: number; // = 100, caller tried to fire an event that was innapropriate in the current state - PENDING_TRANSITION: number; // = 200, caller tried to fire an event while an async transition was still pending - INVALID_CALLBACK: number; // = 300, caller provided callback function threw an exception - }; - - create(config: StateMachineConfig, target?: StateMachine): StateMachine; -} - -interface StateMachineTransition { - (): void; - cancel(): void; -} - -interface StateMachineIs { - (state: string): boolean; -} - -interface StateMachineCan { - (evt: string): boolean; -} - -interface StateMachine { - current: string; - is: StateMachineIs; - can: StateMachineCan; - cannot: StateMachineCan; - error: StateMachineErrorCallback; - - /* transition - only available when performing async state transitions; otherwise null. Can be a: - [1] fsm.transition(); // called from async callback - [2] fsm.transition.cancel(); - */ - transition: StateMachineTransition; -} - -declare var StateMachine: StateMachineStatic; - -declare module "state-machine" { - export = StateMachine; -} +// Type definitions for Finite State Machine 2.2 +// Project: https://github.com/jakesgordon/javascript-state-machine +// Definitions by: Boris Yankov , Maarten Docter , William Sears +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface StateMachineErrorCallback { + (eventName?: string, from?: string, to?: string, args?: any[], errorCode?: number, errorMessage?: string, ex?: Error): void; // NB. errorCode? See: StateMachine.Error +} + +interface StateMachineEventDef { + name: string; + from: any; // string or string[] + to: string; +} + +interface StateMachineEvent { + (...args: any[]): void; +} + +interface StateMachineConfig { + initial?: any; // string or { state: 'foo', event: 'setup', defer: true|false } + events?: StateMachineEventDef[]; + callbacks?: { + [s: string]: (event?: string, from?: string, to?: string, ...args: any[]) => any; + }; + target?: StateMachine; + error?: StateMachineErrorCallback; +} + +interface StateMachineStatic { + + VERSION: string; // = "2.2.0" + WILDCARD: string; // = '*' + ASYNC: string; // = 'async' + + Result: { + SUCCEEDED: number; // = 1, the event transitioned successfully from one state to another + NOTRANSITION: number; // = 2, the event was successfull but no state transition was necessary + CANCELLED: number; // = 3, the event was cancelled by the caller in a beforeEvent callback + ASYNC: number; // = 4, the event is asynchronous and the caller is in control of when the transition occurs + }; + + Error: { + INVALID_TRANSITION: number; // = 100, caller tried to fire an event that was innapropriate in the current state + PENDING_TRANSITION: number; // = 200, caller tried to fire an event while an async transition was still pending + INVALID_CALLBACK: number; // = 300, caller provided callback function threw an exception + }; + + create(config: StateMachineConfig, target?: StateMachine): StateMachine; +} + +interface StateMachineTransition { + (): void; + cancel(): void; +} + +interface StateMachineIs { + (state: string): boolean; +} + +interface StateMachineCan { + (evt: string): boolean; +} + +interface StateMachine { + current: string; + is: StateMachineIs; + can: StateMachineCan; + cannot: StateMachineCan; + error: StateMachineErrorCallback; + + /* transition - only available when performing async state transitions; otherwise null. Can be a: + [1] fsm.transition(); // called from async callback + [2] fsm.transition.cancel(); + */ + transition: StateMachineTransition; +} + +declare var StateMachine: StateMachineStatic; + +declare module "state-machine" { + export = StateMachine; +} diff --git a/statsd-client/statsd-client-tests.ts b/statsd-client/statsd-client-tests.ts index 6854790e6..2dc6f0144 100644 --- a/statsd-client/statsd-client-tests.ts +++ b/statsd-client/statsd-client-tests.ts @@ -1,57 +1,57 @@ -/// - -import SDC = require("statsd-client"); - -var sdc = new SDC( { host: 'statsd.example.com' }); - -var timer = new Date(); -sdc.increment('some.counter'); // Increment by one. -sdc.gauge('some.gauge', 10); // Set gauge to 10 -sdc.timing('some.timer', timer); // Calculates time diff - -sdc.close(); // Optional - stop NOW - -// Initialization -sdc = new SDC({host: 'statsd.example.com', port: 8124, debug: true}); - -// Counting stuff -sdc.increment('systemname.subsystem.value'); // Increment by one -sdc.decrement('systemname.subsystem.value', -10); // Decrement by 10 -sdc.counter('systemname.subsystem.value', 100); // Increment by 100 - -// Gauges -sdc.gauge('what.you.gauge', 100); -sdc.gaugeDelta('what.you.gauge', 20); // Will now count 120 -sdc.gaugeDelta('what.you.gauge', -70); // Will now count 50 -sdc.gauge('what.you.gauge', 10); // Will now count 10 - -// Set -sdc.set('your.set', 200); - -// Timeouts -var start = new Date(); -setTimeout(function () { - sdc.timing('random.timeout', start); -}, 100 * Math.random()); - -// Stopping gracefully -var start = new Date(); -setTimeout(function () { - sdc.timing('random.timeout', start); // 2 - implicitly re-creates socket. - sdc.close(); // 3 - Closes socket after last use. -}, 100 * Math.random()); -sdc.close(); // 1 - Closes socket early. - -// Prefix magic -// Create generic client -var sdc = new SDC({host: 'statsd.example.com', prefix: 'systemname'}); -sdc.increment('foo'); // Increments 'systemname.foo' -// ... do great stuff ... - -// Subsystem A -var sdcA = sdc.getChildClient('a'); -sdcA.increment('foo'); // Increments 'systemname.a.foo' - -// Subsystem B -var sdcB = sdc.getChildClient('b'); -sdcB.increment('foo'); // Increments 'systemname.b.foo' +/// + +import SDC = require("statsd-client"); + +var sdc = new SDC( { host: 'statsd.example.com' }); + +var timer = new Date(); +sdc.increment('some.counter'); // Increment by one. +sdc.gauge('some.gauge', 10); // Set gauge to 10 +sdc.timing('some.timer', timer); // Calculates time diff + +sdc.close(); // Optional - stop NOW + +// Initialization +sdc = new SDC({host: 'statsd.example.com', port: 8124, debug: true}); + +// Counting stuff +sdc.increment('systemname.subsystem.value'); // Increment by one +sdc.decrement('systemname.subsystem.value', -10); // Decrement by 10 +sdc.counter('systemname.subsystem.value', 100); // Increment by 100 + +// Gauges +sdc.gauge('what.you.gauge', 100); +sdc.gaugeDelta('what.you.gauge', 20); // Will now count 120 +sdc.gaugeDelta('what.you.gauge', -70); // Will now count 50 +sdc.gauge('what.you.gauge', 10); // Will now count 10 + +// Set +sdc.set('your.set', 200); + +// Timeouts +var start = new Date(); +setTimeout(function () { + sdc.timing('random.timeout', start); +}, 100 * Math.random()); + +// Stopping gracefully +var start = new Date(); +setTimeout(function () { + sdc.timing('random.timeout', start); // 2 - implicitly re-creates socket. + sdc.close(); // 3 - Closes socket after last use. +}, 100 * Math.random()); +sdc.close(); // 1 - Closes socket early. + +// Prefix magic +// Create generic client +var sdc = new SDC({host: 'statsd.example.com', prefix: 'systemname'}); +sdc.increment('foo'); // Increments 'systemname.foo' +// ... do great stuff ... + +// Subsystem A +var sdcA = sdc.getChildClient('a'); +sdcA.increment('foo'); // Increments 'systemname.a.foo' + +// Subsystem B +var sdcB = sdc.getChildClient('b'); +sdcB.increment('foo'); // Increments 'systemname.b.foo' diff --git a/statsd-client/statsd-client.d.ts b/statsd-client/statsd-client.d.ts index 86e317afa..08649fe08 100644 --- a/statsd-client/statsd-client.d.ts +++ b/statsd-client/statsd-client.d.ts @@ -1,103 +1,103 @@ -// Type definitions for statsd-client v0.1.0 -// Project: https://github.com/msiebuhr/node-statsd-client -// Definitions by: Peter Kooijmans -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "statsd-client" { - - interface CommonOptions { - /** - * Prefix all stats with this value (default ""). - */ - prefix?: string; - - /** - * Print what is being sent to stderr (default false). - */ - debug?: boolean; - - /** - * User specifically wants to use tcp (default false) - */ - tcp?: boolean; - - /** - * Dual-use timer. Will flush metrics every interval. For UDP, - * it auto-closes the socket after this long without activity - * (default 1000 ms; 0 disables this). For TCP, it auto-closes - * the socket after socketTimeoutsToClose number of timeouts - * have elapsed without activity. - */ - socketTimeout?: number; - } - - interface TcpOptions extends CommonOptions { - /** - * Where to send the stats (default localhost). - */ - host?: string; - - /** - * Port to contact the statsd-daemon on (default 8125). - */ - port?: number; - - /** - * Number of timeouts in which the socket auto-closes if it - * has been inactive. (default 10; 1 to auto-close after a - * single timeout). - */ - socketTimeoutsToClose: number; - } - - interface UdpOptions extends CommonOptions { - /** - * Where to send the stats (default localhost). - */ - host?: string; - - /** - * Port to contact the statsd-daemon on (default 8125). - */ - port?: number; - } - - interface HttpOptions extends CommonOptions { - /** - * Where to send the stats (default localhost). - */ - host?: string; - - /** - * Additional headers to send (default {}). - */ - headers?: { [index : string] : string }; - - /** - * What HTTP method to use (default "PUT"). - */ - method?: string; - } - - class StatsdClient { - constructor(options: TcpOptions | UdpOptions | HttpOptions); - - counter(metric: string, delta: number): void; - increment(metric: string, delta?: number): void; - decrement(metric: string, delta?: number): void; - - gauge(name: string, value: number): void; - gaugeDelta(name: string, delta: number): void; - - set(name: string, value: number): void; - - timing(name: string, start: Date): void; - timing(name: string, duration: number): void; - - close(): void; - - getChildClient(name: string): StatsdClient; - } - - export = StatsdClient; -} +// Type definitions for statsd-client v0.1.0 +// Project: https://github.com/msiebuhr/node-statsd-client +// Definitions by: Peter Kooijmans +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "statsd-client" { + + interface CommonOptions { + /** + * Prefix all stats with this value (default ""). + */ + prefix?: string; + + /** + * Print what is being sent to stderr (default false). + */ + debug?: boolean; + + /** + * User specifically wants to use tcp (default false) + */ + tcp?: boolean; + + /** + * Dual-use timer. Will flush metrics every interval. For UDP, + * it auto-closes the socket after this long without activity + * (default 1000 ms; 0 disables this). For TCP, it auto-closes + * the socket after socketTimeoutsToClose number of timeouts + * have elapsed without activity. + */ + socketTimeout?: number; + } + + interface TcpOptions extends CommonOptions { + /** + * Where to send the stats (default localhost). + */ + host?: string; + + /** + * Port to contact the statsd-daemon on (default 8125). + */ + port?: number; + + /** + * Number of timeouts in which the socket auto-closes if it + * has been inactive. (default 10; 1 to auto-close after a + * single timeout). + */ + socketTimeoutsToClose: number; + } + + interface UdpOptions extends CommonOptions { + /** + * Where to send the stats (default localhost). + */ + host?: string; + + /** + * Port to contact the statsd-daemon on (default 8125). + */ + port?: number; + } + + interface HttpOptions extends CommonOptions { + /** + * Where to send the stats (default localhost). + */ + host?: string; + + /** + * Additional headers to send (default {}). + */ + headers?: { [index : string] : string }; + + /** + * What HTTP method to use (default "PUT"). + */ + method?: string; + } + + class StatsdClient { + constructor(options: TcpOptions | UdpOptions | HttpOptions); + + counter(metric: string, delta: number): void; + increment(metric: string, delta?: number): void; + decrement(metric: string, delta?: number): void; + + gauge(name: string, value: number): void; + gaugeDelta(name: string, delta: number): void; + + set(name: string, value: number): void; + + timing(name: string, start: Date): void; + timing(name: string, duration: number): void; + + close(): void; + + getChildClient(name: string): StatsdClient; + } + + export = StatsdClient; +} diff --git a/swap-case/swap-case.d.ts b/swap-case/swap-case.d.ts index a45aaf650..46e34cfd4 100644 --- a/swap-case/swap-case.d.ts +++ b/swap-case/swap-case.d.ts @@ -1,9 +1,9 @@ -// Type definitions for swap-case -// Project: https://github.com/blakeembrey/swap-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "swap-case" { - function swapCase(string: string, locale?: string): string; - export = swapCase; -} +// Type definitions for swap-case +// Project: https://github.com/blakeembrey/swap-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "swap-case" { + function swapCase(string: string, locale?: string): string; + export = swapCase; +} diff --git a/swiper/swiper-tests.ts.tscparams b/swiper/swiper-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/swiper/swiper-tests.ts.tscparams +++ b/swiper/swiper-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/swiper/swiper.d.ts.tscparams b/swiper/swiper.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/swiper/swiper.d.ts.tscparams +++ b/swiper/swiper.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/swipeview/swipeview-tests.ts b/swipeview/swipeview-tests.ts index 02564e11b..e9781133f 100644 --- a/swipeview/swipeview-tests.ts +++ b/swipeview/swipeview-tests.ts @@ -1,252 +1,252 @@ -/// - -function demo1() { - document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); - -var - el, - i, - page, - dots = document.querySelectorAll('#nav li'), - slides = [ - { - img: 'images/pic01.jpg', - width: 300, - height: 213, - desc: 'Piazza del Duomo, Florence, Italy' - }, - { - img: 'images/pic02.jpg', - width: 300, - height: 164, - desc: 'Tuscan Landscape' - } - ]; - - var gallery = new SwipeView('#wrapper', { numberOfPages: slides.length }); - - // Load initial data - for (i = 0; i < 3; i++) { - page = i == 0 ? slides.length - 1 : i - 1; - el = document.createElement('img'); - el.className = 'loading'; - el.src = slides[page].img; - el.width = slides[page].width; - el.height = slides[page].height; - el.onload = function () { this.className = ''; } - gallery.masterPages[i].appendChild(el); - - el = document.createElement('span'); - el.innerHTML = slides[page].desc; - gallery.masterPages[i].appendChild(el) - } - - gallery.onFlip(function () { - var el, - upcoming, - i; - - for (i = 0; i < 3; i++) { - upcoming = (gallery.masterPages[i].dataset).upcomingPageIndex; - - if (upcoming != (gallery.masterPages[i].dataset).pageIndex) { - el = gallery.masterPages[i].querySelector('img'); - el.className = 'loading'; - el.src = slides[upcoming].img; - el.width = slides[upcoming].width; - el.height = slides[upcoming].height; - - el = gallery.masterPages[i].querySelector('span'); - el.innerHTML = slides[upcoming].desc; - } - } - }); - - gallery.onMoveOut(function () { - gallery.masterPages[gallery.currentMasterPage].className = gallery.masterPages[gallery.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, ''); - }); - - gallery.onMoveIn(function () { - var className = gallery.masterPages[gallery.currentMasterPage].className; - /(^|\s)swipeview-active(\s|$)/.test(className) || (gallery.masterPages[gallery.currentMasterPage].className = !className ? 'swipeview-active' : className + ' swipeview-active'); - }); -} - -function demo2() { -var carousel: SwipeView, - el, - i, - page, - slides = [ - 'Swipe to know more >>>
        Or scroll down for Lorem Ipsum', - '1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.', - '2. A robot must obey the orders given to it by human beings, except where such orders would conflict with the First Law.', - '3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.' - ]; - - carousel = new SwipeView('#wrapper', { - numberOfPages: slides.length, - hastyPageFlip: true - }); - - // Load initial data - for (i = 0; i < 3; i++) { - page = i == 0 ? slides.length - 1 : i - 1; - - el = document.createElement('span'); - el.innerHTML = slides[page]; - carousel.masterPages[i].appendChild(el) - } - - carousel.onFlip(function () { - var el, - upcoming, - i; - - for (i = 0; i < 3; i++) { - upcoming = (carousel.masterPages[i].dataset).upcomingPageIndex; - - if (upcoming != (carousel.masterPages[i].dataset).pageIndex) { - el = carousel.masterPages[i].querySelector('span'); - el.innerHTML = slides[upcoming]; - } - } - }); -} - -function demo3() { - document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); - - window.addEventListener('load', function () { - var ereader: SwipeView, - el, - i, - pageIndex, - pages = [], - req = new XMLHttpRequest(); - - ereader = new SwipeView('#wrapper', { hastyPageFlip: true }); - - // Ajax request - req.open('GET', 'flowers.txt', true); - req.onreadystatechange = function () { - if (req.readyState != 4) return; - - paginate(req.status != 200 && (req.status != 304 ? false : req.responseText)); - - req = null; - } - req.send(null); - - function paginate(book) { - var that = this, - container, - helper, - words = [], - segment, - wordCount = 80, - avgWordCount = 0, - progressTotal = 0, - progressCurrent = 0, - progressMaxWidth = document.getElementById('progressbar').clientWidth, - progressToBookRatio = 0, - progressBar = document.querySelector('#progressbar > span'), - size; - - if (!book) return; - - book = book.replace(/\n\n/g, '

        ').replace(/\n/g, ' '); - progressTotal = book.length; - progressToBookRatio = progressMaxWidth / book.length; - - container = document.createElement('div'); - container.style.visibility = 'hidden'; - container.innerHTML = '
        '; - ereader.slider.appendChild(container); - helper = document.getElementById('ereader-helper'); - helper.innerHTML = ''; - - var loopy = function () { - words = book.split(' ', wordCount); - segment = words.join(' '); - helper.innerHTML = segment; - - if (helper.offsetHeight > ereader.wrapperHeight) { - if (size == -1) { - words.pop(); - segment = words.join(' '); - - pages.push(segment); - book = book.substr(segment.length); - avgWordCount = Math.round((wordCount + avgWordCount) / 2); - wordCount = avgWordCount; - size = 0; - progressTotal -= segment.length; - } else { - size = 1; - wordCount--; - } - } else { - if (size == 1) { - pages.push(segment); - book = book.substr(segment.length); - avgWordCount = Math.round((wordCount + avgWordCount) / 2); - wordCount = avgWordCount; - size = 0; - progressTotal -= segment.length; - } else { - if (segment == book) { - pages.push(segment); - book = ''; - } - - size = -1; - wordCount++; - } - } - - if (book) { - progressBar.style.width = 150 - Math.round(progressToBookRatio * progressTotal) + 'px'; - setTimeout(loopy, 1); - } else { - book = null; - words = null; - segment = null; - helper.innerHTML = ''; - ereader.slider.removeChild(container); - - ereader.updatePageCount(pages.length); - (ereader.masterPages[0].dataset).pageIndex = pages.length - 1; - (ereader.masterPages[0].dataset).upcomingPageIndex = (ereader.masterPages[0].dataset).pageIndex; - - // Load initial data - for (i = 0; i < 3; i++) { - pageIndex = i == 0 ? pages.length - 1 : i - 1; - el = document.createElement('div'); - el.innerHTML = pages[pageIndex]; - ereader.masterPages[i].appendChild(el) - } - - document.getElementById('loading').style.display = 'none'; - } - } - - loopy(); - } - - ereader.onFlip(function () { - var el, - upcoming, - i; - - for (i = 0; i < 3; i++) { - upcoming = (ereader.masterPages[i].dataset).upcomingPageIndex; - - if (upcoming != (ereader.masterPages[i].dataset).pageIndex) { - el = ereader.masterPages[i].querySelector('div'); - el.innerHTML = pages[upcoming]; - } - } - }); - }, false); +/// + +function demo1() { + document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); + +var + el, + i, + page, + dots = document.querySelectorAll('#nav li'), + slides = [ + { + img: 'images/pic01.jpg', + width: 300, + height: 213, + desc: 'Piazza del Duomo, Florence, Italy' + }, + { + img: 'images/pic02.jpg', + width: 300, + height: 164, + desc: 'Tuscan Landscape' + } + ]; + + var gallery = new SwipeView('#wrapper', { numberOfPages: slides.length }); + + // Load initial data + for (i = 0; i < 3; i++) { + page = i == 0 ? slides.length - 1 : i - 1; + el = document.createElement('img'); + el.className = 'loading'; + el.src = slides[page].img; + el.width = slides[page].width; + el.height = slides[page].height; + el.onload = function () { this.className = ''; } + gallery.masterPages[i].appendChild(el); + + el = document.createElement('span'); + el.innerHTML = slides[page].desc; + gallery.masterPages[i].appendChild(el) + } + + gallery.onFlip(function () { + var el, + upcoming, + i; + + for (i = 0; i < 3; i++) { + upcoming = (gallery.masterPages[i].dataset).upcomingPageIndex; + + if (upcoming != (gallery.masterPages[i].dataset).pageIndex) { + el = gallery.masterPages[i].querySelector('img'); + el.className = 'loading'; + el.src = slides[upcoming].img; + el.width = slides[upcoming].width; + el.height = slides[upcoming].height; + + el = gallery.masterPages[i].querySelector('span'); + el.innerHTML = slides[upcoming].desc; + } + } + }); + + gallery.onMoveOut(function () { + gallery.masterPages[gallery.currentMasterPage].className = gallery.masterPages[gallery.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, ''); + }); + + gallery.onMoveIn(function () { + var className = gallery.masterPages[gallery.currentMasterPage].className; + /(^|\s)swipeview-active(\s|$)/.test(className) || (gallery.masterPages[gallery.currentMasterPage].className = !className ? 'swipeview-active' : className + ' swipeview-active'); + }); +} + +function demo2() { +var carousel: SwipeView, + el, + i, + page, + slides = [ + 'Swipe to know more >>>
        Or scroll down for Lorem Ipsum', + '1. A robot may not injure a human being or, through inaction, allow a human being to come to harm.', + '2. A robot must obey the orders given to it by human beings, except where such orders would conflict with the First Law.', + '3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws.' + ]; + + carousel = new SwipeView('#wrapper', { + numberOfPages: slides.length, + hastyPageFlip: true + }); + + // Load initial data + for (i = 0; i < 3; i++) { + page = i == 0 ? slides.length - 1 : i - 1; + + el = document.createElement('span'); + el.innerHTML = slides[page]; + carousel.masterPages[i].appendChild(el) + } + + carousel.onFlip(function () { + var el, + upcoming, + i; + + for (i = 0; i < 3; i++) { + upcoming = (carousel.masterPages[i].dataset).upcomingPageIndex; + + if (upcoming != (carousel.masterPages[i].dataset).pageIndex) { + el = carousel.masterPages[i].querySelector('span'); + el.innerHTML = slides[upcoming]; + } + } + }); +} + +function demo3() { + document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); + + window.addEventListener('load', function () { + var ereader: SwipeView, + el, + i, + pageIndex, + pages = [], + req = new XMLHttpRequest(); + + ereader = new SwipeView('#wrapper', { hastyPageFlip: true }); + + // Ajax request + req.open('GET', 'flowers.txt', true); + req.onreadystatechange = function () { + if (req.readyState != 4) return; + + paginate(req.status != 200 && (req.status != 304 ? false : req.responseText)); + + req = null; + } + req.send(null); + + function paginate(book) { + var that = this, + container, + helper, + words = [], + segment, + wordCount = 80, + avgWordCount = 0, + progressTotal = 0, + progressCurrent = 0, + progressMaxWidth = document.getElementById('progressbar').clientWidth, + progressToBookRatio = 0, + progressBar = document.querySelector('#progressbar > span'), + size; + + if (!book) return; + + book = book.replace(/\n\n/g, '

        ').replace(/\n/g, ' '); + progressTotal = book.length; + progressToBookRatio = progressMaxWidth / book.length; + + container = document.createElement('div'); + container.style.visibility = 'hidden'; + container.innerHTML = '
        '; + ereader.slider.appendChild(container); + helper = document.getElementById('ereader-helper'); + helper.innerHTML = ''; + + var loopy = function () { + words = book.split(' ', wordCount); + segment = words.join(' '); + helper.innerHTML = segment; + + if (helper.offsetHeight > ereader.wrapperHeight) { + if (size == -1) { + words.pop(); + segment = words.join(' '); + + pages.push(segment); + book = book.substr(segment.length); + avgWordCount = Math.round((wordCount + avgWordCount) / 2); + wordCount = avgWordCount; + size = 0; + progressTotal -= segment.length; + } else { + size = 1; + wordCount--; + } + } else { + if (size == 1) { + pages.push(segment); + book = book.substr(segment.length); + avgWordCount = Math.round((wordCount + avgWordCount) / 2); + wordCount = avgWordCount; + size = 0; + progressTotal -= segment.length; + } else { + if (segment == book) { + pages.push(segment); + book = ''; + } + + size = -1; + wordCount++; + } + } + + if (book) { + progressBar.style.width = 150 - Math.round(progressToBookRatio * progressTotal) + 'px'; + setTimeout(loopy, 1); + } else { + book = null; + words = null; + segment = null; + helper.innerHTML = ''; + ereader.slider.removeChild(container); + + ereader.updatePageCount(pages.length); + (ereader.masterPages[0].dataset).pageIndex = pages.length - 1; + (ereader.masterPages[0].dataset).upcomingPageIndex = (ereader.masterPages[0].dataset).pageIndex; + + // Load initial data + for (i = 0; i < 3; i++) { + pageIndex = i == 0 ? pages.length - 1 : i - 1; + el = document.createElement('div'); + el.innerHTML = pages[pageIndex]; + ereader.masterPages[i].appendChild(el) + } + + document.getElementById('loading').style.display = 'none'; + } + } + + loopy(); + } + + ereader.onFlip(function () { + var el, + upcoming, + i; + + for (i = 0; i < 3; i++) { + upcoming = (ereader.masterPages[i].dataset).upcomingPageIndex; + + if (upcoming != (ereader.masterPages[i].dataset).pageIndex) { + el = ereader.masterPages[i].querySelector('div'); + el.innerHTML = pages[upcoming]; + } + } + }); + }, false); } \ No newline at end of file diff --git a/swipeview/swipeview-tests.ts.tscparams b/swipeview/swipeview-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/swipeview/swipeview-tests.ts.tscparams +++ b/swipeview/swipeview-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/swipeview/swipeview.d.ts b/swipeview/swipeview.d.ts index 8e079fa7d..d45404712 100644 --- a/swipeview/swipeview.d.ts +++ b/swipeview/swipeview.d.ts @@ -1,43 +1,43 @@ -// Type definitions for SwipeView 1.0 -// Project: http://cubiq.org/swipeview -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -interface SwipeViewEvent { - (fn: Function): void; -} - -interface SwipeViewOptions { - text?: string; - numberOfPages?: number; - snapThreshold?: number; - hastyPageFlip?: boolean; - loop?: boolean; -} - -declare class SwipeView { - - masterPages: HTMLElement[]; - currentMasterPage: number; - wrapper: HTMLElement; - slider: HTMLElement; - - constructor (element: string); - constructor (element: string, options: SwipeViewOptions); - - destroy(): void; - refreshSize(): void; - updatePageCount(n: number): void; - goToPage(p: number): void; - next(): void; - prev(): void; - handleEvent(e: Event): void; - - onFlip: SwipeViewEvent; - onMoveOut: SwipeViewEvent; - onMoveIn: SwipeViewEvent; - onTouchStart: SwipeViewEvent; - - wrapperHeight: number; +// Type definitions for SwipeView 1.0 +// Project: http://cubiq.org/swipeview +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface SwipeViewEvent { + (fn: Function): void; +} + +interface SwipeViewOptions { + text?: string; + numberOfPages?: number; + snapThreshold?: number; + hastyPageFlip?: boolean; + loop?: boolean; +} + +declare class SwipeView { + + masterPages: HTMLElement[]; + currentMasterPage: number; + wrapper: HTMLElement; + slider: HTMLElement; + + constructor (element: string); + constructor (element: string, options: SwipeViewOptions); + + destroy(): void; + refreshSize(): void; + updatePageCount(n: number): void; + goToPage(p: number): void; + next(): void; + prev(): void; + handleEvent(e: Event): void; + + onFlip: SwipeViewEvent; + onMoveOut: SwipeViewEvent; + onMoveIn: SwipeViewEvent; + onTouchStart: SwipeViewEvent; + + wrapperHeight: number; } \ No newline at end of file diff --git a/tedious/tedious-tests.ts b/tedious/tedious-tests.ts index f7346a174..bbfdb7629 100644 --- a/tedious/tedious-tests.ts +++ b/tedious/tedious-tests.ts @@ -1,34 +1,34 @@ - -/// - -"use strict"; - -import tedious = require("tedious"); - -var config: tedious.ConnectionConfig = { - userName: "rogier", - password: "rogiers password", - server: "127.0.0.1", - options: { - database: "somedb", - instanceName: "someinstance", - } -} - -var connection = new tedious.Connection(config); -connection.on("connect", (): void => { - console.log("hurray"); -}); - -connection.beginTransaction((error: Error): void => {}, "some name"); -connection.rollbackTransaction((error: Error): void => {}); -connection.commitTransaction((error: Error): void => {}); - - -var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => { -}); -request.on("row", (row: tedious.ColumnValue[]): void => { -}); -connection.execSql(request); - - + +/// + +"use strict"; + +import tedious = require("tedious"); + +var config: tedious.ConnectionConfig = { + userName: "rogier", + password: "rogiers password", + server: "127.0.0.1", + options: { + database: "somedb", + instanceName: "someinstance", + } +} + +var connection = new tedious.Connection(config); +connection.on("connect", (): void => { + console.log("hurray"); +}); + +connection.beginTransaction((error: Error): void => {}, "some name"); +connection.rollbackTransaction((error: Error): void => {}); +connection.commitTransaction((error: Error): void => {}); + + +var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => { +}); +request.on("row", (row: tedious.ColumnValue[]): void => { +}); +connection.execSql(request); + + diff --git a/tedious/tedious.d.ts b/tedious/tedious.d.ts index db317a353..71f46f1c7 100644 --- a/tedious/tedious.d.ts +++ b/tedious/tedious.d.ts @@ -1,526 +1,526 @@ -// Type definitions for tedious 1.8.0 -// Project: https://pekim.github.io/tedious -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module 'tedious' { - - import events = require("events"); - - export interface ColumnType { - /** - * The column's type, such as VarChar, Int or Binary. - */ - name: string; - } - - export interface ColumnMetaData { - /** - * The column's name - */ - colName: string; - - /** - * The column type. - */ - type: ColumnType; - - /** - * The precision. Only applicable to numeric and decimal. - */ - precision?: number; - - /** - * The scale. Only applicable to numeric, decimal, time, datetime2 and datetimeoffset. - */ - scale?: number; - - /** - * The length, for char, varchar, nvarchar and varbinary. - */ - dataLength?: number; - } - - export interface DebugOptions { - /** - * A boolean, controlling whether debug events will be emitted with text describing packet details (default: false). - */ - packet?: boolean; - - /** - * A boolean, controlling whether debug events will be emitted with text describing packet data details (default: false). - */ - data?: boolean; - - /** - * A boolean, controlling whether debug events will be emitted with text describing packet payload details (default: false). - */ - payload?: boolean; - - /** - * A boolean, controlling whether debug events will be emitted with text describing token stream tokens (default: false). - */ - token?: boolean; - } - - export enum ISOLATION_LEVEL { - NO_CHANGE = 0x00, - READ_UNCOMMITTED = 0x01, - READ_COMMITTED = 0x02, - REPEATABLE_READ = 0x03, - SERIALIZABLE = 0x04, - SNAPSHOT = 0x05 - } - - /** - * Unfortunately these aren't valid JavaScript identifiers - * so I cannot list the values here as enum values - 7_1 = 0x71000001, - 7_2 = 0x72090002, - 7_3_A = 0x730A0003, - 7_3_B = 0x730B0003, - 7_4 = 0x74000004 - */ - export var TDS_VERSION: { [index: string]: number }; - - export interface TediousType { - type: string; - name: string; - } - - export interface TediousTypes { - BigInt: TediousType; - Binary: TediousType; - Bit: TediousType; - BitN: TediousType; - Char: TediousType; - DateN: TediousType; - DateTime2N: TediousType; - DateTime: TediousType; - DateTimeN: TediousType; - DateTimeOffsetN: TediousType; - Decimal: TediousType; - DecimalN: TediousType; - Float: TediousType; - FloatN: TediousType; - Image: TediousType; - Int: TediousType; - IntN: TediousType; - Money: TediousType; - MoneyN: TediousType; - NChar: TediousType; - NText: TediousType; - NVarChar: TediousType; - Null: TediousType; - Numeric: TediousType; - NumericN: TediousType; - Real: TediousType; - SmallDateTime: TediousType; - SmallInt : TediousType; - SmallMoney: TediousType; - TVP: TediousType; - Text: TediousType; - TimeN: TediousType; - TinyInt: TediousType; - UDT: TediousType; - UniqueIdentifierN: TediousType; - VarBinary: TediousType; - VarChar: TediousType; - Xml: TediousType; - } - - export var TYPES: TediousTypes; - - export interface ConnectionOptions { - - /** - * Port to connect to (default: 1433). Mutually exclusive with options.instanceName. - */ - port?: number; - - /** - * The instance name to connect to. The SQL Server Browser service must be running on the database server, - * and UDP port 1444 on the database server must be reachable. (no default) Mutually exclusive with options.port. - */ - instanceName?: string; - - /** - * Database to connect to (default: dependent on server configuration). - */ - database?: string; - - /** - * By default, if the database requestion by options.database cannot be accessed, - * the connection will fail with an error. However, if options.fallbackToDefaultDb is set to true, - * then the user's default database will be * used instead (Default: false). - */ - fallbackToDefaultDb?: boolean; - - /** - * The number of milliseconds before the attempt to connect is considered failed (default: 15000). - */ - connectTimeout?: number; - - /** - * The number of milliseconds before a request is considered failed, or 0 for no timeout (default: 15000). - */ - requestTimeout?: number; - - /** - * The number of milliseconds before the cancel (abort) of a request is considered failed (default: 5000). - */ - cancelTimeout?: number; - - /** - * The size of TDS packets (subject to negotiation with the server). Should be a power of 2. (default: 4096). - */ - packetSize?: number; - - /** - * A boolean determining whether to pass time values in UTC or local time. (default: true). - */ - useUTC?: boolean; - - /** - * A boolean determining whether to rollback a transaction automatically if any error is encountered - * during the given transaction's execution. This sets the value for SET XACT_ABORT during the initial - * SQL phase of a connection (documentation). - */ - abortTransactionOnError?: boolean; - - /** - * A string indicating which network interface (ip addres) to use when connecting to SQL Server. - */ - localAddress?: string; - - /** - * A boolean determining whether to return rows as arrays or key-value collections. (default: false). - */ - useColumnNames?: boolean; - - /** - * A boolean, controlling whether the column names returned will have the first letter converted - * to lower case (true) or not. This value is ignored if you provide a columnNameReplacer. (default: false). - */ - camelCaseColumns?: boolean; - - /** - * A function with parameters (columnName, index, columnMetaData) and returning a string. If provided, - * this will be called once per column per result-set. The returned value will be used instead of the - * SQL-provided column name on row and meta data objects. This allows you to dynamically convert between - * naming conventions. (default: null). - */ - columnNameReplacer?: (columnName: string, index: number, columnMetaData: ColumnMetaData) => string; - - /** - * Debug options - */ - debug?: DebugOptions; - - /** - * The default isolation level that transactions will be run with. (default: READ_COMMITED). - */ - isolationLevel?: ISOLATION_LEVEL; - - /** - * The default isolation level for new connections. All out-of-transaction queries are executed with this setting. (default: READ_COMMITED) - */ - connectionIsolationLevel?: ISOLATION_LEVEL; - - /** - * A boolean, determining whether the connection will request read only access from a SQL Server Availability Group. For more information, see here. (default: false). - */ - readOnlyIntent?: boolean; - - /** - * A boolean determining whether or not the connection will be encrypted. Set to true if you're on Windows Azure. (default: false). - */ - encrypt?: boolean; - - /** - * When encryption is used, an object may be supplied that will be used for the first argument when calling tls.createSecurePair (default: {}). - */ - cryptoCredentialsDetails?: Object; - - /** - * A boolean, that when true will expose received rows in Requests' done* events. See done, doneInProc and doneProc. (default: false) - * Caution: If many row are received, enabling this option could result in excessive memory usage. - */ - rowCollectionOnDone?: boolean; - - /** - * A boolean, that when true will expose received rows in Requests' completion callback. See new Request. (default: false) - * Caution: If many row are received, enabling this option could result in excessive memory usage. - */ - rowCollectionOnRequestCompletion?: boolean; - - /** - * The version of TDS to use. If server doesn't support specified version, negotiated version is used instead. (default: 7_4). - * Take this from tedious.TDS_VERSION.7_4 . - */ - tdsVersion?: number; - } - - export interface ConnectionConfig { - /** - * User name to use for authentication. - */ - userName?: string; - - /** - * Password to use for authentication. - */ - password?: string; - - /** - * Hostname to connect to. - */ - server?: string; - - /** - * Once you set domain, driver will connect to SQL Server using domain login. - */ - domain?: string; - - /** - * Further options - */ - options?: ConnectionOptions; - } - - export interface ParameterOptions { - // for VarChar, NVarChar, VarBinary - length?: number; - // precision for Numeric, Decimal - precision?: number; - // scale for Numeric, Decimal, Time, DateTime2, DateTimeOffset - scale?: number; - } - - /** - * Type of each column in the Request#row event - */ - export interface ColumnValue { - metadata: ColumnMetaData; - value: any; - } - - /** - * A Request instance represents a request that can be executed on a connection - * @event 'columnMetadata' This event, describing result set columns, will be emitted before row events are emitted. This event may be emited multiple times when more than one recordset is produced by the statement. - * @event 'row' A row resulting from execution of the SQL statement - * @event 'done' All rows from a result set have been provided (through row events). This token is used to indicate the completion of a SQL statement. As multiple SQL statements can be sent to the server in a single SQL batch, multiple done events can be generated. An done event is emited for each SQL statement in the SQL batch except variable declarations. For execution of SQL statements within stored procedures, doneProc and doneInProc events are used in place of done events. - * @event 'doneInProc' Indicates the completion status of a SQL statement within a stored procedure. All rows from a statement in a stored procedure have been provided (through row events). - * @event 'doneProc' Indicates the completion status of a stored procedure. This is also generated for stored procedures executed through SQL statements. - * @event 'returnValue' A value for an output parameter (that was added to the request with addOutputParameter(...)). See also Using Parameters. - */ - export class Request extends events.EventEmitter { - - /** - * Constructor - * @param sql The SQL statement to be executed (or a procedure name, if the request is to be used with connection.callProcedure). - * @param callback The callback is called when the request has completed, either successfully or with an error. If an error occurs during execution of the statement(s), then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - * rowCount: The number of rows emitted as result of executing the SQL statement. - * rows: Rows as a result of executing the SQL statement. Will only be avaiable if Connection's config.options.rowCollectionOnRequestCompletion is true. - */ - constructor(sql: string, callback: (error: Error, rowCount: number, rows: any[]) => void); - - /** - * Add an input parameter to the request. - * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. The name should not start '@'. - * @param type One of the supported data types. - * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. - * @param options Additional type options. Optional. - */ - addParameter(name: string, type: TediousType, value: any, options?: ParameterOptions): void; - - /** - * Add an output parameter to the request. The parameter's value will be provide by an emitted returnValue event. - * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. - * @param type One of the supported data types. - * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. Optional. - * @param options Additional type options. Optional. - */ - addOutputParameter(name: string, type: TediousType, value?: any, options?: ParameterOptions): void; - } - - export interface BulkLoadColumnOpts extends ParameterOptions { - // indicates whether the column accepts NULL values. - nullable: boolean; - // If the name of the column is different from the name of the property found on rowObj arguments passed to , then you can use this option to specify the property name. - objName?: string; - } - - export interface BulkLoad { - - /** - * Adds a column to the bulk load. The column definitions should match the table you are trying to insert into. Attempting to call addColumn after the first row has been added will throw an exception. - * @param name The name of the column. - * @param type One of the supported data types. - * @param options Additional column type information. At a minimum, nullable must be set to true or false. - */ - addColumn(name: string, type: TediousType, options: BulkLoadColumnOpts): void; - - /** - * Adds a row to the bulk insert. This method accepts arguments in three different formats: - * @param rowObj An object of key/value pairs representing column name (or objName) and value. - */ - addRow(row: Object): void; - /** - * Adds a row to the bulk insert. This method accepts arguments in three different formats: - * @param columnArray An array representing the values of each column in the same order which they were added to the bulkLoad object. - */ - addRow(columnArray: any[]): void; - /** - * Adds a row to the bulk insert. This method accepts arguments in three different formats: - * @param args If there are at least two columns, values can be passed as multiple arguments instead of an array. They must be in the same order the columns were added in. - */ - addRow(...args: any[]): void; - - /** - * This is simply a helper utility function which returns a CREATE TABLE SQL statement based on the columns added to the bulkLoad object. This may be particularly handy when you want to insert into a temporary table (a table which starts with #). A side note on bulk inserting into temporary tables: if you want to access a local temporary table after executing the bulk load, you'll need to use the same connection and execute your requests using connection.execSqlBatch instead of .execSql. - */ - getTableCreationSql(): string; - } - - /** - * message interface used by the infoMessage and errorMessage events of Connection - */ - export interface InfoObject { - /** - * Error number - */ - number: number; - /** - * The error state, used as a modifier to the error number. - */ - state: any; - /** - * The class (severity) of the error. A class of less than 10 indicates an informational message. - */ - class: number; - /** - * The message text. - */ - message: string; - /** - * The stored procedure name (if a stored procedure generated the message). - */ - procName: string; - /** - * The line number in the SQL batch or stored procedure that caused the error. Line numbers begin at 1; therefore, if the line number is not applicable to the message, the value of LineNumber will be 0. - */ - lineNumber: number; - } - - /** - * Connection - * @event 'connect' The attempt to connect and validate has completed. - * @event 'end' The connection has ended. This may be as a result of the client calling close(), the server closing the connection, or a network error. - * @event 'error' Internal error occurs. - * @event 'debug' A debug message is available. It may be logged or ignored. - * @event 'infoMessage' The server has issued an information message. - * @event 'errorMessage' The server has issued an error message. - * @event 'databaseChange' The server has reported that the active database has changed. This may be as a result of a sucessful login, or a use statement. - * @event 'languageChange' The server has reported that the language has changed. - * @event 'charsetChange' The server has reported that the charset has changed. - * @event 'secure' A secure connection has been established. - */ - export class Connection extends events.EventEmitter { - - constructor(config: ConnectionConfig); - - /** - * Start a transaction. As only one request at a time may be executed on - * a connection, another request should not be initiated until this callback is called. - * @param callback The callback is called when the request to start the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. - * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present. - * @param isolationLevel The isolation level that the transaction is to be run with. - */ - beginTransaction(callback: (error?: Error) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; - - /** - * Commit a transaction. - * There should be an active transaction. That is, beginTransaction should have been previously called. - * @param callback The callback is called when the request to commit the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - */ - commitTransaction(callback: (error: Error) => void): void; - - /** - * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. - * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - */ - rollbackTransaction(callback: (error: Error) => void): void; - - /** - * Prepare the SQL represented by the request. The request can then be used in subsequent calls to execute and unprepare - * @param request A Request object representing the request. Parameters only require a name and type. Parameter values are ignored. - */ - prepare(request: Request): void; - - /** - * Release the SQL Server resources associated with a previously prepared request. - */ - unprepare(request: Request): void; - - /** - * Call a stored procedure represented by request. - */ - callProcedure(request: Request): void; - - /** - * Execute the SQL represented by request. - * As sp_executesql is used to execute the SQL, if the same SQL is executed multiples times using this function, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution. - * Beware of the way that scoping rules apply, and how they may affect local temp tables. If you're running in to scoping issues, then execSqlBatch may be a better choice. See also issue #24. - */ - execSql(request: Request): void; - - /** - * Execute the SQL batch represented by request. There is no param support, and unlike execSql, it is not likely that SQL Server will reuse the execution plan it generates for the SQL. - * In almost all cases, execSql will be a better choice. - */ - execSqlBatch(request: Request): void; - - /** - * Execute previously prepared SQL, using the supplied parameters. - * @param request A previously prepared Request. - * @param parameters An object whose names correspond to the names of parameters that were added to the request before it was prepared. The object's values are passed as the parameters' values when the request is executed. - */ - execute(request: Request, parameters: {}): void; - - /** - * Creates a new BulkLoad instance. - * @param tableName The name of the table to bulk-insert into. - * @param callback A function which will be called after the BulkLoad finishes executing. rowCount will equal the number of rows inserted. - */ - newBulkLoad(tableName: string, callback: (error: Error, rowCount: number) => void): BulkLoad; - - /** - * Executes a BulkLoad. - */ - execBulkLoad(bulkLoad: BulkLoad): void; - - /** - * Reset the connection to its initial state. Can be useful for connection pool implementations. - * @param callback The callback is called when the connection reset has completed, either successfully or with an error. If an error occured then err will describe the error. - * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. - */ - reset(callback: (error: Error) => void): void; - - /** - * Cancel currently executed request. - */ - cancel(): void; - - /** - * Closes the connection to the database. The end will be emmited once the connection has been closed. - */ - close(): void; - - } -} +// Type definitions for tedious 1.8.0 +// Project: https://pekim.github.io/tedious +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'tedious' { + + import events = require("events"); + + export interface ColumnType { + /** + * The column's type, such as VarChar, Int or Binary. + */ + name: string; + } + + export interface ColumnMetaData { + /** + * The column's name + */ + colName: string; + + /** + * The column type. + */ + type: ColumnType; + + /** + * The precision. Only applicable to numeric and decimal. + */ + precision?: number; + + /** + * The scale. Only applicable to numeric, decimal, time, datetime2 and datetimeoffset. + */ + scale?: number; + + /** + * The length, for char, varchar, nvarchar and varbinary. + */ + dataLength?: number; + } + + export interface DebugOptions { + /** + * A boolean, controlling whether debug events will be emitted with text describing packet details (default: false). + */ + packet?: boolean; + + /** + * A boolean, controlling whether debug events will be emitted with text describing packet data details (default: false). + */ + data?: boolean; + + /** + * A boolean, controlling whether debug events will be emitted with text describing packet payload details (default: false). + */ + payload?: boolean; + + /** + * A boolean, controlling whether debug events will be emitted with text describing token stream tokens (default: false). + */ + token?: boolean; + } + + export enum ISOLATION_LEVEL { + NO_CHANGE = 0x00, + READ_UNCOMMITTED = 0x01, + READ_COMMITTED = 0x02, + REPEATABLE_READ = 0x03, + SERIALIZABLE = 0x04, + SNAPSHOT = 0x05 + } + + /** + * Unfortunately these aren't valid JavaScript identifiers + * so I cannot list the values here as enum values + 7_1 = 0x71000001, + 7_2 = 0x72090002, + 7_3_A = 0x730A0003, + 7_3_B = 0x730B0003, + 7_4 = 0x74000004 + */ + export var TDS_VERSION: { [index: string]: number }; + + export interface TediousType { + type: string; + name: string; + } + + export interface TediousTypes { + BigInt: TediousType; + Binary: TediousType; + Bit: TediousType; + BitN: TediousType; + Char: TediousType; + DateN: TediousType; + DateTime2N: TediousType; + DateTime: TediousType; + DateTimeN: TediousType; + DateTimeOffsetN: TediousType; + Decimal: TediousType; + DecimalN: TediousType; + Float: TediousType; + FloatN: TediousType; + Image: TediousType; + Int: TediousType; + IntN: TediousType; + Money: TediousType; + MoneyN: TediousType; + NChar: TediousType; + NText: TediousType; + NVarChar: TediousType; + Null: TediousType; + Numeric: TediousType; + NumericN: TediousType; + Real: TediousType; + SmallDateTime: TediousType; + SmallInt : TediousType; + SmallMoney: TediousType; + TVP: TediousType; + Text: TediousType; + TimeN: TediousType; + TinyInt: TediousType; + UDT: TediousType; + UniqueIdentifierN: TediousType; + VarBinary: TediousType; + VarChar: TediousType; + Xml: TediousType; + } + + export var TYPES: TediousTypes; + + export interface ConnectionOptions { + + /** + * Port to connect to (default: 1433). Mutually exclusive with options.instanceName. + */ + port?: number; + + /** + * The instance name to connect to. The SQL Server Browser service must be running on the database server, + * and UDP port 1444 on the database server must be reachable. (no default) Mutually exclusive with options.port. + */ + instanceName?: string; + + /** + * Database to connect to (default: dependent on server configuration). + */ + database?: string; + + /** + * By default, if the database requestion by options.database cannot be accessed, + * the connection will fail with an error. However, if options.fallbackToDefaultDb is set to true, + * then the user's default database will be * used instead (Default: false). + */ + fallbackToDefaultDb?: boolean; + + /** + * The number of milliseconds before the attempt to connect is considered failed (default: 15000). + */ + connectTimeout?: number; + + /** + * The number of milliseconds before a request is considered failed, or 0 for no timeout (default: 15000). + */ + requestTimeout?: number; + + /** + * The number of milliseconds before the cancel (abort) of a request is considered failed (default: 5000). + */ + cancelTimeout?: number; + + /** + * The size of TDS packets (subject to negotiation with the server). Should be a power of 2. (default: 4096). + */ + packetSize?: number; + + /** + * A boolean determining whether to pass time values in UTC or local time. (default: true). + */ + useUTC?: boolean; + + /** + * A boolean determining whether to rollback a transaction automatically if any error is encountered + * during the given transaction's execution. This sets the value for SET XACT_ABORT during the initial + * SQL phase of a connection (documentation). + */ + abortTransactionOnError?: boolean; + + /** + * A string indicating which network interface (ip addres) to use when connecting to SQL Server. + */ + localAddress?: string; + + /** + * A boolean determining whether to return rows as arrays or key-value collections. (default: false). + */ + useColumnNames?: boolean; + + /** + * A boolean, controlling whether the column names returned will have the first letter converted + * to lower case (true) or not. This value is ignored if you provide a columnNameReplacer. (default: false). + */ + camelCaseColumns?: boolean; + + /** + * A function with parameters (columnName, index, columnMetaData) and returning a string. If provided, + * this will be called once per column per result-set. The returned value will be used instead of the + * SQL-provided column name on row and meta data objects. This allows you to dynamically convert between + * naming conventions. (default: null). + */ + columnNameReplacer?: (columnName: string, index: number, columnMetaData: ColumnMetaData) => string; + + /** + * Debug options + */ + debug?: DebugOptions; + + /** + * The default isolation level that transactions will be run with. (default: READ_COMMITED). + */ + isolationLevel?: ISOLATION_LEVEL; + + /** + * The default isolation level for new connections. All out-of-transaction queries are executed with this setting. (default: READ_COMMITED) + */ + connectionIsolationLevel?: ISOLATION_LEVEL; + + /** + * A boolean, determining whether the connection will request read only access from a SQL Server Availability Group. For more information, see here. (default: false). + */ + readOnlyIntent?: boolean; + + /** + * A boolean determining whether or not the connection will be encrypted. Set to true if you're on Windows Azure. (default: false). + */ + encrypt?: boolean; + + /** + * When encryption is used, an object may be supplied that will be used for the first argument when calling tls.createSecurePair (default: {}). + */ + cryptoCredentialsDetails?: Object; + + /** + * A boolean, that when true will expose received rows in Requests' done* events. See done, doneInProc and doneProc. (default: false) + * Caution: If many row are received, enabling this option could result in excessive memory usage. + */ + rowCollectionOnDone?: boolean; + + /** + * A boolean, that when true will expose received rows in Requests' completion callback. See new Request. (default: false) + * Caution: If many row are received, enabling this option could result in excessive memory usage. + */ + rowCollectionOnRequestCompletion?: boolean; + + /** + * The version of TDS to use. If server doesn't support specified version, negotiated version is used instead. (default: 7_4). + * Take this from tedious.TDS_VERSION.7_4 . + */ + tdsVersion?: number; + } + + export interface ConnectionConfig { + /** + * User name to use for authentication. + */ + userName?: string; + + /** + * Password to use for authentication. + */ + password?: string; + + /** + * Hostname to connect to. + */ + server?: string; + + /** + * Once you set domain, driver will connect to SQL Server using domain login. + */ + domain?: string; + + /** + * Further options + */ + options?: ConnectionOptions; + } + + export interface ParameterOptions { + // for VarChar, NVarChar, VarBinary + length?: number; + // precision for Numeric, Decimal + precision?: number; + // scale for Numeric, Decimal, Time, DateTime2, DateTimeOffset + scale?: number; + } + + /** + * Type of each column in the Request#row event + */ + export interface ColumnValue { + metadata: ColumnMetaData; + value: any; + } + + /** + * A Request instance represents a request that can be executed on a connection + * @event 'columnMetadata' This event, describing result set columns, will be emitted before row events are emitted. This event may be emited multiple times when more than one recordset is produced by the statement. + * @event 'row' A row resulting from execution of the SQL statement + * @event 'done' All rows from a result set have been provided (through row events). This token is used to indicate the completion of a SQL statement. As multiple SQL statements can be sent to the server in a single SQL batch, multiple done events can be generated. An done event is emited for each SQL statement in the SQL batch except variable declarations. For execution of SQL statements within stored procedures, doneProc and doneInProc events are used in place of done events. + * @event 'doneInProc' Indicates the completion status of a SQL statement within a stored procedure. All rows from a statement in a stored procedure have been provided (through row events). + * @event 'doneProc' Indicates the completion status of a stored procedure. This is also generated for stored procedures executed through SQL statements. + * @event 'returnValue' A value for an output parameter (that was added to the request with addOutputParameter(...)). See also Using Parameters. + */ + export class Request extends events.EventEmitter { + + /** + * Constructor + * @param sql The SQL statement to be executed (or a procedure name, if the request is to be used with connection.callProcedure). + * @param callback The callback is called when the request has completed, either successfully or with an error. If an error occurs during execution of the statement(s), then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + * rowCount: The number of rows emitted as result of executing the SQL statement. + * rows: Rows as a result of executing the SQL statement. Will only be avaiable if Connection's config.options.rowCollectionOnRequestCompletion is true. + */ + constructor(sql: string, callback: (error: Error, rowCount: number, rows: any[]) => void); + + /** + * Add an input parameter to the request. + * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. The name should not start '@'. + * @param type One of the supported data types. + * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. + * @param options Additional type options. Optional. + */ + addParameter(name: string, type: TediousType, value: any, options?: ParameterOptions): void; + + /** + * Add an output parameter to the request. The parameter's value will be provide by an emitted returnValue event. + * @param name The parameter name. This should correspond to a parameter in the SQL, or a parameter that a called procedure expects. + * @param type One of the supported data types. + * @param value The value that the parameter is to be given. The Javascript type of the argument should match that documented for data types. Optional. + * @param options Additional type options. Optional. + */ + addOutputParameter(name: string, type: TediousType, value?: any, options?: ParameterOptions): void; + } + + export interface BulkLoadColumnOpts extends ParameterOptions { + // indicates whether the column accepts NULL values. + nullable: boolean; + // If the name of the column is different from the name of the property found on rowObj arguments passed to , then you can use this option to specify the property name. + objName?: string; + } + + export interface BulkLoad { + + /** + * Adds a column to the bulk load. The column definitions should match the table you are trying to insert into. Attempting to call addColumn after the first row has been added will throw an exception. + * @param name The name of the column. + * @param type One of the supported data types. + * @param options Additional column type information. At a minimum, nullable must be set to true or false. + */ + addColumn(name: string, type: TediousType, options: BulkLoadColumnOpts): void; + + /** + * Adds a row to the bulk insert. This method accepts arguments in three different formats: + * @param rowObj An object of key/value pairs representing column name (or objName) and value. + */ + addRow(row: Object): void; + /** + * Adds a row to the bulk insert. This method accepts arguments in three different formats: + * @param columnArray An array representing the values of each column in the same order which they were added to the bulkLoad object. + */ + addRow(columnArray: any[]): void; + /** + * Adds a row to the bulk insert. This method accepts arguments in three different formats: + * @param args If there are at least two columns, values can be passed as multiple arguments instead of an array. They must be in the same order the columns were added in. + */ + addRow(...args: any[]): void; + + /** + * This is simply a helper utility function which returns a CREATE TABLE SQL statement based on the columns added to the bulkLoad object. This may be particularly handy when you want to insert into a temporary table (a table which starts with #). A side note on bulk inserting into temporary tables: if you want to access a local temporary table after executing the bulk load, you'll need to use the same connection and execute your requests using connection.execSqlBatch instead of .execSql. + */ + getTableCreationSql(): string; + } + + /** + * message interface used by the infoMessage and errorMessage events of Connection + */ + export interface InfoObject { + /** + * Error number + */ + number: number; + /** + * The error state, used as a modifier to the error number. + */ + state: any; + /** + * The class (severity) of the error. A class of less than 10 indicates an informational message. + */ + class: number; + /** + * The message text. + */ + message: string; + /** + * The stored procedure name (if a stored procedure generated the message). + */ + procName: string; + /** + * The line number in the SQL batch or stored procedure that caused the error. Line numbers begin at 1; therefore, if the line number is not applicable to the message, the value of LineNumber will be 0. + */ + lineNumber: number; + } + + /** + * Connection + * @event 'connect' The attempt to connect and validate has completed. + * @event 'end' The connection has ended. This may be as a result of the client calling close(), the server closing the connection, or a network error. + * @event 'error' Internal error occurs. + * @event 'debug' A debug message is available. It may be logged or ignored. + * @event 'infoMessage' The server has issued an information message. + * @event 'errorMessage' The server has issued an error message. + * @event 'databaseChange' The server has reported that the active database has changed. This may be as a result of a sucessful login, or a use statement. + * @event 'languageChange' The server has reported that the language has changed. + * @event 'charsetChange' The server has reported that the charset has changed. + * @event 'secure' A secure connection has been established. + */ + export class Connection extends events.EventEmitter { + + constructor(config: ConnectionConfig); + + /** + * Start a transaction. As only one request at a time may be executed on + * a connection, another request should not be initiated until this callback is called. + * @param callback The callback is called when the request to start the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present. + * @param isolationLevel The isolation level that the transaction is to be run with. + */ + beginTransaction(callback: (error?: Error) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; + + /** + * Commit a transaction. + * There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to commit the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + commitTransaction(callback: (error: Error) => void): void; + + /** + * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + rollbackTransaction(callback: (error: Error) => void): void; + + /** + * Prepare the SQL represented by the request. The request can then be used in subsequent calls to execute and unprepare + * @param request A Request object representing the request. Parameters only require a name and type. Parameter values are ignored. + */ + prepare(request: Request): void; + + /** + * Release the SQL Server resources associated with a previously prepared request. + */ + unprepare(request: Request): void; + + /** + * Call a stored procedure represented by request. + */ + callProcedure(request: Request): void; + + /** + * Execute the SQL represented by request. + * As sp_executesql is used to execute the SQL, if the same SQL is executed multiples times using this function, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution. + * Beware of the way that scoping rules apply, and how they may affect local temp tables. If you're running in to scoping issues, then execSqlBatch may be a better choice. See also issue #24. + */ + execSql(request: Request): void; + + /** + * Execute the SQL batch represented by request. There is no param support, and unlike execSql, it is not likely that SQL Server will reuse the execution plan it generates for the SQL. + * In almost all cases, execSql will be a better choice. + */ + execSqlBatch(request: Request): void; + + /** + * Execute previously prepared SQL, using the supplied parameters. + * @param request A previously prepared Request. + * @param parameters An object whose names correspond to the names of parameters that were added to the request before it was prepared. The object's values are passed as the parameters' values when the request is executed. + */ + execute(request: Request, parameters: {}): void; + + /** + * Creates a new BulkLoad instance. + * @param tableName The name of the table to bulk-insert into. + * @param callback A function which will be called after the BulkLoad finishes executing. rowCount will equal the number of rows inserted. + */ + newBulkLoad(tableName: string, callback: (error: Error, rowCount: number) => void): BulkLoad; + + /** + * Executes a BulkLoad. + */ + execBulkLoad(bulkLoad: BulkLoad): void; + + /** + * Reset the connection to its initial state. Can be useful for connection pool implementations. + * @param callback The callback is called when the connection reset has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + reset(callback: (error: Error) => void): void; + + /** + * Cancel currently executed request. + */ + cancel(): void; + + /** + * Closes the connection to the database. The end will be emmited once the connection has been closed. + */ + close(): void; + + } +} diff --git a/teechart/teechart.d.ts b/teechart/teechart.d.ts index 6e7ac3944..e40e517bd 100644 --- a/teechart/teechart.d.ts +++ b/teechart/teechart.d.ts @@ -1,683 +1,683 @@ -// Type definitions for TeeChart 1.3 -// Project: http://www.steema.com -// Definitions by: Steema Software -// Definitions: https://github.com/borisyankov/DefinitelyTyped -/** - * TeeChart(tm) for TypeScript - * - * v1.3 October 2012 - * Copyright(c) 2012 by Steema Software SL. All Rights Reserved. - * http://www.steema.com - * - * Licensed with commercial and non-commercial attributes, - * specifically: http://www.steema.com/licensing/html5 - * - * TypeScript is a Microsoft product: www.typescriptlang.org - * - */ - -/** - * @author Steema Software - * @version 1.3 - */ - - -declare module Tee { - - interface IPoint { - x: number; - y: number; - } - - interface IRectangle { - x: number; - y: number; - width: number; - height: number; - - contains(point: IPoint): boolean; - } - - interface ITool { - active: boolean; - chart: IChart; - - mousedown(event): boolean; - mousemove(event): boolean; - clicked(p:IPoint): boolean; - draw(): void; - } - - interface IGradient { - chart: IChart; - visible: boolean; - - colors: string[]; - direction: string; - stops: number[]; - offset: IPoint; - } - - interface IShadow { - chart: IChart; - visible: boolean; - blur:number; - color: string; - width:number; - height:number; - } - - interface IStroke { - chart: IChart; - fill: string; - size: number; - join: string; - cap: string; - dash: number[]; - gradient: IGradient; - } - - interface IFont { - chart: IChart; - style: string; - gradient: IGradient; - fill: string; - stroke: IStroke; - shadow: IShadow; - textAlign: string; - baseLine: string; - - getSize():number; - setSize(size:number):void; - } - - interface IImage { - url: string; - chart: IChart; - visible: boolean; - } - - interface IFormat { - font: IFont; - gradient: IGradient; - shadow: IShadow; - stroke: IStroke; - round: IPoint; - transparency: number; - image: IImage; - fill: string; - - textHeight(text:string): number; - textWidth(text:string): number; - drawText(bounds:IRectangle, text:string); - rectangle(x:number, y:number, width:number, height:number); - poligon(points:IPoint[]); - ellipse(x:number, y:number, width:number, height:number); - } - - interface IMargins { - left: number; - top: number; - right: number; - bottom: number; - } - - interface IAnnotation extends ITool { - position: IPoint; - margins: IMargins; - items: IAnnotation[]; - bounds: IRectangle; - visible: boolean; - transparent: boolean; - text: string; - format: IFormat; - - add(text: string): IAnnotation; - resize(): void; - clicked(point: IPoint): boolean; - draw(): void; - } - - interface IPanel { - format: IFormat; - transparent: boolean; - margins: IMargins; - } - - interface ITitle extends IAnnotation { - expand: boolean; - padding: number; - transparent: boolean; - } - - interface IPalette { - colors: string[]; - - get(index: number): string; - } - - interface IArrow extends IFormat { - length: number; - underline: boolean; - } - - interface IMarks extends IAnnotation { - arrow: IArrow; - series: ISeries; - - style: string; - - drawEvery: number; - visible: boolean; - } - - interface ISeriesData { - values: number[]; - labels: string[]; - source: any; - } - - interface ICursor { - cursor: string; - } - - interface ISeriesNoBounds { - data: ISeriesData; - marks: IMarks; - - yMandatory: boolean; - horizAxis: string; - vertAxis: string; - - format: IFormat; - hover: IFormat; - - visible: boolean; - - cursor: ICursor; - over: number; - - palette: IPalette; - colorEach: string; - - useAxes: boolean; - decimals: number; - - title: string; - - //refresh(failure: function): void; - - toPercent(index: number): string; - markText(index: number): string; - - valueText(index: number): string; - - associatedToAxis(axis: IAxis): boolean; - - calc(index: number, position: IPoint): void; - - clicked(position: IPoint): number; - - minXValue(): number; - maxXValue(): number; - - minYValue(): number; - maxYValue(): number; - - count(): number; - - addRandom(count: number, range?: number, x?: boolean): ISeries; - } - - interface ISeries extends ISeriesNoBounds { - bounds(rectangle: IRectangle): void; - } - - interface IAxisLabels { - chart: IChart; - format: IFormat; - decimals: number; - padding: number; - separation: number; // % - visible: boolean; - rotation: number; - alternate: boolean; - maxWidth: number; - - labelStyle: string; - dateFormat: string; - - getLabel(value: number): string; - width(value: number): number; - - } - - interface IGrid { - chart: IChart; - format: IFormat; - visible: boolean; - lineDash: boolean; - } - - interface ITicks { - chart: IChart; - stroke: IStroke; - visible: boolean; - length: number; - } - - interface IMinorTicks extends ITicks { - count: number; - } - - interface IAxisTitle extends IAnnotation { - padding: number; - transparent: boolean; - } - - interface IAxis { - chart: IChart; - visible: boolean; - inverted: boolean; - - horizontal: boolean; // readonly - otherSize: boolean; // readonly - bounds: IRectangle; // readonly? - - position: number; - format: IFormat; - custom: boolean; // readonly - - grid: IGrid; - labels: IAxisLabels; - ticks: ITicks; - minorTicks: IMinorTicks; - innerTicks: ITicks; - - title: IAxisTitle; - - automatic: boolean; - minimum: number; - maximum: number; - increment: number; - log: boolean; - - startPos: number; - endPos: number; - - start: number; // % - end: number; // % - - axisSize: number; - - scale: number; - increm: number; - - calc(value: number): number; - fromPos(position: number): number; - fromSize(size: number): number; - - hasAnySeries(): boolean; - scroll(delta: number): void; - setMinMax(minimum: number, maximum: number): void; - } - - interface IAxes { - chart: IChart; - visible: boolean; - - left: IAxis; - top: IAxis; - right: IAxis; - bottom: IAxis; - - items: IAxis[]; - - add(horizontal: boolean, otherSide: boolean): IAxis; - //each(f: function): void; - } - - interface ISymbol { - chart: IChart; - format: IFormat; - width: number; - height: number; - padding: number; - visible: boolean; - } - - interface ILegend { - chart: IChart; - - transparent: boolean; - - format: IFormat; - title: IAnnotation; - - bounds: IRectangle; - position: string; - visible: boolean; - inverted: boolean; - padding: number; - align: number; - - fontColor: boolean; - - dividing: IStroke; - over: number; - symbol: ISymbol; - - itemHeight: number; - innerOff: number; - - legendStyle: string; - textStyle: string; - - availRows(): number; - itemsCount(): number; - totalWidth(): number; - showValues(): boolean; - itemText(series: ISeries, index: number): string; - isVertical(): boolean; - } - - interface IScroll { - chart: IChart; - active: boolean; - enabled: boolean; - direction: string; - mouseButton: number; - - position: IPoint; - } - - interface ISeriesList { - chart: IChart; - items: ISeries[]; - - anyUsesAxes(): boolean; - clicked(position: IPoint): boolean; - //each(f: function): void; - firstVisible(): ISeries; - - } - - interface ITools { - chart: IChart; - items: ITool[]; - - add(tool: ITool): ITool; - } - - interface IWall { - format: IFormat; - visible: boolean; - bounds: IRectangle; - } - - interface IWalls { - visible: boolean; - left: IWall; - right: IWall; - bottom: IWall; - back: IWall; - } - - interface IZoom { - chart: IChart; - active: boolean; - direction: string; - enabled: boolean; - mouseButton: number; - format: IFormat; - - reset(): void; - } - - interface IChart { - addSeries(series:ISeries): ISeries; - draw(context?:CanvasRenderingContext2D); - } - - // SERIES - - interface ICustomBar extends ISeries { - sideMargins: number; - useOrigin: boolean; - origin: number; - - offset: number; - barSize: number; - barStyle: string; - - stacked: string; - } - - interface ISeriesPointer { - chart: IChart; - format: IFormat; - visible: boolean; - colorEach: boolean; - style: string; - width: number; - height: number; - } - - interface ICustomSeries extends ISeries { - pointer: ISeriesPointer; - - stacked: string; - stairs: boolean; - } - - interface ILine extends ICustomSeries { - smooth: number; - } - - interface ISmoothLine extends ILine { - smooth: number; - } - - interface IArea extends ISeries { - useOrigin: boolean; - origin: number; - } - - interface IPie extends ISeries { - donut: number; - rotation: number; - sort: string; - orderAscending: boolean; - explode: number[]; - concentric: boolean; - - calcPos(angle: number, position: IPoint): void; - } - - interface IBubbleData extends ISeriesData { - radius: number[]; - } - - interface IBubble extends ICustomSeries { - data: IBubbleData; - } - - interface IGanttData extends ISeriesData { - start: number[]; - x: number[]; - end: number[]; - } - - interface IGantt extends ISeriesNoBounds { - data: IGanttData; - dateFormat: string; - colorEach: string; - height: number; - margin: IPoint; - - add(index: number, label: string, start: number, end: number): void; - bounds(index: number, rectangle: IRectangle): void; - } - - interface ICandleData extends ISeriesData { - open: number[]; - close: number[]; - high: number[]; - low: number[]; - } - - interface ICandle extends ICustomSeries { - data: ICandleData; - higher: IFormat; - lower: IFormat; - style: string; - } - - // TOOLS - - interface IDragTool extends ITool { - series: ISeries; - } - - interface ICursorTool extends ITool { - direction: string; - size: IPoint; - - followMouse: boolean; - dragging: number; - - format: IFormat; - - horizAxis: IAxis; - vertAxis: IAxis; - - render: string; - - over(point: IPoint): boolean; - setRender(render: string): void; - } - - interface IToolTip extends IAnnotation { - animated: number; - autoHide: boolean; - autoRedraw: boolean; - currentSeries: ISeries; - currentIndex: number; - delay: number; - - hide(): void; - refresh(series: ISeries, index: number): void; - } - - class Point implements IPoint { - public x:number; - public y:number; - } - - class Chart implements IChart { - //public aspect: IAspect; - - public axes: IAxes; - public footer: ITitle; - public legend: ILegend; - public panel: IPanel; - public scroll: IScroll; - public series: ISeriesList; - public title: ITitle; - public tools: ITools; - public walls: IWalls; - public zoom: IZoom; - - public bounds: IRectangle; - public canvas: HTMLCanvasElement; - public chartRect: IRectangle; - public palette: IPalette; - - constructor(canvas: string); - addSeries(series: ISeries): ISeries; - getSeries(index: number): ISeries; - removeSeries(series:ISeries): void; - - draw(context?:CanvasRenderingContext2D); - toImage(image: HTMLImageElement, format:string, quality:number): void; - } - - // SERIES - - var Line: { - prototype: ILine; - new(values?:number[]): ILine; - } - - var PointXY: { - prototype: ICustomSeries; - new(values?:number[]): ICustomSeries; - } - - var Area: { - prototype: IArea; - new(values?:number[]): IArea; - } - - var HorizArea: { - prototype: IArea; - new(values?:number[]): IArea; - } - - var Bar: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - var HorizBar: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - var Pie: { - prototype: IPie; - new(values?:number[]): IPie; - } - - var Donut: { - prototype: IPie; - new(values?:number[]): IPie; - } - - var Bubble: { - prototype: IBubble; - new(values?:number[]): IBubble; - } - - var Gantt: { - prototype: IGantt; - new(values?:number[]): IGantt; - } - - var Volume: { - prototype: ICustomBar; - new(values?:number[]): ICustomBar; - } - - var Candle: { - prototype: ICandle; - new(values?:number[]): ICandle; - } - - // TOOLS - - var CursorTool: { - prototype: ICursorTool; - new(chart?: Chart): ICursorTool; - } - - var DragTool: { - prototype: IDragTool; - new(chart?: Chart): IDragTool; - } - - var ToolTip: { - prototype: IToolTip; - new(chart?: Chart): IToolTip; - } -} +// Type definitions for TeeChart 1.3 +// Project: http://www.steema.com +// Definitions by: Steema Software +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/** + * TeeChart(tm) for TypeScript + * + * v1.3 October 2012 + * Copyright(c) 2012 by Steema Software SL. All Rights Reserved. + * http://www.steema.com + * + * Licensed with commercial and non-commercial attributes, + * specifically: http://www.steema.com/licensing/html5 + * + * TypeScript is a Microsoft product: www.typescriptlang.org + * + */ + +/** + * @author Steema Software + * @version 1.3 + */ + + +declare module Tee { + + interface IPoint { + x: number; + y: number; + } + + interface IRectangle { + x: number; + y: number; + width: number; + height: number; + + contains(point: IPoint): boolean; + } + + interface ITool { + active: boolean; + chart: IChart; + + mousedown(event): boolean; + mousemove(event): boolean; + clicked(p:IPoint): boolean; + draw(): void; + } + + interface IGradient { + chart: IChart; + visible: boolean; + + colors: string[]; + direction: string; + stops: number[]; + offset: IPoint; + } + + interface IShadow { + chart: IChart; + visible: boolean; + blur:number; + color: string; + width:number; + height:number; + } + + interface IStroke { + chart: IChart; + fill: string; + size: number; + join: string; + cap: string; + dash: number[]; + gradient: IGradient; + } + + interface IFont { + chart: IChart; + style: string; + gradient: IGradient; + fill: string; + stroke: IStroke; + shadow: IShadow; + textAlign: string; + baseLine: string; + + getSize():number; + setSize(size:number):void; + } + + interface IImage { + url: string; + chart: IChart; + visible: boolean; + } + + interface IFormat { + font: IFont; + gradient: IGradient; + shadow: IShadow; + stroke: IStroke; + round: IPoint; + transparency: number; + image: IImage; + fill: string; + + textHeight(text:string): number; + textWidth(text:string): number; + drawText(bounds:IRectangle, text:string); + rectangle(x:number, y:number, width:number, height:number); + poligon(points:IPoint[]); + ellipse(x:number, y:number, width:number, height:number); + } + + interface IMargins { + left: number; + top: number; + right: number; + bottom: number; + } + + interface IAnnotation extends ITool { + position: IPoint; + margins: IMargins; + items: IAnnotation[]; + bounds: IRectangle; + visible: boolean; + transparent: boolean; + text: string; + format: IFormat; + + add(text: string): IAnnotation; + resize(): void; + clicked(point: IPoint): boolean; + draw(): void; + } + + interface IPanel { + format: IFormat; + transparent: boolean; + margins: IMargins; + } + + interface ITitle extends IAnnotation { + expand: boolean; + padding: number; + transparent: boolean; + } + + interface IPalette { + colors: string[]; + + get(index: number): string; + } + + interface IArrow extends IFormat { + length: number; + underline: boolean; + } + + interface IMarks extends IAnnotation { + arrow: IArrow; + series: ISeries; + + style: string; + + drawEvery: number; + visible: boolean; + } + + interface ISeriesData { + values: number[]; + labels: string[]; + source: any; + } + + interface ICursor { + cursor: string; + } + + interface ISeriesNoBounds { + data: ISeriesData; + marks: IMarks; + + yMandatory: boolean; + horizAxis: string; + vertAxis: string; + + format: IFormat; + hover: IFormat; + + visible: boolean; + + cursor: ICursor; + over: number; + + palette: IPalette; + colorEach: string; + + useAxes: boolean; + decimals: number; + + title: string; + + //refresh(failure: function): void; + + toPercent(index: number): string; + markText(index: number): string; + + valueText(index: number): string; + + associatedToAxis(axis: IAxis): boolean; + + calc(index: number, position: IPoint): void; + + clicked(position: IPoint): number; + + minXValue(): number; + maxXValue(): number; + + minYValue(): number; + maxYValue(): number; + + count(): number; + + addRandom(count: number, range?: number, x?: boolean): ISeries; + } + + interface ISeries extends ISeriesNoBounds { + bounds(rectangle: IRectangle): void; + } + + interface IAxisLabels { + chart: IChart; + format: IFormat; + decimals: number; + padding: number; + separation: number; // % + visible: boolean; + rotation: number; + alternate: boolean; + maxWidth: number; + + labelStyle: string; + dateFormat: string; + + getLabel(value: number): string; + width(value: number): number; + + } + + interface IGrid { + chart: IChart; + format: IFormat; + visible: boolean; + lineDash: boolean; + } + + interface ITicks { + chart: IChart; + stroke: IStroke; + visible: boolean; + length: number; + } + + interface IMinorTicks extends ITicks { + count: number; + } + + interface IAxisTitle extends IAnnotation { + padding: number; + transparent: boolean; + } + + interface IAxis { + chart: IChart; + visible: boolean; + inverted: boolean; + + horizontal: boolean; // readonly + otherSize: boolean; // readonly + bounds: IRectangle; // readonly? + + position: number; + format: IFormat; + custom: boolean; // readonly + + grid: IGrid; + labels: IAxisLabels; + ticks: ITicks; + minorTicks: IMinorTicks; + innerTicks: ITicks; + + title: IAxisTitle; + + automatic: boolean; + minimum: number; + maximum: number; + increment: number; + log: boolean; + + startPos: number; + endPos: number; + + start: number; // % + end: number; // % + + axisSize: number; + + scale: number; + increm: number; + + calc(value: number): number; + fromPos(position: number): number; + fromSize(size: number): number; + + hasAnySeries(): boolean; + scroll(delta: number): void; + setMinMax(minimum: number, maximum: number): void; + } + + interface IAxes { + chart: IChart; + visible: boolean; + + left: IAxis; + top: IAxis; + right: IAxis; + bottom: IAxis; + + items: IAxis[]; + + add(horizontal: boolean, otherSide: boolean): IAxis; + //each(f: function): void; + } + + interface ISymbol { + chart: IChart; + format: IFormat; + width: number; + height: number; + padding: number; + visible: boolean; + } + + interface ILegend { + chart: IChart; + + transparent: boolean; + + format: IFormat; + title: IAnnotation; + + bounds: IRectangle; + position: string; + visible: boolean; + inverted: boolean; + padding: number; + align: number; + + fontColor: boolean; + + dividing: IStroke; + over: number; + symbol: ISymbol; + + itemHeight: number; + innerOff: number; + + legendStyle: string; + textStyle: string; + + availRows(): number; + itemsCount(): number; + totalWidth(): number; + showValues(): boolean; + itemText(series: ISeries, index: number): string; + isVertical(): boolean; + } + + interface IScroll { + chart: IChart; + active: boolean; + enabled: boolean; + direction: string; + mouseButton: number; + + position: IPoint; + } + + interface ISeriesList { + chart: IChart; + items: ISeries[]; + + anyUsesAxes(): boolean; + clicked(position: IPoint): boolean; + //each(f: function): void; + firstVisible(): ISeries; + + } + + interface ITools { + chart: IChart; + items: ITool[]; + + add(tool: ITool): ITool; + } + + interface IWall { + format: IFormat; + visible: boolean; + bounds: IRectangle; + } + + interface IWalls { + visible: boolean; + left: IWall; + right: IWall; + bottom: IWall; + back: IWall; + } + + interface IZoom { + chart: IChart; + active: boolean; + direction: string; + enabled: boolean; + mouseButton: number; + format: IFormat; + + reset(): void; + } + + interface IChart { + addSeries(series:ISeries): ISeries; + draw(context?:CanvasRenderingContext2D); + } + + // SERIES + + interface ICustomBar extends ISeries { + sideMargins: number; + useOrigin: boolean; + origin: number; + + offset: number; + barSize: number; + barStyle: string; + + stacked: string; + } + + interface ISeriesPointer { + chart: IChart; + format: IFormat; + visible: boolean; + colorEach: boolean; + style: string; + width: number; + height: number; + } + + interface ICustomSeries extends ISeries { + pointer: ISeriesPointer; + + stacked: string; + stairs: boolean; + } + + interface ILine extends ICustomSeries { + smooth: number; + } + + interface ISmoothLine extends ILine { + smooth: number; + } + + interface IArea extends ISeries { + useOrigin: boolean; + origin: number; + } + + interface IPie extends ISeries { + donut: number; + rotation: number; + sort: string; + orderAscending: boolean; + explode: number[]; + concentric: boolean; + + calcPos(angle: number, position: IPoint): void; + } + + interface IBubbleData extends ISeriesData { + radius: number[]; + } + + interface IBubble extends ICustomSeries { + data: IBubbleData; + } + + interface IGanttData extends ISeriesData { + start: number[]; + x: number[]; + end: number[]; + } + + interface IGantt extends ISeriesNoBounds { + data: IGanttData; + dateFormat: string; + colorEach: string; + height: number; + margin: IPoint; + + add(index: number, label: string, start: number, end: number): void; + bounds(index: number, rectangle: IRectangle): void; + } + + interface ICandleData extends ISeriesData { + open: number[]; + close: number[]; + high: number[]; + low: number[]; + } + + interface ICandle extends ICustomSeries { + data: ICandleData; + higher: IFormat; + lower: IFormat; + style: string; + } + + // TOOLS + + interface IDragTool extends ITool { + series: ISeries; + } + + interface ICursorTool extends ITool { + direction: string; + size: IPoint; + + followMouse: boolean; + dragging: number; + + format: IFormat; + + horizAxis: IAxis; + vertAxis: IAxis; + + render: string; + + over(point: IPoint): boolean; + setRender(render: string): void; + } + + interface IToolTip extends IAnnotation { + animated: number; + autoHide: boolean; + autoRedraw: boolean; + currentSeries: ISeries; + currentIndex: number; + delay: number; + + hide(): void; + refresh(series: ISeries, index: number): void; + } + + class Point implements IPoint { + public x:number; + public y:number; + } + + class Chart implements IChart { + //public aspect: IAspect; + + public axes: IAxes; + public footer: ITitle; + public legend: ILegend; + public panel: IPanel; + public scroll: IScroll; + public series: ISeriesList; + public title: ITitle; + public tools: ITools; + public walls: IWalls; + public zoom: IZoom; + + public bounds: IRectangle; + public canvas: HTMLCanvasElement; + public chartRect: IRectangle; + public palette: IPalette; + + constructor(canvas: string); + addSeries(series: ISeries): ISeries; + getSeries(index: number): ISeries; + removeSeries(series:ISeries): void; + + draw(context?:CanvasRenderingContext2D); + toImage(image: HTMLImageElement, format:string, quality:number): void; + } + + // SERIES + + var Line: { + prototype: ILine; + new(values?:number[]): ILine; + } + + var PointXY: { + prototype: ICustomSeries; + new(values?:number[]): ICustomSeries; + } + + var Area: { + prototype: IArea; + new(values?:number[]): IArea; + } + + var HorizArea: { + prototype: IArea; + new(values?:number[]): IArea; + } + + var Bar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + var HorizBar: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + var Pie: { + prototype: IPie; + new(values?:number[]): IPie; + } + + var Donut: { + prototype: IPie; + new(values?:number[]): IPie; + } + + var Bubble: { + prototype: IBubble; + new(values?:number[]): IBubble; + } + + var Gantt: { + prototype: IGantt; + new(values?:number[]): IGantt; + } + + var Volume: { + prototype: ICustomBar; + new(values?:number[]): ICustomBar; + } + + var Candle: { + prototype: ICandle; + new(values?:number[]): ICandle; + } + + // TOOLS + + var CursorTool: { + prototype: ICursorTool; + new(chart?: Chart): ICursorTool; + } + + var DragTool: { + prototype: IDragTool; + new(chart?: Chart): IDragTool; + } + + var ToolTip: { + prototype: IToolTip; + new(chart?: Chart): IToolTip; + } +} diff --git a/teechart/teechart.d.ts.tscparams b/teechart/teechart.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/teechart/teechart.d.ts.tscparams +++ b/teechart/teechart.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/threejs/three-tests.ts.tscparams b/threejs/three-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/threejs/three-tests.ts.tscparams +++ b/threejs/three-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/through/through-tests.ts b/through/through-tests.ts index 35822c9e8..83f8e8780 100644 --- a/through/through-tests.ts +++ b/through/through-tests.ts @@ -1,11 +1,11 @@ -/// - -import through = require('through'); - -var i = 0; -through( - function () { - this.queue((i++).toString()); - }, function () { - this.queue(null); - }, { autoDestroy: true }).pipe(process.stdout); +/// + +import through = require('through'); + +var i = 0; +through( + function () { + this.queue((i++).toString()); + }, function () { + this.queue(null); + }, { autoDestroy: true }).pipe(process.stdout); diff --git a/through/through.d.ts b/through/through.d.ts index 70a7d989c..afffcdcc1 100644 --- a/through/through.d.ts +++ b/through/through.d.ts @@ -1,24 +1,24 @@ -// Type definitions for through -// Project: https://github.com/dominictarr/through -// Definitions by: Andrew Gaspar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "through" { - import stream = require("stream"); - - function through(write?: (data: any) => void, - end?: () => void, - opts?: { - autoDestroy: boolean; - }): through.ThroughStream; - - module through { - export interface ThroughStream extends stream.Transform { - autoDestroy: boolean; - } - } - - export = through; -} +// Type definitions for through +// Project: https://github.com/dominictarr/through +// Definitions by: Andrew Gaspar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "through" { + import stream = require("stream"); + + function through(write?: (data: any) => void, + end?: () => void, + opts?: { + autoDestroy: boolean; + }): through.ThroughStream; + + module through { + export interface ThroughStream extends stream.Transform { + autoDestroy: boolean; + } + } + + export = through; +} diff --git a/timezone-js/timezone-js.d.ts b/timezone-js/timezone-js.d.ts index 9aca2738e..069ed67c8 100644 --- a/timezone-js/timezone-js.d.ts +++ b/timezone-js/timezone-js.d.ts @@ -19,50 +19,50 @@ declare module "timezone-js" { setTimezone: (timezone: string) => void; // regular Date members - toString(): string; - toDateString(): string; - toTimeString(): string; - toLocaleString(): string; - toLocaleDateString(): string; - toLocaleTimeString(): string; - valueOf(): number; - getTime(): number; - getFullYear(): number; - getUTCFullYear(): number; - getMonth(): number; - getUTCMonth(): number; - getDate(): number; - getUTCDate(): number; - getDay(): number; - getUTCDay(): number; - getHours(): number; - getUTCHours(): number; - getMinutes(): number; - getUTCMinutes(): number; - getSeconds(): number; - getUTCSeconds(): number; - getMilliseconds(): number; - getUTCMilliseconds(): number; - getTimezoneOffset(): number; - setTime(time: number): number; - - // Note the setters have a non-void return type. Date has them as well, according to TypeScript - setMilliseconds(ms: number): number; - setUTCMilliseconds(ms: number): number; - setSeconds(sec: number, ms?: number): number; - setUTCSeconds(sec: number, ms?: number): number; - setMinutes(min: number, sec?: number, ms?: number): number; - setUTCMinutes(min: number, sec?: number, ms?: number): number; - setHours(hours: number, min?: number, sec?: number, ms?: number): number; - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; - setDate(date: number): number; - setUTCDate(date: number): number; - setMonth(month: number, date?: number): number; - setUTCMonth(month: number, date?: number): number; - setFullYear(year: number, month?: number, date?: number): number; - setUTCFullYear(year: number, month?: number, date?: number): number; - toUTCString(): string; - toISOString(): string; + toString(): string; + toDateString(): string; + toTimeString(): string; + toLocaleString(): string; + toLocaleDateString(): string; + toLocaleTimeString(): string; + valueOf(): number; + getTime(): number; + getFullYear(): number; + getUTCFullYear(): number; + getMonth(): number; + getUTCMonth(): number; + getDate(): number; + getUTCDate(): number; + getDay(): number; + getUTCDay(): number; + getHours(): number; + getUTCHours(): number; + getMinutes(): number; + getUTCMinutes(): number; + getSeconds(): number; + getUTCSeconds(): number; + getMilliseconds(): number; + getUTCMilliseconds(): number; + getTimezoneOffset(): number; + setTime(time: number): number; + + // Note the setters have a non-void return type. Date has them as well, according to TypeScript + setMilliseconds(ms: number): number; + setUTCMilliseconds(ms: number): number; + setSeconds(sec: number, ms?: number): number; + setUTCSeconds(sec: number, ms?: number): number; + setMinutes(min: number, sec?: number, ms?: number): number; + setUTCMinutes(min: number, sec?: number, ms?: number): number; + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + setDate(date: number): number; + setUTCDate(date: number): number; + setMonth(month: number, date?: number): number; + setUTCMonth(month: number, date?: number): number; + setFullYear(year: number, month?: number, date?: number): number; + setUTCFullYear(year: number, month?: number, date?: number): number; + toUTCString(): string; + toISOString(): string; toJSON(key?: any): string; } diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts index cb1c69282..b08cb20b6 100644 --- a/timezonecomplete/timezonecomplete-tests.ts +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -1,234 +1,234 @@ -/// - -import tc = require("timezonecomplete"); - -var b: boolean; -var n: number; -var s: string; -var w: tc.WeekDay; - -n = tc.timeUnitToMilliseconds(tc.TimeUnit.Month); -b = tc.isLeapYear(2014); -n = tc.daysInMonth(2014, 10); -n = tc.daysInYear(2014); -n = tc.dayOfYear(2014, 1, 2); -w = tc.firstWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); -w = tc.lastWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); -n = tc.weekDayOnOrAfter(2014, 1, 14, tc.WeekDay.Monday); -n = tc.weekDayOnOrBefore(2014, 1, 14, tc.WeekDay.Monday); -n = tc.secondOfDay(13, 59, 59); -n = tc.weekOfMonth(2014, 1, 1); - -s = tc.timeUnitToString(tc.TimeUnit.Second); -var tu: tc.TimeUnit = tc.stringToTimeUnit("bla"); - -// DURATION - -var d: tc.Duration; -var d1: tc.Duration = tc.Duration.hours(24); -var d2: tc.Duration = tc.Duration.minutes(24); -var d3: tc.Duration = tc.Duration.seconds(24); -var d4: tc.Duration = tc.Duration.milliseconds(24); -var d5: tc.Duration = tc.hours(24); -var d6: tc.Duration = tc.minutes(24); -var d7: tc.Duration = tc.seconds(24); -var d8: tc.Duration = tc.milliseconds(24); -var d9: tc.Duration = new tc.Duration(24); -var d10: tc.Duration = new tc.Duration("00:01"); -var d11: tc.Duration = d6.clone(); -var d12: tc.Duration = new tc.Duration(4, tc.TimeUnit.Second); - -n = d7.wholeHours(); -n = d7.hours(); -n = d7.minutes(); -n = d7.minute(); -n = d7.seconds(); -n = d7.second(); -n = d7.milliseconds(); -n = d7.millisecond(); -s = d7.sign(); -b = d7.lessThan(d6); -b = d7.greaterThan(d6); -d = d7.min(d6); -d = d7.max(d6); -d = d7.multiply(3); -d = d7.divide(0.3); -d = d7.add(d6); -d = d7.sub(d6); -s = d7.toString(); - -b = d7.equals(d6); -b = d7.equalsExact(d6); -b = d7.identical(d6); - -// TIMEZONE - -var t: tc.TimeZone; -var k: tc.TimeZoneKind; - -t = tc.TimeZone.local(); -t = tc.TimeZone.utc(); -t = tc.TimeZone.zone(2); -t = tc.TimeZone.zone("+01:00"); -t = tc.local(); -t = tc.utc(); -t = tc.zone(2); -t = tc.zone("+01:00"); -t = tc.zone("Europe/Amsterdam", false); -s = t.name(); -k = t.kind(); -b = t.equals(t); -b = t.isUtc(); -b = t.dst(); -n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); -n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); -n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); -n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); -s = t.toString(); -s = tc.TimeZone.offsetToString(2); -n = tc.TimeZone.stringToOffset("+00:01"); -b = t.equals(t); -b = t.identical(t); - -// REALTIMESOURCE - -var date: Date = (new tc.RealTimeSource()).now(); - -// DATETIME - -var dt: tc.DateTime; - -var ts: tc.TimeSource = tc.DateTime.timeSource; - -dt = tc.DateTime.nowLocal(); -dt = tc.DateTime.nowUtc(); -dt = tc.DateTime.now(tc.TimeZone.local()); -dt = tc.DateTime.fromExcel(1.5); -dt = tc.nowLocal(); -dt = tc.nowUtc(); -dt = tc.now(tc.TimeZone.local()); -dt = new tc.DateTime(); -dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); -dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); -dt = new tc.DateTime(date, tc.DateFunctions.Get); -dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); -dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); -dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); -dt = new tc.DateTime(89949284); -dt = new tc.DateTime(89949284, tc.TimeZone.utc()); -dt = dt.clone(); -t = dt.zone(); -n = dt.offset(); -n = dt.year(); -n = dt.month(); -n = dt.day(); -n = dt.hour(); -n = dt.minute(); -n = dt.second(); -n = dt.weekNumber(); -n = dt.weekOfMonth(); -n = dt.secondOfDay(); -n = dt.dayOfYear(); -n = dt.millisecond(); -n = dt.unixUtcMillis(); -n = dt.utcYear(); -n = dt.utcMonth(); -n = dt.utcDay(); -n = dt.utcHour(); -n = dt.utcMinute(); -n = dt.utcSecond(); -n = dt.utcMillisecond(); -n = dt.utcWeekNumber(); -n = dt.utcWeekOfMonth(); -n = dt.utcSecondOfDay(); -n = dt.utcDayOfYear(); -s = dt.format("%Y-%m-%d"); -dt.convert(tc.TimeZone.local()); -dt = dt.toZone(tc.TimeZone.utc()); -date = dt.toDate(); -dt = dt.add(tc.Duration.seconds(2)); -dt = dt.add(2, tc.TimeUnit.Year); -dt = dt.add(2, tc.TimeUnit.Month); -dt = dt.add(2, tc.TimeUnit.Week); -dt = dt.add(2, tc.TimeUnit.Day); -dt = dt.add(2, tc.TimeUnit.Hour); -dt = dt.add(2, tc.TimeUnit.Minute); -dt = dt.add(2, tc.TimeUnit.Second); -dt = dt.addLocal(2, tc.TimeUnit.Second); -dt = dt.addLocal(tc.minutes(2)); -dt = dt.sub(tc.Duration.seconds(2)); -dt = dt.sub(2, tc.TimeUnit.Year); -dt = dt.sub(2, tc.TimeUnit.Month); -dt = dt.sub(2, tc.TimeUnit.Week); -dt = dt.sub(2, tc.TimeUnit.Day); -dt = dt.sub(2, tc.TimeUnit.Hour); -dt = dt.sub(2, tc.TimeUnit.Minute); -dt = dt.sub(2, tc.TimeUnit.Second); -dt = dt.subLocal(2, tc.TimeUnit.Second); -dt = dt.subLocal(tc.minutes(2)); -d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); -b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); -b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); -b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); -b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); -dt = dt.min(new tc.DateTime(9289234, tc.TimeZone.local())); -dt = dt.max(new tc.DateTime(9289234, tc.TimeZone.local())); -s = dt.toIsoString(); -s = dt.toString(); -s = dt.toUtcString(); -dt = dt.startOfDay(); - -var wd: tc.WeekDay; -wd = dt.weekDay(); -wd = dt.utcWeekDay(); - -// PERIOD - -s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); -s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); - -var p: tc.Period; - -p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); -p = new tc.Period(tc.DateTime.nowLocal(), tc.hours(1), tc.PeriodDst.RegularLocalTime); -dt = p.start(); -n = p.amount(); -var tu: tc.TimeUnit = p.unit(); -var pd: tc.PeriodDst = p.dst(); -dt = p.findFirst(tc.DateTime.nowLocal()); -dt = p.findNext(dt); -s = p.toIsoString(); -s = p.toString(); -b = p.isBoundary(dt); -b = p.equals(p); -b = p.identical(p); - - -// GLOBALS -d = tc.min(tc.Duration.seconds(2), tc.Duration.seconds(3)); -d = tc.max(tc.Duration.seconds(2), tc.Duration.seconds(3)); - -dt = tc.min(new tc.DateTime(2), new tc.DateTime(3)); -dt = tc.max(new tc.DateTime(2), new tc.DateTime(3)); - - - - - - - - - - - - - - - - - - - - - - +/// + +import tc = require("timezonecomplete"); + +var b: boolean; +var n: number; +var s: string; +var w: tc.WeekDay; + +n = tc.timeUnitToMilliseconds(tc.TimeUnit.Month); +b = tc.isLeapYear(2014); +n = tc.daysInMonth(2014, 10); +n = tc.daysInYear(2014); +n = tc.dayOfYear(2014, 1, 2); +w = tc.firstWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +w = tc.lastWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +n = tc.weekDayOnOrAfter(2014, 1, 14, tc.WeekDay.Monday); +n = tc.weekDayOnOrBefore(2014, 1, 14, tc.WeekDay.Monday); +n = tc.secondOfDay(13, 59, 59); +n = tc.weekOfMonth(2014, 1, 1); + +s = tc.timeUnitToString(tc.TimeUnit.Second); +var tu: tc.TimeUnit = tc.stringToTimeUnit("bla"); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = tc.hours(24); +var d6: tc.Duration = tc.minutes(24); +var d7: tc.Duration = tc.seconds(24); +var d8: tc.Duration = tc.milliseconds(24); +var d9: tc.Duration = new tc.Duration(24); +var d10: tc.Duration = new tc.Duration("00:01"); +var d11: tc.Duration = d6.clone(); +var d12: tc.Duration = new tc.Duration(4, tc.TimeUnit.Second); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.divide(0.3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +b = d7.equals(d6); +b = d7.equalsExact(d6); +b = d7.identical(d6); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +t = tc.local(); +t = tc.utc(); +t = tc.zone(2); +t = tc.zone("+01:00"); +t = tc.zone("Europe/Amsterdam", false); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +b = t.dst(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); +b = t.equals(t); +b = t.identical(t); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = tc.DateTime.fromExcel(1.5); +dt = tc.nowLocal(); +dt = tc.nowUtc(); +dt = tc.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.weekNumber(); +n = dt.weekOfMonth(); +n = dt.secondOfDay(); +n = dt.dayOfYear(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +n = dt.utcWeekNumber(); +n = dt.utcWeekOfMonth(); +n = dt.utcSecondOfDay(); +n = dt.utcDayOfYear(); +s = dt.format("%Y-%m-%d"); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.addLocal(tc.minutes(2)); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +dt = dt.subLocal(tc.minutes(2)); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +dt = dt.min(new tc.DateTime(9289234, tc.TimeZone.local())); +dt = dt.max(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); +dt = dt.startOfDay(); + +var wd: tc.WeekDay; +wd = dt.weekDay(); +wd = dt.utcWeekDay(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +p = new tc.Period(tc.DateTime.nowLocal(), tc.hours(1), tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); +b = p.isBoundary(dt); +b = p.equals(p); +b = p.identical(p); + + +// GLOBALS +d = tc.min(tc.Duration.seconds(2), tc.Duration.seconds(3)); +d = tc.max(tc.Duration.seconds(2), tc.Duration.seconds(3)); + +dt = tc.min(new tc.DateTime(2), new tc.DateTime(3)); +dt = tc.max(new tc.DateTime(2), new tc.DateTime(3)); + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts index 635f4558f..a9c54e6a0 100644 --- a/timezonecomplete/timezonecomplete.d.ts +++ b/timezonecomplete/timezonecomplete.d.ts @@ -1,1519 +1,1519 @@ -// Type definitions for timezonecomplete 1.15.0 -// Project: https://github.com/SpiritIT/timezonecomplete -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module 'timezonecomplete' { - import basics = require("__timezonecomplete/basics"); - export import TimeUnit = basics.TimeUnit; - export import WeekDay = basics.WeekDay; - export import timeUnitToMilliseconds = basics.timeUnitToMilliseconds; - export import isLeapYear = basics.isLeapYear; - export import daysInMonth = basics.daysInMonth; - export import daysInYear = basics.daysInYear; - export import firstWeekDayOfMonth = basics.firstWeekDayOfMonth; - export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; - export import weekDayOnOrAfter = basics.weekDayOnOrAfter; - export import weekDayOnOrBefore = basics.weekDayOnOrBefore; - export import weekNumber = basics.weekNumber; - export import weekOfMonth = basics.weekOfMonth; - export import dayOfYear = basics.dayOfYear; - export import secondOfDay = basics.secondOfDay; - export import timeUnitToString = basics.timeUnitToString; - export import stringToTimeUnit = basics.stringToTimeUnit; - import datetime = require("__timezonecomplete/datetime"); - export import DateTime = datetime.DateTime; - export import now = datetime.now; - export import nowLocal = datetime.nowLocal; - export import nowUtc = datetime.nowUtc; - import duration = require("__timezonecomplete/duration"); - export import Duration = duration.Duration; - export import years = duration.years; - export import months = duration.months; - export import days = duration.days; - export import hours = duration.hours; - export import minutes = duration.minutes; - export import seconds = duration.seconds; - export import milliseconds = duration.milliseconds; - import javascript = require("__timezonecomplete/javascript"); - export import DateFunctions = javascript.DateFunctions; - import period = require("__timezonecomplete/period"); - export import Period = period.Period; - export import PeriodDst = period.PeriodDst; - export import periodDstToString = period.periodDstToString; - import timesource = require("__timezonecomplete/timesource"); - export import TimeSource = timesource.TimeSource; - export import RealTimeSource = timesource.RealTimeSource; - import timezone = require("__timezonecomplete/timezone"); - export import NormalizeOption = timezone.NormalizeOption; - export import TimeZoneKind = timezone.TimeZoneKind; - export import TimeZone = timezone.TimeZone; - export import local = timezone.local; - export import utc = timezone.utc; - export import zone = timezone.zone; - import globals = require("__timezonecomplete/globals"); - export import min = globals.min; - export import max = globals.max; -} - -declare module '__timezonecomplete/basics' { - import javascript = require("__timezonecomplete/javascript"); - import DateFunctions = javascript.DateFunctions; - /** - * Day-of-week. Note the enum values correspond to JavaScript day-of-week: - * Sunday = 0, Monday = 1 etc - */ - export enum WeekDay { - Sunday = 0, - Monday = 1, - Tuesday = 2, - Wednesday = 3, - Thursday = 4, - Friday = 5, - Saturday = 6, - } - /** - * Time units - */ - export enum TimeUnit { - Millisecond = 0, - Second = 1, - Minute = 2, - Hour = 3, - Day = 4, - Week = 5, - Month = 6, - Year = 7, - /** - * End-of-enum marker, do not use - */ - MAX = 8, - } - /** - * Approximate number of milliseconds for a time unit. - * A day is assumed to have 24 hours, a month is assumed to equal 30 days - * and a year is set to 360 days (because 12 months of 30 days). - * - * @param unit Time unit e.g. TimeUnit.Month - * @returns The number of milliseconds. - */ - export function timeUnitToMilliseconds(unit: TimeUnit): number; - /** - * Time unit to lowercase string. If amount is specified, then the string is put in plural form - * if necessary. - * @param unit The unit - * @param amount If this is unequal to -1 and 1, then the result is pluralized - */ - export function timeUnitToString(unit: TimeUnit, amount?: number): string; - export function stringToTimeUnit(s: string): TimeUnit; - /** - * @return True iff the given year is a leap year. - */ - export function isLeapYear(year: number): boolean; - /** - * The days in a given year - */ - export function daysInYear(year: number): number; - /** - * @param year The full year - * @param month The month 1-12 - * @return The number of days in the given month - */ - export function daysInMonth(year: number, month: number): number; - /** - * Returns the day of the year of the given date [0..365]. January first is 0. - * - * @param year The year e.g. 1986 - * @param month Month 1-12 - * @param day Day of month 1-31 - */ - export function dayOfYear(year: number, month: number, day: number): number; - /** - * Returns the last instance of the given weekday in the given month - * - * @param year The year - * @param month the month 1-12 - * @param weekDay the desired week day - * - * @return the last occurrence of the week day in the month - */ - export function lastWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; - /** - * Returns the first instance of the given weekday in the given month - * - * @param year The year - * @param month the month 1-12 - * @param weekDay the desired week day - * - * @return the first occurrence of the week day in the month - */ - export function firstWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; - /** - * Returns the day-of-month that is on the given weekday and which is >= the given day. - * Throws if the month has no such day. - */ - export function weekDayOnOrAfter(year: number, month: number, day: number, weekDay: WeekDay): number; - /** - * Returns the day-of-month that is on the given weekday and which is <= the given day. - * Throws if the month has no such day. - */ - export function weekDayOnOrBefore(year: number, month: number, day: number, weekDay: WeekDay): number; - /** - * The week of this month. There is no official standard for this, - * but we assume the same rules for the weekNumber (i.e. - * week 1 is the week that has the 4th day of the month in it) - * - * @param year The year - * @param month The month [1-12] - * @param day The day [1-31] - * @return Week number [1-5] - */ - export function weekOfMonth(year: number, month: number, day: number): number; - /** - * The ISO 8601 week number for the given date. Week 1 is the week - * that has January 4th in it, and it starts on Monday. - * See https://en.wikipedia.org/wiki/ISO_week_date - * - * @param year Year e.g. 1988 - * @param month Month 1-12 - * @param day Day of month 1-31 - * - * @return Week number 1-53 - */ - export function weekNumber(year: number, month: number, day: number): number; - /** - * Convert a unix milli timestamp into a TimeT structure. - * This does NOT take leap seconds into account. - */ - export function unixToTimeNoLeapSecs(unixMillis: number): TimeStruct; - /** - * Convert a year, month, day etc into a unix milli timestamp. - * This does NOT take leap seconds into account. - * - * @param year Year e.g. 1970 - * @param month Month 1-12 - * @param day Day 1-31 - * @param hour Hour 0-23 - * @param minute Minute 0-59 - * @param second Second 0-59 (no leap seconds) - * @param milli Millisecond 0-999 - */ - export function timeToUnixNoLeapSecs(year?: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, milli?: number): number; - /** - * Convert a TimeT structure into a unix milli timestamp. - * This does NOT take leap seconds into account. - */ - export function timeToUnixNoLeapSecs(tm: TimeStruct): number; - /** - * Return the day-of-week. - * This does NOT take leap seconds into account. - */ - export function weekDayNoLeapSecs(unixMillis: number): WeekDay; - /** - * N-th second in the day, counting from 0 - */ - export function secondOfDay(hour: number, minute: number, second: number): number; - /** - * Basic representation of a date and time - */ - export class TimeStruct { - /** - * Year, 1970-... - */ - year: number; - /** - * Month 1-12 - */ - month: number; - /** - * Day of month, 1-31 - */ - day: number; - /** - * Hour 0-23 - */ - hour: number; - /** - * Minute 0-59 - */ - minute: number; - /** - * Seconds, 0-59 - */ - second: number; - /** - * Milliseconds 0-999 - */ - milli: number; - /** - * Create a TimeStruct from a number of unix milliseconds - */ - static fromUnix(unixMillis: number): TimeStruct; - /** - * Create a TimeStruct from a JavaScript date - * - * @param d The date - * @param df Which functions to take (getX() or getUTCX()) - */ - static fromDate(d: Date, df: DateFunctions): TimeStruct; - /** - * Returns a TimeStruct from an ISO 8601 string WITHOUT time zone - */ - static fromString(s: string): TimeStruct; - /** - * Constructor - * - * @param year Year e.g. 1970 - * @param month Month 1-12 - * @param day Day 1-31 - * @param hour Hour 0-23 - * @param minute Minute 0-59 - * @param second Second 0-59 (no leap seconds) - * @param milli Millisecond 0-999 - */ - constructor( - /** - * Year, 1970-... - */ - year?: number, - /** - * Month 1-12 - */ - month?: number, - /** - * Day of month, 1-31 - */ - day?: number, - /** - * Hour 0-23 - */ - hour?: number, - /** - * Minute 0-59 - */ - minute?: number, - /** - * Seconds, 0-59 - */ - second?: number, - /** - * Milliseconds 0-999 - */ - milli?: number); - /** - * Validate a TimeStruct, returns false if invalid. - */ - validate(): boolean; - /** - * The day-of-year 0-365 - */ - yearDay(): number; - /** - * Returns this time as a unix millisecond timestamp - * Does NOT take leap seconds into account. - */ - toUnixNoLeapSecs(): number; - /** - * Deep equals - */ - equals(other: TimeStruct): boolean; - /** - * < operator - */ - lessThan(other: TimeStruct): boolean; - clone(): TimeStruct; - valueOf(): number; - /** - * ISO 8601 string YYYY-MM-DDThh:mm:ss.nnn - */ - toString(): string; - inspect(): string; - } -} - -declare module '__timezonecomplete/datetime' { - import basics = require("__timezonecomplete/basics"); - import WeekDay = basics.WeekDay; - import TimeUnit = basics.TimeUnit; - import duration = require("__timezonecomplete/duration"); - import Duration = duration.Duration; - import javascript = require("__timezonecomplete/javascript"); - import DateFunctions = javascript.DateFunctions; - import timesource = require("__timezonecomplete/timesource"); - import TimeSource = timesource.TimeSource; - import timezone = require("__timezonecomplete/timezone"); - import TimeZone = timezone.TimeZone; - /** - * Current date+time in local time - */ - export function nowLocal(): DateTime; - /** - * Current date+time in UTC time - */ - export function nowUtc(): DateTime; - /** - * Current date+time in the given time zone - * @param timeZone The desired time zone (optional, defaults to UTC). - */ - export function now(timeZone?: TimeZone): DateTime; - /** - * DateTime class which is time zone-aware - * and which can be mocked for testing purposes. - */ - export class DateTime { - /** - * Actual time source in use. Setting this property allows to - * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() - * use this property for obtaining the current time. - */ - static timeSource: TimeSource; - /** - * Current date+time in local time - */ - static nowLocal(): DateTime; - /** - * Current date+time in UTC time - */ - static nowUtc(): DateTime; - /** - * Current date+time in the given time zone - * @param timeZone The desired time zone (optional, defaults to UTC). - */ - static now(timeZone?: TimeZone): DateTime; - /** - * Create a DateTime from a Lotus 123 / Microsoft Excel date-time value - * i.e. a double representing days since 1-1-1900 where 1900 is incorrectly seen as leap year - */ - static fromExcel(n: number, timeZone?: TimeZone): DateTime; - /** - * Constructor. Creates current time in local timezone. - */ - constructor(); - /** - * Constructor - * Non-existing local times are normalized by rounding up to the next DST offset. - * - * @param isoString String in ISO 8601 format. Instead of ISO time zone, - * it may include a space and then and IANA time zone. - * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) - * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) - * or "2007-04-05T12:30:40.500Z" (UTC) - * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) - * @param timeZone if given, the date in the string is assumed to be in this time zone. - * Note that it is NOT CONVERTED to the time zone. Useful - * for strings without a time zone - */ - constructor(isoString: string, timeZone?: TimeZone); - /** - * Constructor. You provide a date, then you say whether to take the - * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, - * and then you state which time zone that date is in. - * Non-existing local times are normalized by rounding up to the next DST offset. - * Note that the Date class has bugs and inconsistencies when constructing them with times around - * DST changes. - * - * @param date A date object. - * @param getters Specifies which set of Date getters contains the date in the given time zone: the - * Date.getXxx() methods or the Date.getUTCXxx() methods. - * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) - */ - constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); - /** - * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. - * Use the add(duration) or sub(duration) for arithmetic. - * @param year The full year (e.g. 2014) - * @param month The month [1-12] (note this deviates from JavaScript Date) - * @param day The day of the month [1-31] - * @param hour The hour of the day [0-24) - * @param minute The minute of the hour [0-59] - * @param second The second of the minute [0-59] - * @param millisecond The millisecond of the second [0-999] - * @param timeZone The time zone, or null (for unaware dates) - */ - constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); - /** - * Constructor - * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 - * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). - */ - constructor(unixTimestamp: number, timeZone?: TimeZone); - /** - * @return a copy of this object - */ - clone(): DateTime; - /** - * @return The time zone that the date is in. May be null for unaware dates. - */ - zone(): TimeZone; - /** - * Zone name abbreviation at this time - * @param dstDependent (default true) set to false for a DST-agnostic abbreviation - * @return The abbreviation - */ - zoneAbbreviation(dstDependent?: boolean): string; - /** - * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. - */ - offset(): number; - /** - * @return The full year e.g. 2014 - */ - year(): number; - /** - * @return The month 1-12 (note this deviates from JavaScript Date) - */ - month(): number; - /** - * @return The day of the month 1-31 - */ - day(): number; - /** - * @return The hour 0-23 - */ - hour(): number; - /** - * @return the minutes 0-59 - */ - minute(): number; - /** - * @return the seconds 0-59 - */ - second(): number; - /** - * @return the milliseconds 0-999 - */ - millisecond(): number; - /** - * @return the day-of-week (the enum values correspond to JavaScript - * week day numbers) - */ - weekDay(): WeekDay; - /** - * Returns the day number within the year: Jan 1st has number 0, - * Jan 2nd has number 1 etc. - * - * @return the day-of-year [0-366] - */ - dayOfYear(): number; - /** - * The ISO 8601 week number. Week 1 is the week - * that has January 4th in it, and it starts on Monday. - * See https://en.wikipedia.org/wiki/ISO_week_date - * - * @return Week number [1-53] - */ - weekNumber(): number; - /** - * The week of this month. There is no official standard for this, - * but we assume the same rules for the weekNumber (i.e. - * week 1 is the week that has the 4th day of the month in it) - * - * @return Week number [1-5] - */ - weekOfMonth(): number; - /** - * Returns the number of seconds that have passed on the current day - * Does not consider leap seconds - * - * @return seconds [0-86399] - */ - secondOfDay(): number; - /** - * @return Milliseconds since 1970-01-01T00:00:00.000Z - */ - unixUtcMillis(): number; - /** - * @return The full year e.g. 2014 - */ - utcYear(): number; - /** - * @return The UTC month 1-12 (note this deviates from JavaScript Date) - */ - utcMonth(): number; - /** - * @return The UTC day of the month 1-31 - */ - utcDay(): number; - /** - * @return The UTC hour 0-23 - */ - utcHour(): number; - /** - * @return The UTC minutes 0-59 - */ - utcMinute(): number; - /** - * @return The UTC seconds 0-59 - */ - utcSecond(): number; - /** - * Returns the UTC day number within the year: Jan 1st has number 0, - * Jan 2nd has number 1 etc. - * - * @return the day-of-year [0-366] - */ - utcDayOfYear(): number; - /** - * @return The UTC milliseconds 0-999 - */ - utcMillisecond(): number; - /** - * @return the UTC day-of-week (the enum values correspond to JavaScript - * week day numbers) - */ - utcWeekDay(): WeekDay; - /** - * The ISO 8601 UTC week number. Week 1 is the week - * that has January 4th in it, and it starts on Monday. - * See https://en.wikipedia.org/wiki/ISO_week_date - * - * @return Week number [1-53] - */ - utcWeekNumber(): number; - /** - * The week of this month. There is no official standard for this, - * but we assume the same rules for the weekNumber (i.e. - * week 1 is the week that has the 4th day of the month in it) - * - * @return Week number [1-5] - */ - utcWeekOfMonth(): number; - /** - * Returns the number of seconds that have passed on the current day - * Does not consider leap seconds - * - * @return seconds [0-86399] - */ - utcSecondOfDay(): number; - /** - * Convert this date to the given time zone (in-place). - * Throws if this date does not have a time zone. - * @return this (for chaining) - */ - convert(zone?: TimeZone): DateTime; - /** - * Returns this date converted to the given time zone. - * Unaware dates can only be converted to unaware dates (clone) - * Converting an unaware date to an aware date throws an exception. Use the constructor - * if you really need to do that. - * - * @param zone The new time zone. This may be null to create unaware date. - * @return The converted date - */ - toZone(zone?: TimeZone): DateTime; - /** - * Convert to JavaScript date with the zone time in the getX() methods. - * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. - * This is because Date calculates getUTCX() from getX() applying local time zone. - */ - toDate(): Date; - /** - * Add a time duration relative to UTC. - * @return this + duration - */ - add(duration: Duration): DateTime; - /** - * Add an amount of time relative to UTC, as regularly as possible. - * - * Adding e.g. 1 hour will increment the utcHour() field, adding 1 month - * increments the utcMonth() field. - * Adding an amount of units leaves lower units intact. E.g. - * adding a month will leave the day() field untouched if possible. - * - * Note adding Months or Years will clamp the date to the end-of-month if - * the start date was at the end of a month, i.e. contrary to JavaScript - * Date#setUTCMonth() it will not overflow into the next month - * - * In case of DST changes, the utc time fields are still untouched but local - * time fields may shift. - */ - add(amount: number, unit: TimeUnit): DateTime; - /** - * Add an amount of time to the zone time, as regularly as possible. - * - * Adding e.g. 1 hour will increment the hour() field of the zone - * date by one. In case of DST changes, the time fields may additionally - * increase by the DST offset, if a non-existing local time would - * be reached otherwise. - * - * Adding a unit of time will leave lower-unit fields intact, unless the result - * would be a non-existing time. Then an extra DST offset is added. - * - * Note adding Months or Years will clamp the date to the end-of-month if - * the start date was at the end of a month, i.e. contrary to JavaScript - * Date#setUTCMonth() it will not overflow into the next month - */ - addLocal(duration: Duration): DateTime; - addLocal(amount: number, unit: TimeUnit): DateTime; - /** - * Same as add(-1*duration); - */ - sub(duration: Duration): DateTime; - /** - * Same as add(-1*amount, unit); - */ - sub(amount: number, unit: TimeUnit): DateTime; - /** - * Same as addLocal(-1*amount, unit); - */ - subLocal(duration: Duration): DateTime; - subLocal(amount: number, unit: TimeUnit): DateTime; - /** - * Time difference between two DateTimes - * @return this - other - */ - diff(other: DateTime): Duration; - /** - * Chops off the time part, yields the same date at 00:00:00.000 - * @return a new DateTime - */ - startOfDay(): DateTime; - /** - * @return True iff (this < other) - */ - lessThan(other: DateTime): boolean; - /** - * @return True iff (this <= other) - */ - lessEqual(other: DateTime): boolean; - /** - * @return True iff this and other represent the same moment in time in UTC - */ - equals(other: DateTime): boolean; - /** - * @return True iff this and other represent the same time and the same zone - */ - identical(other: DateTime): boolean; - /** - * @return True iff this > other - */ - greaterThan(other: DateTime): boolean; - /** - * @return True iff this >= other - */ - greaterEqual(other: DateTime): boolean; - /** - * @return The minimum of this and other - */ - min(other: DateTime): DateTime; - /** - * @return The maximum of this and other - */ - max(other: DateTime): DateTime; - /** - * Proper ISO 8601 format string with any IANA zone converted to ISO offset - * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam - */ - toIsoString(): string; - /** - * Return a string representation of the DateTime according to the - * specified format. The format is implemented as the LDML standard - * (http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns) - * - * @param formatString The format specification (e.g. "dd/MM/yyyy HH:mm:ss") - * @return The string representation of this DateTime - */ - format(formatString: string): string; - /** - * Modified ISO 8601 format string with IANA name if applicable. - * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" - */ - toString(): string; - /** - * Used by util.inspect() - */ - inspect(): string; - /** - * The valueOf() method returns the primitive value of the specified object. - */ - valueOf(): any; - /** - * Modified ISO 8601 format string in UTC without time zone info - */ - toUtcString(): string; - } -} - -declare module '__timezonecomplete/duration' { - import basics = require("__timezonecomplete/basics"); - import TimeUnit = basics.TimeUnit; - /** - * Construct a time duration - * @param n Number of years (may be fractional or negative) - * @return A duration of n years - */ - export function years(n: number): Duration; - /** - * Construct a time duration - * @param n Number of months (may be fractional or negative) - * @return A duration of n months - */ - export function months(n: number): Duration; - /** - * Construct a time duration - * @param n Number of days (may be fractional or negative) - * @return A duration of n days - */ - export function days(n: number): Duration; - /** - * Construct a time duration - * @param n Number of hours (may be fractional or negative) - * @return A duration of n hours - */ - export function hours(n: number): Duration; - /** - * Construct a time duration - * @param n Number of minutes (may be fractional or negative) - * @return A duration of n minutes - */ - export function minutes(n: number): Duration; - /** - * Construct a time duration - * @param n Number of seconds (may be fractional or negative) - * @return A duration of n seconds - */ - export function seconds(n: number): Duration; - /** - * Construct a time duration - * @param n Number of milliseconds (may be fractional or negative) - * @return A duration of n milliseconds - */ - export function milliseconds(n: number): Duration; - /** - * Time duration which is represented as an amount and a unit e.g. - * '1 Month' or '166 Seconds'. The unit is preserved through calculations. - * - * It has two sets of getter functions: - * - second(), minute(), hour() etc, singular form: these can be used to create string representations. - * These return a part of your string representation. E.g. for 2500 milliseconds, the millisecond() part would be 500 - * - seconds(), minutes(), hours() etc, plural form: these return the total amount represented in the corresponding unit. - */ - export class Duration { - /** - * Construct a time duration - * @param n Number of years (may be fractional or negative) - * @return A duration of n years - */ - static years(n: number): Duration; - /** - * Construct a time duration - * @param n Number of months (may be fractional or negative) - * @return A duration of n months - */ - static months(n: number): Duration; - /** - * Construct a time duration - * @param n Number of days (may be fractional or negative) - * @return A duration of n days - */ - static days(n: number): Duration; - /** - * Construct a time duration - * @param n Number of hours (may be fractional or negative) - * @return A duration of n hours - */ - static hours(n: number): Duration; - /** - * Construct a time duration - * @param n Number of minutes (may be fractional or negative) - * @return A duration of n minutes - */ - static minutes(n: number): Duration; - /** - * Construct a time duration - * @param n Number of seconds (may be fractional or negative) - * @return A duration of n seconds - */ - static seconds(n: number): Duration; - /** - * Construct a time duration - * @param n Number of milliseconds (may be fractional or negative) - * @return A duration of n milliseconds - */ - static milliseconds(n: number): Duration; - /** - * Construct a time duration of 0 - */ - constructor(); - /** - * Construct a time duration from a string in one of two formats: - * 1) [-]hhhh[:mm[:ss[.nnn]]] e.g. '-01:00:30.501' - * 2) amount and unit e.g. '-1 days' or '1 year'. The unit may be in singular or plural form and is case-insensitive - */ - constructor(input: string); - /** - * Construct a duration from an amount and a time unit. - * @param amount Number of units - * @param unit A time unit i.e. TimeUnit.Second, TimeUnit.Hour etc. Default Millisecond. - */ - constructor(amount: number, unit?: TimeUnit); - /** - * @return another instance of Duration with the same value. - */ - clone(): Duration; - /** - * Returns this duration expressed in different unit (positive or negative, fractional). - * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). - * It is approximate for any other conversion - */ - as(unit: TimeUnit): number; - /** - * Convert this duration to a Duration in another unit. You always get a clone even if you specify - * the same unit. - * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). - * It is approximate for any other conversion - */ - convert(unit: TimeUnit): Duration; - /** - * The entire duration in milliseconds (negative or positive) - * For Day/Month/Year durations, this is approximate! - */ - milliseconds(): number; - /** - * The millisecond part of the duration (always positive) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 400 for a -01:02:03.400 duration - */ - millisecond(): number; - /** - * The entire duration in seconds (negative or positive, fractional) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 1.5 for a 1500 milliseconds duration - */ - seconds(): number; - /** - * The second part of the duration (always positive) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 3 for a -01:02:03.400 duration - */ - second(): number; - /** - * The entire duration in minutes (negative or positive, fractional) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 1.5 for a 90000 milliseconds duration - */ - minutes(): number; - /** - * The minute part of the duration (always positive) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 2 for a -01:02:03.400 duration - */ - minute(): number; - /** - * The entire duration in hours (negative or positive, fractional) - * For Day/Month/Year durations, this is approximate! - * @return e.g. 1.5 for a 5400000 milliseconds duration - */ - hours(): number; - /** - * The hour part of a duration. This assumes that a day has 24 hours (which is not the case - * during DST changes). - */ - hour(): number; - /** - * DEPRECATED - * The hour part of the duration (always positive). - * Note that this part can exceed 23 hours, because for - * now, we do not have a days() function - * For Day/Month/Year durations, this is approximate! - * @return e.g. 25 for a -25:02:03.400 duration - */ - wholeHours(): number; - /** - * The entire duration in days (negative or positive, fractional) - * This is approximate if this duration is not in days! - */ - days(): number; - /** - * The day part of a duration. This assumes that a month has 30 days. - */ - day(): number; - /** - * The entire duration in days (negative or positive, fractional) - * This is approximate if this duration is not in Months or Years! - */ - months(): number; - /** - * The month part of a duration. - */ - month(): number; - /** - * The entire duration in years (negative or positive, fractional) - * This is approximate if this duration is not in Months or Years! - */ - years(): number; - /** - * Non-fractional positive years - */ - wholeYears(): number; - /** - * Amount of units (positive or negative, fractional) - */ - amount(): number; - /** - * The unit this duration was created with - */ - unit(): TimeUnit; - /** - * Sign - * @return "-" if the duration is negative - */ - sign(): string; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff (this < other) - */ - lessThan(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff (this <= other) - */ - lessEqual(other: Duration): boolean; - /** - * Similar but not identical - * Approximate if the durations have units that cannot be converted - * @return True iff this and other represent the same time duration - */ - equals(other: Duration): boolean; - /** - * Similar but not identical - * Returns false if we cannot determine whether they are equal in all time zones - * so e.g. 60 minutes equals 1 hour, but 24 hours do NOT equal 1 day - * - * @return True iff this and other represent the same time duration - */ - equalsExact(other: Duration): boolean; - /** - * Same unit and same amount - */ - identical(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff this > other - */ - greaterThan(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return True iff this >= other - */ - greaterEqual(other: Duration): boolean; - /** - * Approximate if the durations have units that cannot be converted - * @return The minimum (most negative) of this and other - */ - min(other: Duration): Duration; - /** - * Approximate if the durations have units that cannot be converted - * @return The maximum (most positive) of this and other - */ - max(other: Duration): Duration; - /** - * Approximate if the durations have units that cannot be converted - * Multiply with a fixed number. - * @return a new Duration of (this * value) - */ - multiply(value: number): Duration; - /** - * Approximate if the durations have units that cannot be converted - * Divide by a fixed number. - * @return a new Duration of (this / value) - */ - divide(value: number): Duration; - /** - * Add a duration. - * @return a new Duration of (this + value) with the unit of this duration - */ - add(value: Duration): Duration; - /** - * Subtract a duration. - * @return a new Duration of (this - value) with the unit of this duration - */ - sub(value: Duration): Duration; - /** - * Return the absolute value of the duration i.e. remove the sign. - */ - abs(): Duration; - /** - * DEPRECATED - * String in [-]hhhh:mm:ss.nnn notation. All fields are - * always present except the sign. - */ - toFullString(): string; - /** - * String in [-]hhhh:mm[:ss[.nnn]] notation. - * @param full If true, then all fields are always present except the sign. Otherwise, seconds and milliseconds - * are chopped off if zero - */ - toHmsString(full?: boolean): string; - /** - * String in ISO 8601 notation e.g. 'P1M' for one month or 'PT1M' for one minute - */ - toIsoString(): string; - /** - * String representation with amount and unit e.g. '1.5 years' or '-1 day' - */ - toString(): string; - /** - * Used by util.inspect() - */ - inspect(): string; - /** - * The valueOf() method returns the primitive value of the specified object. - */ - valueOf(): any; - } -} - -declare module '__timezonecomplete/javascript' { - /** - * Indicates how a Date object should be interpreted. - * Either we can take getYear(), getMonth() etc for our field - * values, or we can take getUTCYear(), getUtcMonth() etc to do that. - */ - export enum DateFunctions { - /** - * Use the Date.getFullYear(), Date.getMonth(), ... functions. - */ - Get = 0, - /** - * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. - */ - GetUTC = 1, - } -} - -declare module '__timezonecomplete/period' { - import basics = require("__timezonecomplete/basics"); - import TimeUnit = basics.TimeUnit; - import duration = require("__timezonecomplete/duration"); - import Duration = duration.Duration; - import datetime = require("__timezonecomplete/datetime"); - import DateTime = datetime.DateTime; - /** - * Specifies how the period should repeat across the day - * during DST changes. - */ - export enum PeriodDst { - /** - * Keep repeating in similar intervals measured in UTC, - * unaffected by Daylight Saving Time. - * E.g. a repetition of one hour will take one real hour - * every time, even in a time zone with DST. - * Leap seconds, leap days and month length - * differences will still make the intervals different. - */ - RegularIntervals = 0, - /** - * Ensure that the time at which the intervals occur stay - * at the same place in the day, local time. So e.g. - * a period of one day, starting at 8:05AM Europe/Amsterdam time - * will always start at 8:05 Europe/Amsterdam. This means that - * in UTC time, some intervals will be 25 hours and some - * 23 hours during DST changes. - * Another example: an hourly interval will be hourly in local time, - * skipping an hour in UTC for a DST backward change. - */ - RegularLocalTime = 1, - /** - * End-of-enum marker - */ - MAX = 2, - } - /** - * Convert a PeriodDst to a string: "regular intervals" or "regular local time" - */ - export function periodDstToString(p: PeriodDst): string; - /** - * Repeating time period: consists of a starting point and - * a time length. This class accounts for leap seconds and leap days. - */ - export class Period { - /** - * Constructor - * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, - * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. - * This is due to the enormous processing power required by these cases. They are not - * implemented and you will get an assert. - * - * @param start The start of the period. If the period is in Months or Years, and - * the day is 29 or 30 or 31, the results are maximised to end-of-month. - * @param interval The interval of the period - * @param dst Specifies how to handle Daylight Saving Time. Not relevant - * if the time zone of the start datetime does not have DST. - * Defaults to RegularLocalTime. - */ - constructor(start: DateTime, interval: Duration, dst?: PeriodDst); - /** - * Constructor - * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, - * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. - * This is due to the enormous processing power required by these cases. They are not - * implemented and you will get an assert. - * - * @param start The start of the period. If the period is in Months or Years, and - * the day is 29 or 30 or 31, the results are maximised to end-of-month. - * @param amount The amount of units. - * @param unit The unit. - * @param dst Specifies how to handle Daylight Saving Time. Not relevant - * if the time zone of the start datetime does not have DST. - * Defaults to RegularLocalTime. - */ - constructor(start: DateTime, amount: number, unit: TimeUnit, dst?: PeriodDst); - /** - * The start date - */ - start(): DateTime; - /** - * The interval - */ - interval(): Duration; - /** - * DEPRECATED - * The amount of units of the interval - */ - amount(): number; - /** - * DEPRECATED - * The unit of the interval - */ - unit(): TimeUnit; - /** - * The dst handling mode - */ - dst(): PeriodDst; - /** - * The first occurrence of the period greater than - * the given date. The given date need not be at a period boundary. - * Pre: the fromdate and startdate must either both have timezones or not - * @param fromDate: the date after which to return the next date - * @return the first date matching the period after fromDate, given - * in the same zone as the fromDate. - */ - findFirst(fromDate: DateTime): DateTime; - /** - * Returns the next timestamp in the period. The given timestamp must - * be at a period boundary, otherwise the answer is incorrect. - * This function has MUCH better performance than findFirst. - * Returns the datetime "count" times away from the given datetime. - * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. - * @param count Optional, must be >= 1 and whole. - * @return (prev + count * period), in the same timezone as prev. - */ - findNext(prev: DateTime, count?: number): DateTime; - /** - * Checks whether the given date is on a period boundary - * (expensive!) - */ - isBoundary(occurrence: DateTime): boolean; - /** - * Returns true iff this period has the same effect as the given one. - * i.e. a period of 24 hours is equal to one of 1 day if they have the same UTC start moment - * and same dst. - */ - equals(other: Period): boolean; - /** - * Returns true iff this period was constructed with identical arguments to the other one. - */ - identical(other: Period): boolean; - /** - * Returns an ISO duration string e.g. - * 2014-01-01T12:00:00.000+01:00/P1H - * 2014-01-01T12:00:00.000+01:00/PT1M (one minute) - * 2014-01-01T12:00:00.000+01:00/P1M (one month) - */ - toIsoString(): string; - /** - * A string representation e.g. - * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam, keeping regular intervals". - */ - toString(): string; - /** - * Used by util.inspect() - */ - inspect(): string; - } -} - -declare module '__timezonecomplete/timesource' { - /** - * For testing purposes, we often need to manipulate what the current - * time is. This is an interface for a custom time source object - * so in tests you can use a custom time source. - */ - export interface TimeSource { - /** - * Return the current date+time as a javascript Date object - */ - now(): Date; - } - /** - * Default time source, returns actual time - */ - export class RealTimeSource implements TimeSource { - now(): Date; - } -} - -declare module '__timezonecomplete/timezone' { - import javascript = require("__timezonecomplete/javascript"); - import DateFunctions = javascript.DateFunctions; - /** - * The local time zone for a given date as per OS settings. Note that time zones are cached - * so you don't necessarily get a new object each time. - */ - export function local(): TimeZone; - /** - * Coordinated Universal Time zone. Note that time zones are cached - * so you don't necessarily get a new object each time. - */ - export function utc(): TimeZone; - /** - * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30. Note that time zones are cached - * so you don't necessarily get a new object each time. - * @returns a time zone with the given fixed offset - */ - export function zone(offset: number): TimeZone; - /** - * Time zone for an offset string or an IANA time zone string. Note that time zones are cached - * so you don't necessarily get a new object each time. - * @param s Empty string for no time zone (null is returned), - * "localtime" for local time, - * a TZ database time zone name (e.g. Europe/Amsterdam), - * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: - * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for - * "localtime", timezonecomplete will adhere to the computer settings, the DST flag - * does not have any effect. - */ - export function zone(name: string, dst?: boolean): TimeZone; - /** - * The type of time zone - */ - export enum TimeZoneKind { - /** - * Local time offset as determined by JavaScript Date class. - */ - Local = 0, - /** - * Fixed offset from UTC, without DST. - */ - Offset = 1, - /** - * IANA timezone managed through Olsen TZ database. Includes - * DST if applicable. - */ - Proper = 2, - } - /** - * Option for TimeZone#normalizeLocal() - */ - export enum NormalizeOption { - /** - * Normalize non-existing times by ADDING the DST offset - */ - Up = 0, - /** - * Normalize non-existing times by SUBTRACTING the DST offset - */ - Down = 1, - } - /** - * Time zone. The object is immutable because it is cached: - * requesting a time zone twice yields the very same object. - * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), - * i.e. offset 90 means +01:30. - * - * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, - * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST - * applied depending on the time zone rules. - */ - export class TimeZone { - /** - * The local time zone for a given date. Note that - * the time zone varies with the date: amsterdam time for - * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 - */ - static local(): TimeZone; - /** - * The UTC time zone. - */ - static utc(): TimeZone; - /** - * Time zone with a fixed offset - * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30 - */ - static zone(offset: number): TimeZone; - /** - * Time zone for an offset string or an IANA time zone string. Note that time zones are cached - * so you don't necessarily get a new object each time. - * @param s Empty string for no time zone (null is returned), - * "localtime" for local time, - * a TZ database time zone name (e.g. Europe/Amsterdam), - * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: - * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - * TZ database zone name may be suffixed with " without DST" to indicate no DST should be applied. - * In that case, the dst parameter is ignored. - * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for - * "localtime", timezonecomplete will adhere to the computer settings, the DST flag - * does not have any effect. - */ - static zone(s: string, dst?: boolean): TimeZone; - /** - * Do not use this constructor, use the static - * TimeZone.zone() method instead. - * @param name NORMALIZED name, assumed to be correct - * @param dst Adhere to Daylight Saving Time if applicable, ignored for local time and fixed offsets - */ - constructor(name: string, dst?: boolean); - /** - * The time zone identifier. Can be an offset "-01:30" or an - * IANA time zone name "Europe/Amsterdam", or "localtime" for - * the local time zone. - */ - name(): string; - dst(): boolean; - /** - * The kind of time zone (Local/Offset/Proper) - */ - kind(): TimeZoneKind; - /** - * Equality operator. Maps zero offsets and different names for UTC onto - * each other. Other time zones are not mapped onto each other. - */ - equals(other: TimeZone): boolean; - /** - * Returns true iff the constructor arguments were identical, so UTC !== GMT - */ - identical(other: TimeZone): boolean; - /** - * Is this zone equivalent to UTC? - */ - isUtc(): boolean; - /** - * Does this zone have Daylight Saving Time at all? - */ - hasDst(): boolean; - /** - * Calculate timezone offset from a UTC time. - * - * @param year Full year - * @param month Month 1-12 (note this deviates from JavaScript date) - * @param day Day of month 1-31 - * @param hour Hour 0-23 - * @param minute Minute 0-59 - * @param second Second 0-59 - * @param millisecond Millisecond 0-999 - * - * @return the offset of this time zone with respect to UTC at the given time, in minutes. - */ - offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; - /** - * Calculate timezone offset from a zone-local time (NOT a UTC time). - * @param year local full year - * @param month local month 1-12 (note this deviates from JavaScript date) - * @param day local day of month 1-31 - * @param hour local hour 0-23 - * @param minute local minute 0-59 - * @param second local second 0-59 - * @param millisecond local millisecond 0-999 - * @return the offset of this time zone with respect to UTC at the given time, in minutes. - */ - offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; - /** - * Note: will be removed in version 2.0.0 - * - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ - offsetForUtcDate(date: Date, funcs: DateFunctions): number; - /** - * Note: will be removed in version 2.0.0 - * - * Convenience function, takes values from a Javascript Date - * Calls offsetForUtc() with the contents of the date - * - * @param date: the date - * @param funcs: the set of functions to use: get() or getUTC() - */ - offsetForZoneDate(date: Date, funcs: DateFunctions): number; - /** - * Zone abbreviation at given UTC timestamp e.g. CEST for Central European Summer Time. - * - * @param year Full year - * @param month Month 1-12 (note this deviates from JavaScript date) - * @param day Day of month 1-31 - * @param hour Hour 0-23 - * @param minute Minute 0-59 - * @param second Second 0-59 - * @param millisecond Millisecond 0-999 - * @param dstDependent (default true) set to false for a DST-agnostic abbreviation - * - * @return "local" for local timezone, the offset for an offset zone, or the abbreviation for a proper zone. - */ - abbreviationForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, dstDependent?: boolean): string; - /** - * Normalizes non-existing local times by adding a forward offset change. - * During a forward standard offset change or DST offset change, some amount of - * local time is skipped. Therefore, this amount of local time does not exist. - * This function adds the amount of forward change to any non-existing time. After all, - * this is probably what the user meant. - * - * @param localUnixMillis Unix timestamp in zone time - * @param opt (optional) Round up or down? Default: up - * - * @returns Unix timestamp in zone time, normalized. - */ - normalizeZoneTime(localUnixMillis: number, opt?: NormalizeOption): number; - /** - * The time zone identifier (normalized). - * Either "localtime", IANA name, or "+hh:mm" offset. - */ - toString(): string; - /** - * Used by util.inspect() - */ - inspect(): string; - /** - * Convert an offset number into an offset string - * @param offset The offset in minutes from UTC e.g. 90 minutes - * @return the offset in ISO notation "+01:30" for +90 minutes - */ - static offsetToString(offset: number): string; - /** - * String to offset conversion. - * @param s Formats: "-01:00", "-0100", "-01", "Z" - * @return offset w.r.t. UTC in minutes - */ - static stringToOffset(s: string): number; - } -} - -declare module '__timezonecomplete/globals' { - import datetime = require("__timezonecomplete/datetime"); - import DateTime = datetime.DateTime; - import duration = require("__timezonecomplete/duration"); - import Duration = duration.Duration; - /** - * Returns the minimum of two DateTimes - */ - export function min(d1: DateTime, d2: DateTime): DateTime; - /** - * Returns the minimum of two Durations - */ - export function min(d1: Duration, d2: Duration): Duration; - /** - * Returns the maximum of two DateTimes - */ - export function max(d1: DateTime, d2: DateTime): DateTime; - /** - * Returns the maximum of two Durations - */ - export function max(d1: Duration, d2: Duration): Duration; - /** - * Returns the absolute value of a Duration - */ - export function abs(d: Duration): Duration; -} +// Type definitions for timezonecomplete 1.15.0 +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'timezonecomplete' { + import basics = require("__timezonecomplete/basics"); + export import TimeUnit = basics.TimeUnit; + export import WeekDay = basics.WeekDay; + export import timeUnitToMilliseconds = basics.timeUnitToMilliseconds; + export import isLeapYear = basics.isLeapYear; + export import daysInMonth = basics.daysInMonth; + export import daysInYear = basics.daysInYear; + export import firstWeekDayOfMonth = basics.firstWeekDayOfMonth; + export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; + export import weekDayOnOrAfter = basics.weekDayOnOrAfter; + export import weekDayOnOrBefore = basics.weekDayOnOrBefore; + export import weekNumber = basics.weekNumber; + export import weekOfMonth = basics.weekOfMonth; + export import dayOfYear = basics.dayOfYear; + export import secondOfDay = basics.secondOfDay; + export import timeUnitToString = basics.timeUnitToString; + export import stringToTimeUnit = basics.stringToTimeUnit; + import datetime = require("__timezonecomplete/datetime"); + export import DateTime = datetime.DateTime; + export import now = datetime.now; + export import nowLocal = datetime.nowLocal; + export import nowUtc = datetime.nowUtc; + import duration = require("__timezonecomplete/duration"); + export import Duration = duration.Duration; + export import years = duration.years; + export import months = duration.months; + export import days = duration.days; + export import hours = duration.hours; + export import minutes = duration.minutes; + export import seconds = duration.seconds; + export import milliseconds = duration.milliseconds; + import javascript = require("__timezonecomplete/javascript"); + export import DateFunctions = javascript.DateFunctions; + import period = require("__timezonecomplete/period"); + export import Period = period.Period; + export import PeriodDst = period.PeriodDst; + export import periodDstToString = period.periodDstToString; + import timesource = require("__timezonecomplete/timesource"); + export import TimeSource = timesource.TimeSource; + export import RealTimeSource = timesource.RealTimeSource; + import timezone = require("__timezonecomplete/timezone"); + export import NormalizeOption = timezone.NormalizeOption; + export import TimeZoneKind = timezone.TimeZoneKind; + export import TimeZone = timezone.TimeZone; + export import local = timezone.local; + export import utc = timezone.utc; + export import zone = timezone.zone; + import globals = require("__timezonecomplete/globals"); + export import min = globals.min; + export import max = globals.max; +} + +declare module '__timezonecomplete/basics' { + import javascript = require("__timezonecomplete/javascript"); + import DateFunctions = javascript.DateFunctions; + /** + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc + */ + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } + /** + * Time units + */ + export enum TimeUnit { + Millisecond = 0, + Second = 1, + Minute = 2, + Hour = 3, + Day = 4, + Week = 5, + Month = 6, + Year = 7, + /** + * End-of-enum marker, do not use + */ + MAX = 8, + } + /** + * Approximate number of milliseconds for a time unit. + * A day is assumed to have 24 hours, a month is assumed to equal 30 days + * and a year is set to 360 days (because 12 months of 30 days). + * + * @param unit Time unit e.g. TimeUnit.Month + * @returns The number of milliseconds. + */ + export function timeUnitToMilliseconds(unit: TimeUnit): number; + /** + * Time unit to lowercase string. If amount is specified, then the string is put in plural form + * if necessary. + * @param unit The unit + * @param amount If this is unequal to -1 and 1, then the result is pluralized + */ + export function timeUnitToString(unit: TimeUnit, amount?: number): string; + export function stringToTimeUnit(s: string): TimeUnit; + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * The days in a given year + */ + export function daysInYear(year: number): number; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns the day of the year of the given date [0..365]. January first is 0. + * + * @param year The year e.g. 1986 + * @param month Month 1-12 + * @param day Day of month 1-31 + */ + export function dayOfYear(year: number, month: number, day: number): number; + /** + * Returns the last instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the last occurrence of the week day in the month + */ + export function lastWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the first instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the first occurrence of the week day in the month + */ + export function firstWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is >= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrAfter(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is <= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrBefore(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @param year The year + * @param month The month [1-12] + * @param day The day [1-31] + * @return Week number [1-5] + */ + export function weekOfMonth(year: number, month: number, day: number): number; + /** + * The ISO 8601 week number for the given date. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @param year Year e.g. 1988 + * @param month Month 1-12 + * @param day Day of month 1-31 + * + * @return Week number 1-53 + */ + export function weekNumber(year: number, month: number, day: number): number; + /** + * Convert a unix milli timestamp into a TimeT structure. + * This does NOT take leap seconds into account. + */ + export function unixToTimeNoLeapSecs(unixMillis: number): TimeStruct; + /** + * Convert a year, month, day etc into a unix milli timestamp. + * This does NOT take leap seconds into account. + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + export function timeToUnixNoLeapSecs(year?: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, milli?: number): number; + /** + * Convert a TimeT structure into a unix milli timestamp. + * This does NOT take leap seconds into account. + */ + export function timeToUnixNoLeapSecs(tm: TimeStruct): number; + /** + * Return the day-of-week. + * This does NOT take leap seconds into account. + */ + export function weekDayNoLeapSecs(unixMillis: number): WeekDay; + /** + * N-th second in the day, counting from 0 + */ + export function secondOfDay(hour: number, minute: number, second: number): number; + /** + * Basic representation of a date and time + */ + export class TimeStruct { + /** + * Year, 1970-... + */ + year: number; + /** + * Month 1-12 + */ + month: number; + /** + * Day of month, 1-31 + */ + day: number; + /** + * Hour 0-23 + */ + hour: number; + /** + * Minute 0-59 + */ + minute: number; + /** + * Seconds, 0-59 + */ + second: number; + /** + * Milliseconds 0-999 + */ + milli: number; + /** + * Create a TimeStruct from a number of unix milliseconds + */ + static fromUnix(unixMillis: number): TimeStruct; + /** + * Create a TimeStruct from a JavaScript date + * + * @param d The date + * @param df Which functions to take (getX() or getUTCX()) + */ + static fromDate(d: Date, df: DateFunctions): TimeStruct; + /** + * Returns a TimeStruct from an ISO 8601 string WITHOUT time zone + */ + static fromString(s: string): TimeStruct; + /** + * Constructor + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + constructor( + /** + * Year, 1970-... + */ + year?: number, + /** + * Month 1-12 + */ + month?: number, + /** + * Day of month, 1-31 + */ + day?: number, + /** + * Hour 0-23 + */ + hour?: number, + /** + * Minute 0-59 + */ + minute?: number, + /** + * Seconds, 0-59 + */ + second?: number, + /** + * Milliseconds 0-999 + */ + milli?: number); + /** + * Validate a TimeStruct, returns false if invalid. + */ + validate(): boolean; + /** + * The day-of-year 0-365 + */ + yearDay(): number; + /** + * Returns this time as a unix millisecond timestamp + * Does NOT take leap seconds into account. + */ + toUnixNoLeapSecs(): number; + /** + * Deep equals + */ + equals(other: TimeStruct): boolean; + /** + * < operator + */ + lessThan(other: TimeStruct): boolean; + clone(): TimeStruct; + valueOf(): number; + /** + * ISO 8601 string YYYY-MM-DDThh:mm:ss.nnn + */ + toString(): string; + inspect(): string; + } +} + +declare module '__timezonecomplete/datetime' { + import basics = require("__timezonecomplete/basics"); + import WeekDay = basics.WeekDay; + import TimeUnit = basics.TimeUnit; + import duration = require("__timezonecomplete/duration"); + import Duration = duration.Duration; + import javascript = require("__timezonecomplete/javascript"); + import DateFunctions = javascript.DateFunctions; + import timesource = require("__timezonecomplete/timesource"); + import TimeSource = timesource.TimeSource; + import timezone = require("__timezonecomplete/timezone"); + import TimeZone = timezone.TimeZone; + /** + * Current date+time in local time + */ + export function nowLocal(): DateTime; + /** + * Current date+time in UTC time + */ + export function nowUtc(): DateTime; + /** + * Current date+time in the given time zone + * @param timeZone The desired time zone (optional, defaults to UTC). + */ + export function now(timeZone?: TimeZone): DateTime; + /** + * DateTime class which is time zone-aware + * and which can be mocked for testing purposes. + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: TimeSource; + /** + * Current date+time in local time + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone + * @param timeZone The desired time zone (optional, defaults to UTC). + */ + static now(timeZone?: TimeZone): DateTime; + /** + * Create a DateTime from a Lotus 123 / Microsoft Excel date-time value + * i.e. a double representing days since 1-1-1900 where 1900 is incorrectly seen as leap year + */ + static fromExcel(n: number, timeZone?: TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * Non-existing local times are normalized by rounding up to the next DST offset. + * + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * Non-existing local times are normalized by rounding up to the next DST offset. + * Note that the Date class has bugs and inconsistencies when constructing them with times around + * DST changes. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: DateFunctions, timeZone?: TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): TimeZone; + /** + * Zone name abbreviation at this time + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * @return The abbreviation + */ + zoneAbbreviation(dstDependent?: boolean): string; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): WeekDay; + /** + * Returns the day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + dayOfYear(): number; + /** + * The ISO 8601 week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + weekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + weekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + secondOfDay(): number; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * Returns the UTC day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + utcDayOfYear(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): WeekDay; + /** + * The ISO 8601 UTC week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + utcWeekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + utcWeekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + utcSecondOfDay(): number; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * Converting an unaware date to an aware date throws an exception. Use the constructor + * if you really need to do that. + * + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + * This is because Date calculates getUTCX() from getX() applying local time zone. + */ + toDate(): Date; + /** + * Add a time duration relative to UTC. + * @return this + duration + */ + add(duration: Duration): DateTime; + /** + * Add an amount of time relative to UTC, as regularly as possible. + * + * Adding e.g. 1 hour will increment the utcHour() field, adding 1 month + * increments the utcMonth() field. + * Adding an amount of units leaves lower units intact. E.g. + * adding a month will leave the day() field untouched if possible. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + * + * In case of DST changes, the utc time fields are still untouched but local + * time fields may shift. + */ + add(amount: number, unit: TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the time fields may additionally + * increase by the DST offset, if a non-existing local time would + * be reached otherwise. + * + * Adding a unit of time will leave lower-unit fields intact, unless the result + * would be a non-existing time. Then an extra DST offset is added. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + */ + addLocal(duration: Duration): DateTime; + addLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(duration: Duration): DateTime; + subLocal(amount: number, unit: TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): Duration; + /** + * Chops off the time part, yields the same date at 00:00:00.000 + * @return a new DateTime + */ + startOfDay(): DateTime; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same moment in time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * @return The minimum of this and other + */ + min(other: DateTime): DateTime; + /** + * @return The maximum of this and other + */ + max(other: DateTime): DateTime; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Return a string representation of the DateTime according to the + * specified format. The format is implemented as the LDML standard + * (http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns) + * + * @param formatString The format specification (e.g. "dd/MM/yyyy HH:mm:ss") + * @return The string representation of this DateTime + */ + format(formatString: string): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } +} + +declare module '__timezonecomplete/duration' { + import basics = require("__timezonecomplete/basics"); + import TimeUnit = basics.TimeUnit; + /** + * Construct a time duration + * @param n Number of years (may be fractional or negative) + * @return A duration of n years + */ + export function years(n: number): Duration; + /** + * Construct a time duration + * @param n Number of months (may be fractional or negative) + * @return A duration of n months + */ + export function months(n: number): Duration; + /** + * Construct a time duration + * @param n Number of days (may be fractional or negative) + * @return A duration of n days + */ + export function days(n: number): Duration; + /** + * Construct a time duration + * @param n Number of hours (may be fractional or negative) + * @return A duration of n hours + */ + export function hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes (may be fractional or negative) + * @return A duration of n minutes + */ + export function minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds (may be fractional or negative) + * @return A duration of n seconds + */ + export function seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds (may be fractional or negative) + * @return A duration of n milliseconds + */ + export function milliseconds(n: number): Duration; + /** + * Time duration which is represented as an amount and a unit e.g. + * '1 Month' or '166 Seconds'. The unit is preserved through calculations. + * + * It has two sets of getter functions: + * - second(), minute(), hour() etc, singular form: these can be used to create string representations. + * These return a part of your string representation. E.g. for 2500 milliseconds, the millisecond() part would be 500 + * - seconds(), minutes(), hours() etc, plural form: these return the total amount represented in the corresponding unit. + */ + export class Duration { + /** + * Construct a time duration + * @param n Number of years (may be fractional or negative) + * @return A duration of n years + */ + static years(n: number): Duration; + /** + * Construct a time duration + * @param n Number of months (may be fractional or negative) + * @return A duration of n months + */ + static months(n: number): Duration; + /** + * Construct a time duration + * @param n Number of days (may be fractional or negative) + * @return A duration of n days + */ + static days(n: number): Duration; + /** + * Construct a time duration + * @param n Number of hours (may be fractional or negative) + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes (may be fractional or negative) + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds (may be fractional or negative) + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds (may be fractional or negative) + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a string in one of two formats: + * 1) [-]hhhh[:mm[:ss[.nnn]]] e.g. '-01:00:30.501' + * 2) amount and unit e.g. '-1 days' or '1 year'. The unit may be in singular or plural form and is case-insensitive + */ + constructor(input: string); + /** + * Construct a duration from an amount and a time unit. + * @param amount Number of units + * @param unit A time unit i.e. TimeUnit.Second, TimeUnit.Hour etc. Default Millisecond. + */ + constructor(amount: number, unit?: TimeUnit); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * Returns this duration expressed in different unit (positive or negative, fractional). + * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). + * It is approximate for any other conversion + */ + as(unit: TimeUnit): number; + /** + * Convert this duration to a Duration in another unit. You always get a clone even if you specify + * the same unit. + * This is precise for Year <-> Month and for time-to-time conversion (i.e. Hour-or-less to Hour-or-less). + * It is approximate for any other conversion + */ + convert(unit: TimeUnit): Duration; + /** + * The entire duration in milliseconds (negative or positive) + * For Day/Month/Year durations, this is approximate! + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * For Day/Month/Year durations, this is approximate! + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of a duration. This assumes that a day has 24 hours (which is not the case + * during DST changes). + */ + hour(): number; + /** + * DEPRECATED + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * For Day/Month/Year durations, this is approximate! + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * The entire duration in days (negative or positive, fractional) + * This is approximate if this duration is not in days! + */ + days(): number; + /** + * The day part of a duration. This assumes that a month has 30 days. + */ + day(): number; + /** + * The entire duration in days (negative or positive, fractional) + * This is approximate if this duration is not in Months or Years! + */ + months(): number; + /** + * The month part of a duration. + */ + month(): number; + /** + * The entire duration in years (negative or positive, fractional) + * This is approximate if this duration is not in Months or Years! + */ + years(): number; + /** + * Non-fractional positive years + */ + wholeYears(): number; + /** + * Amount of units (positive or negative, fractional) + */ + amount(): number; + /** + * The unit this duration was created with + */ + unit(): TimeUnit; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff (this <= other) + */ + lessEqual(other: Duration): boolean; + /** + * Similar but not identical + * Approximate if the durations have units that cannot be converted + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * Similar but not identical + * Returns false if we cannot determine whether they are equal in all time zones + * so e.g. 60 minutes equals 1 hour, but 24 hours do NOT equal 1 day + * + * @return True iff this and other represent the same time duration + */ + equalsExact(other: Duration): boolean; + /** + * Same unit and same amount + */ + identical(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return True iff this >= other + */ + greaterEqual(other: Duration): boolean; + /** + * Approximate if the durations have units that cannot be converted + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * Approximate if the durations have units that cannot be converted + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * Approximate if the durations have units that cannot be converted + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Approximate if the durations have units that cannot be converted + * Divide by a fixed number. + * @return a new Duration of (this / value) + */ + divide(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) with the unit of this duration + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) with the unit of this duration + */ + sub(value: Duration): Duration; + /** + * Return the absolute value of the duration i.e. remove the sign. + */ + abs(): Duration; + /** + * DEPRECATED + * String in [-]hhhh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hhhh:mm[:ss[.nnn]] notation. + * @param full If true, then all fields are always present except the sign. Otherwise, seconds and milliseconds + * are chopped off if zero + */ + toHmsString(full?: boolean): string; + /** + * String in ISO 8601 notation e.g. 'P1M' for one month or 'PT1M' for one minute + */ + toIsoString(): string; + /** + * String representation with amount and unit e.g. '1.5 years' or '-1 day' + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; + } +} + +declare module '__timezonecomplete/javascript' { + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear(), getUtcMonth() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } +} + +declare module '__timezonecomplete/period' { + import basics = require("__timezonecomplete/basics"); + import TimeUnit = basics.TimeUnit; + import duration = require("__timezonecomplete/duration"); + import Duration = duration.Duration; + import datetime = require("__timezonecomplete/datetime"); + import DateTime = datetime.DateTime; + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + /** + * End-of-enum marker + */ + MAX = 2, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param interval The interval of the period + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + * Defaults to RegularLocalTime. + */ + constructor(start: DateTime, interval: Duration, dst?: PeriodDst); + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + * Defaults to RegularLocalTime. + */ + constructor(start: DateTime, amount: number, unit: TimeUnit, dst?: PeriodDst); + /** + * The start date + */ + start(): DateTime; + /** + * The interval + */ + interval(): Duration; + /** + * DEPRECATED + * The amount of units of the interval + */ + amount(): number; + /** + * DEPRECATED + * The unit of the interval + */ + unit(): TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: DateTime): DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: DateTime, count?: number): DateTime; + /** + * Checks whether the given date is on a period boundary + * (expensive!) + */ + isBoundary(occurrence: DateTime): boolean; + /** + * Returns true iff this period has the same effect as the given one. + * i.e. a period of 24 hours is equal to one of 1 day if they have the same UTC start moment + * and same dst. + */ + equals(other: Period): boolean; + /** + * Returns true iff this period was constructed with identical arguments to the other one. + */ + identical(other: Period): boolean; + /** + * Returns an ISO duration string e.g. + * 2014-01-01T12:00:00.000+01:00/P1H + * 2014-01-01T12:00:00.000+01:00/PT1M (one minute) + * 2014-01-01T12:00:00.000+01:00/P1M (one month) + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam, keeping regular intervals". + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + } +} + +declare module '__timezonecomplete/timesource' { + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } +} + +declare module '__timezonecomplete/timezone' { + import javascript = require("__timezonecomplete/javascript"); + import DateFunctions = javascript.DateFunctions; + /** + * The local time zone for a given date as per OS settings. Note that time zones are cached + * so you don't necessarily get a new object each time. + */ + export function local(): TimeZone; + /** + * Coordinated Universal Time zone. Note that time zones are cached + * so you don't necessarily get a new object each time. + */ + export function utc(): TimeZone; + /** + * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @returns a time zone with the given fixed offset + */ + export function zone(offset: number): TimeZone; + /** + * Time zone for an offset string or an IANA time zone string. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @param s Empty string for no time zone (null is returned), + * "localtime" for local time, + * a TZ database time zone name (e.g. Europe/Amsterdam), + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for + * "localtime", timezonecomplete will adhere to the computer settings, the DST flag + * does not have any effect. + */ + export function zone(name: string, dst?: boolean): TimeZone; + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Option for TimeZone#normalizeLocal() + */ + export enum NormalizeOption { + /** + * Normalize non-existing times by ADDING the DST offset + */ + Up = 0, + /** + * Normalize non-existing times by SUBTRACTING the DST offset + */ + Down = 1, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Time zone with a fixed offset + * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Time zone for an offset string or an IANA time zone string. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @param s Empty string for no time zone (null is returned), + * "localtime" for local time, + * a TZ database time zone name (e.g. Europe/Amsterdam), + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + * TZ database zone name may be suffixed with " without DST" to indicate no DST should be applied. + * In that case, the dst parameter is ignored. + * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for + * "localtime", timezonecomplete will adhere to the computer settings, the DST flag + * does not have any effect. + */ + static zone(s: string, dst?: boolean): TimeZone; + /** + * Do not use this constructor, use the static + * TimeZone.zone() method instead. + * @param name NORMALIZED name, assumed to be correct + * @param dst Adhere to Daylight Saving Time if applicable, ignored for local time and fixed offsets + */ + constructor(name: string, dst?: boolean); + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + dst(): boolean; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Returns true iff the constructor arguments were identical, so UTC !== GMT + */ + identical(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Does this zone have Daylight Saving Time at all? + */ + hasDst(): boolean; + /** + * Calculate timezone offset from a UTC time. + * + * @param year Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond Millisecond 0-999 + * + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: DateFunctions): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: DateFunctions): number; + /** + * Zone abbreviation at given UTC timestamp e.g. CEST for Central European Summer Time. + * + * @param year Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond Millisecond 0-999 + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * + * @return "local" for local timezone, the offset for an offset zone, or the abbreviation for a proper zone. + */ + abbreviationForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, dstDependent?: boolean): string; + /** + * Normalizes non-existing local times by adding a forward offset change. + * During a forward standard offset change or DST offset change, some amount of + * local time is skipped. Therefore, this amount of local time does not exist. + * This function adds the amount of forward change to any non-existing time. After all, + * this is probably what the user meant. + * + * @param localUnixMillis Unix timestamp in zone time + * @param opt (optional) Round up or down? Default: up + * + * @returns Unix timestamp in zone time, normalized. + */ + normalizeZoneTime(localUnixMillis: number, opt?: NormalizeOption): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } +} + +declare module '__timezonecomplete/globals' { + import datetime = require("__timezonecomplete/datetime"); + import DateTime = datetime.DateTime; + import duration = require("__timezonecomplete/duration"); + import Duration = duration.Duration; + /** + * Returns the minimum of two DateTimes + */ + export function min(d1: DateTime, d2: DateTime): DateTime; + /** + * Returns the minimum of two Durations + */ + export function min(d1: Duration, d2: Duration): Duration; + /** + * Returns the maximum of two DateTimes + */ + export function max(d1: DateTime, d2: DateTime): DateTime; + /** + * Returns the maximum of two Durations + */ + export function max(d1: Duration, d2: Duration): Duration; + /** + * Returns the absolute value of a Duration + */ + export function abs(d: Duration): Duration; +} diff --git a/title-case/title-case.d.ts b/title-case/title-case.d.ts index c8e4dee30..1409f6b06 100644 --- a/title-case/title-case.d.ts +++ b/title-case/title-case.d.ts @@ -1,9 +1,9 @@ -// Type definitions for title-case -// Project: https://github.com/blakeembrey/title-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "title-case" { - function titleCase(string1: string, string2?: string): string; - export = titleCase; +// Type definitions for title-case +// Project: https://github.com/blakeembrey/title-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "title-case" { + function titleCase(string1: string, string2?: string): string; + export = titleCase; } \ No newline at end of file diff --git a/tmp/tmp-tests.ts b/tmp/tmp-tests.ts index c5560e799..c343f5278 100644 --- a/tmp/tmp-tests.ts +++ b/tmp/tmp-tests.ts @@ -1,68 +1,68 @@ -/// -import tmp = require('tmp'); - -tmp.file((err, path, fd, cleanupCallback) => { - if (err) throw err; - - console.log("File: ", path); - console.log("Filedescriptor: ", fd); - - cleanupCallback(); -}); - -tmp.dir((err, path, cleanupCallback) => { - if (err) throw err; - - console.log("Dir: ", path); - - cleanupCallback(); -}); - -tmp.tmpName((err, path) => { - if (err) throw err; - - console.log("Created temporary filename: ", path); -}); - -tmp.file({ mode: 644, prefix: 'prefix-', postfix: '.txt' }, (err, path, fd) => { - if (err) throw err; - - console.log("File: ", path); - console.log("Filedescriptor: ", fd); -}); - -tmp.dir({ mode: 750, prefix: 'myTmpDir_' }, (err, path) => { - if (err) throw err; - - console.log("Dir: ", path); -}); - -tmp.tmpName({ template: '/tmp/tmp-XXXXXX' }, (err, path) => { - if (err) throw err; - - console.log("Created temporary filename: ", path); -}); - -tmp.setGracefulCleanup(); - -var tmpobj = tmp.fileSync(); -console.log("File: ", tmpobj.name); -console.log("Filedescriptor: ", tmpobj.fd); -tmpobj.removeCallback(); - -tmpobj = tmp.dirSync(); -console.log("Dir: ", tmpobj.name); -tmpobj.removeCallback(); - -var name = tmp.tmpNameSync(); -console.log("Created temporary filename: ", name); - -tmpobj = tmp.fileSync({ mode: 644, prefix: 'prefix-', postfix: '.txt' }); -console.log("File: ", tmpobj.name); -console.log("Filedescriptor: ", tmpobj.fd); - -tmpobj = tmp.dirSync({ mode: 750, prefix: 'myTmpDir_' }); -console.log("Dir: ", tmpobj.name); - -var tmpname = tmp.tmpNameSync({ template: '/tmp/tmp-XXXXXX' }); +/// +import tmp = require('tmp'); + +tmp.file((err, path, fd, cleanupCallback) => { + if (err) throw err; + + console.log("File: ", path); + console.log("Filedescriptor: ", fd); + + cleanupCallback(); +}); + +tmp.dir((err, path, cleanupCallback) => { + if (err) throw err; + + console.log("Dir: ", path); + + cleanupCallback(); +}); + +tmp.tmpName((err, path) => { + if (err) throw err; + + console.log("Created temporary filename: ", path); +}); + +tmp.file({ mode: 644, prefix: 'prefix-', postfix: '.txt' }, (err, path, fd) => { + if (err) throw err; + + console.log("File: ", path); + console.log("Filedescriptor: ", fd); +}); + +tmp.dir({ mode: 750, prefix: 'myTmpDir_' }, (err, path) => { + if (err) throw err; + + console.log("Dir: ", path); +}); + +tmp.tmpName({ template: '/tmp/tmp-XXXXXX' }, (err, path) => { + if (err) throw err; + + console.log("Created temporary filename: ", path); +}); + +tmp.setGracefulCleanup(); + +var tmpobj = tmp.fileSync(); +console.log("File: ", tmpobj.name); +console.log("Filedescriptor: ", tmpobj.fd); +tmpobj.removeCallback(); + +tmpobj = tmp.dirSync(); +console.log("Dir: ", tmpobj.name); +tmpobj.removeCallback(); + +var name = tmp.tmpNameSync(); +console.log("Created temporary filename: ", name); + +tmpobj = tmp.fileSync({ mode: 644, prefix: 'prefix-', postfix: '.txt' }); +console.log("File: ", tmpobj.name); +console.log("Filedescriptor: ", tmpobj.fd); + +tmpobj = tmp.dirSync({ mode: 750, prefix: 'myTmpDir_' }); +console.log("Dir: ", tmpobj.name); + +var tmpname = tmp.tmpNameSync({ template: '/tmp/tmp-XXXXXX' }); console.log("Created temporary filename: ", tmpname ); \ No newline at end of file diff --git a/tmp/tmp.d.ts b/tmp/tmp.d.ts index 4625fc19c..99fce6400 100644 --- a/tmp/tmp.d.ts +++ b/tmp/tmp.d.ts @@ -1,48 +1,48 @@ -// Type definitions for tmp v0.0.28 -// Project: https://www.npmjs.com/package/tmp -// Definitions by: Jared Klopper -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "tmp" { - - module tmp { - interface Options extends SimpleOptions { - mode?: number; - } - - interface SimpleOptions { - prefix?: string; - postfix?: string; - template?: string; - dir?: string; - tries?: number; - keep?: boolean; - unsafeCleanup?: boolean; - } - - interface SynchrounousResult { - name: string; - fd: number; - removeCallback: () => void; - } - - function file(callback: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; - function file(config: Options, callback?: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; - - function fileSync(config?: Options): SynchrounousResult; - - function dir(callback: (err: any, path: string, cleanupCallback: () => void) => void): void; - function dir(config: Options, callback?: (err: any, path: string, cleanupCallback: () => void) => void): void; - - function dirSync(config?: Options): SynchrounousResult; - - function tmpName(callback: (err: any, path: string) => void): void; - function tmpName(config: SimpleOptions, callback?: (err: any, path: string) => void): void; - - function tmpNameSync(config?: SimpleOptions): string; - - function setGracefulCleanup(): void; - } - - export = tmp; -} +// Type definitions for tmp v0.0.28 +// Project: https://www.npmjs.com/package/tmp +// Definitions by: Jared Klopper +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "tmp" { + + module tmp { + interface Options extends SimpleOptions { + mode?: number; + } + + interface SimpleOptions { + prefix?: string; + postfix?: string; + template?: string; + dir?: string; + tries?: number; + keep?: boolean; + unsafeCleanup?: boolean; + } + + interface SynchrounousResult { + name: string; + fd: number; + removeCallback: () => void; + } + + function file(callback: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; + function file(config: Options, callback?: (err: any, path: string, fd: number, cleanupCallback: () => void) => void): void; + + function fileSync(config?: Options): SynchrounousResult; + + function dir(callback: (err: any, path: string, cleanupCallback: () => void) => void): void; + function dir(config: Options, callback?: (err: any, path: string, cleanupCallback: () => void) => void): void; + + function dirSync(config?: Options): SynchrounousResult; + + function tmpName(callback: (err: any, path: string) => void): void; + function tmpName(config: SimpleOptions, callback?: (err: any, path: string) => void): void; + + function tmpNameSync(config?: SimpleOptions): string; + + function setGracefulCleanup(): void; + } + + export = tmp; +} diff --git a/to-title-case-gouch/to-title-case-gouch.d.ts b/to-title-case-gouch/to-title-case-gouch.d.ts index 2faa2d8d0..0c089720f 100644 --- a/to-title-case-gouch/to-title-case-gouch.d.ts +++ b/to-title-case-gouch/to-title-case-gouch.d.ts @@ -1,8 +1,8 @@ -// Type definitions for to-title-case -// Project: https://github.com/gouch/to-title-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface String { - toTitleCase(): string; -} +// Type definitions for to-title-case +// Project: https://github.com/gouch/to-title-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface String { + toTitleCase(): string; +} diff --git a/toastr/toastr-tests.ts.tscparams b/toastr/toastr-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/toastr/toastr-tests.ts.tscparams +++ b/toastr/toastr-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/tspromise/tspromise.d.ts b/tspromise/tspromise.d.ts index 0d1132ed1..0228bc946 100644 --- a/tspromise/tspromise.d.ts +++ b/tspromise/tspromise.d.ts @@ -1,40 +1,40 @@ -// Type definitions for tspromise 0.0.4 -// Project: https://github.com/soywiz/tspromise -// Definitions by: Carlos Ballesteros Velasco -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -declare class Thenable { - then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => TR): Thenable; - then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => void): Thenable; - then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => void): Thenable; - then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => TR): Thenable; - catch(onRejected: (error: Error) => T): Thenable; -} - -interface NodeCallback { - (err: Error, value: T): void; -} - -declare module "tspromise" { - class Promise extends Thenable { - constructor(callback: (resolve: (value?: T) => void, reject?: (error: Error) => void) => void); - static resolve(value?: T): Thenable; - static resolve(promise: Thenable): Thenable; - static reject(error: Error): Thenable; - static all(promises: Thenable[]): Thenable; - static async(callback: () => TR): () => Thenable; - static async(callback: (p1: T1) => TR): (p1: T1) => Thenable; - static async(callback: (p1: T1, p2: T2) => TR): (p1: T1, p2: T2) => Thenable; - static async(callback: (p1: T1, p2: T2, p3: T3) => TR): (p1: T1, p2: T2, p3: T3) => Thenable; - static async(callback: (p1: T1, p2: T2, p3: T3, p4: T4) => TR): (p1: T1, p2: T2, p3: T3, p4: T4) => Thenable; - static spawn(generatorFunction: () => TR): Thenable; - static rewriteFolderSync(path: string): void; - static waitAsync(time: number): Thenable<{}>; - static nfcall(obj: any, methodName: String, ...args: any[]): Thenable; - } - - export = Promise; -} - -declare function yield(promise: Thenable): T; +// Type definitions for tspromise 0.0.4 +// Project: https://github.com/soywiz/tspromise +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare class Thenable { + then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => TR): Thenable; + then(onFulfilled: (value: T) => Thenable, onRejected?: (error: Error) => void): Thenable; + then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => void): Thenable; + then(onFulfilled: (value: T) => TR, onRejected?: (error: Error) => TR): Thenable; + catch(onRejected: (error: Error) => T): Thenable; +} + +interface NodeCallback { + (err: Error, value: T): void; +} + +declare module "tspromise" { + class Promise extends Thenable { + constructor(callback: (resolve: (value?: T) => void, reject?: (error: Error) => void) => void); + static resolve(value?: T): Thenable; + static resolve(promise: Thenable): Thenable; + static reject(error: Error): Thenable; + static all(promises: Thenable[]): Thenable; + static async(callback: () => TR): () => Thenable; + static async(callback: (p1: T1) => TR): (p1: T1) => Thenable; + static async(callback: (p1: T1, p2: T2) => TR): (p1: T1, p2: T2) => Thenable; + static async(callback: (p1: T1, p2: T2, p3: T3) => TR): (p1: T1, p2: T2, p3: T3) => Thenable; + static async(callback: (p1: T1, p2: T2, p3: T3, p4: T4) => TR): (p1: T1, p2: T2, p3: T3, p4: T4) => Thenable; + static spawn(generatorFunction: () => TR): Thenable; + static rewriteFolderSync(path: string): void; + static waitAsync(time: number): Thenable<{}>; + static nfcall(obj: any, methodName: String, ...args: any[]): Thenable; + } + + export = Promise; +} + +declare function yield(promise: Thenable): T; diff --git a/tween.js/tween.js.d.ts b/tween.js/tween.js.d.ts index d83300cba..d4787a86a 100644 --- a/tween.js/tween.js.d.ts +++ b/tween.js/tween.js.d.ts @@ -1,100 +1,100 @@ -// Type definitions for tween.js r12 -// Project: https://github.com/sole/tween.js/ -// Definitions by: sunetos , jzarnikov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module TWEEN { - export var REVISION: string; - export function getAll(): Tween[]; - export function removeAll(): void; - export function add(tween:Tween): void; - export function remove(tween:Tween): void; - export function update(time?:number): boolean; - - export class Tween { - constructor(object?:any); - to(properties:any, duration:number): Tween; - start(time?:number): Tween; - stop(): Tween; - delay(amount:number): Tween; - easing(easing: (k: number) => number): Tween; - interpolation(interpolation: (v:number[], k:number) => number): Tween; - chain(...tweens:Tween[]): Tween; - onStart(callback: (object?: any) => void): Tween; - onUpdate(callback: (object?: any) => void): Tween; - onComplete(callback: (object?: any) => void): Tween; - update(time: number): boolean; - repeat(times: number): Tween; - yoyo(enable: boolean): Tween; - } - export var Easing: TweenEasing; - export var Interpolation: TweenInterpolation; -} - -interface TweenEasing { - Linear: { - None(k:number): number; - }; - Quadratic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Cubic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Quartic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Quintic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Sinusoidal: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Exponential: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Circular: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Elastic: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Back: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; - Bounce: { - In(k:number): number; - Out(k:number): number; - InOut(k:number): number; - }; -} - -interface TweenInterpolation { - Linear(v:number[], k:number): number; - Bezier(v:number[], k:number): number; - CatmullRom(v:number[], k:number): number; - - Utils: { - Linear(p0:number, p1:number, t:number): number; - Bernstein(n:number, i:number): number; - Factorial(n:number): number; - }; -} +// Type definitions for tween.js r12 +// Project: https://github.com/sole/tween.js/ +// Definitions by: sunetos , jzarnikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module TWEEN { + export var REVISION: string; + export function getAll(): Tween[]; + export function removeAll(): void; + export function add(tween:Tween): void; + export function remove(tween:Tween): void; + export function update(time?:number): boolean; + + export class Tween { + constructor(object?:any); + to(properties:any, duration:number): Tween; + start(time?:number): Tween; + stop(): Tween; + delay(amount:number): Tween; + easing(easing: (k: number) => number): Tween; + interpolation(interpolation: (v:number[], k:number) => number): Tween; + chain(...tweens:Tween[]): Tween; + onStart(callback: (object?: any) => void): Tween; + onUpdate(callback: (object?: any) => void): Tween; + onComplete(callback: (object?: any) => void): Tween; + update(time: number): boolean; + repeat(times: number): Tween; + yoyo(enable: boolean): Tween; + } + export var Easing: TweenEasing; + export var Interpolation: TweenInterpolation; +} + +interface TweenEasing { + Linear: { + None(k:number): number; + }; + Quadratic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Cubic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Quartic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Quintic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Sinusoidal: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Exponential: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Circular: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Elastic: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Back: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; + Bounce: { + In(k:number): number; + Out(k:number): number; + InOut(k:number): number; + }; +} + +interface TweenInterpolation { + Linear(v:number[], k:number): number; + Bezier(v:number[], k:number): number; + CatmullRom(v:number[], k:number): number; + + Utils: { + Linear(p0:number, p1:number, t:number): number; + Bernstein(n:number, i:number): number; + Factorial(n:number): number; + }; +} diff --git a/tweenjs/tweenjs.d.ts b/tweenjs/tweenjs.d.ts index cb566dfcc..0d3d0d1aa 100644 --- a/tweenjs/tweenjs.d.ts +++ b/tweenjs/tweenjs.d.ts @@ -1,166 +1,166 @@ -// Type definitions for TweenJS 0.6.0 -// Project: http://www.createjs.com/#!/TweenJS -// Definitions by: Pedro Ferreira , Chris Smith -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* - Copyright (c) 2012 Pedro Ferreira - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -// Library documentation : http://www.createjs.com/Docs/TweenJS/modules/TweenJS.html - -/// - -declare module createjs { - export class CSSPlugin { - constructor(); - - // properties - static cssSuffixMap: Object; - - // methods - static install(): void; - } - - export class Ease { - // methods - static backIn: (amount: number) => number; - static backInOut: (amount: number) => number; - static backOut: (amount: number) => number; - static bounceIn: (amount: number) => number; - static bounceInOut: (amount: number) => number; - static bounceOut: (amount: number) => number; - static circIn: (amount: number) => number; - static circInOut: (amount: number) => number; - static circOut: (amount: number) => number; - static cubicIn: (amount: number) => number; - static cubicInOut: (amount: number) => number; - static cubicOut: (amount: number) => number; - static elasticIn: (amount: number) => number; - static elasticInOut: (amount: number) => number; - static elasticOut: (amount: number) => number; - static get(amount: number): (amount: number) => number; - static getBackIn(amount: number): (amount: number) => number; - static getBackInOut(amount: number): (amount: number) => number; - static getBackOut(amount: number): (amount: number) => number; - static getElasticIn(amplitude: number, period: number): (amount: number) => number; - static getElasticInOut(amplitude: number, period: number): (amount: number) => number; - static getElasticOut(amplitude: number, period: number): (amount: number) => number; - static getPowIn(pow: number): (amount: number) => number; - static getPowInOut(pow: number): (amount: number) => number; - static getPowOut(pow: number): (amount: number) => number; - static linear: (amount: number) => number; - static none: (amount: number) => number; // same as linear - static quadIn: (amount: number) => number; - static quadInOut: (amount: number) => number; - static quadOut: (amount: number) => number; - static quartIn: (amount: number) => number; - static quartInOut: (amount: number) => number; - static quartOut: (amount: number) => number; - static quintIn: (amount: number) => number; - static quintInOut: (amount: number) => number; - static quintOut: (amount: number) => number; - static sineIn: (amount: number) => number; - static sineInOut: (amount: number) => number; - static sineOut: (amount: number) => number; - } - - export class MotionGuidePlugin { - constructor(); - - //methods - static install(): Object; - } - - /* - NOTE: It is commented out because it conflicts with SamplePlugin Class of PreloadJS. - this class is mainly for documentation purposes. - http://www.createjs.com/Docs/TweenJS/classes/SamplePlugin.html - */ - /* - export class SamplePlugin { - constructor(); - - // properties - static priority: any; - - //methods - static init(tween: Tween, prop: string, value: any): any; - static step(tween: Tween, prop: string, startValue: any, injectProps: Object, endValue: any): void; - static install(): void; - static tween(tween: Tween, prop: string, value: any, startValues: Object, endValues: Object, ratio: number, wait: boolean, end: boolean): any; - } - */ - - export class Timeline extends EventDispatcher { - constructor (tweens: Tween[], labels: Object, props: Object); - - // properties - duration: number; - ignoreGlobalPause: boolean; - loop: boolean; - position: Object; - - // methods - addLabel(label: string, position: number): void; - addTween(...tween: Tween[]): void; - getCurrentLabel(): string; - getLabels(): Object[]; - gotoAndPlay(positionOrLabel: string | number): void; - gotoAndStop(positionOrLabel: string | number): void; - removeTween(...tween: Tween[]): void; - resolve(positionOrLabel: string | number): number; - setLabels(o: Object): void; - setPaused(value: boolean): void; - setPosition(value: number, actionsMode?: number): boolean; - tick(delta: number): void; - updateDuration(): void; - } - - - export class Tween extends EventDispatcher { - constructor(target: Object, props?: Object, pluginData?: Object); - - // properties - duration: number; - static IGNORE: Object; - ignoreGlobalPause: boolean; - static LOOP: number; - loop: boolean; - static NONE: number; - onChange: Function; // deprecated - passive: boolean; - pluginData: Object; - position: number; - static REVERSE: number; - target: Object; - - // methods - call(callback: (tweenObject: Tween) => any, params?: any[], scope?: Object): Tween; // when 'params' isn't given, the callback receives a tweenObject - call(callback: (...params: any[]) => any, params?: any[], scope?: Object): Tween; // otherwise, it receives the params only - static get(target: Object, props?: Object, pluginData?: Object, override?: boolean): Tween; - static hasActiveTweens(target?: Object): boolean; - static installPlugin(plugin: Object, properties: any[]): void; - pause(tween: Tween): Tween; - play(tween: Tween): Tween; - static removeAllTweens(): void; - static removeTweens(target: Object): void; - set(props: Object, target?: Object): Tween; - setPaused(value: boolean): Tween; - setPosition(value: number, actionsMode: number): boolean; - static tick(delta: number, paused: boolean): void; - tick(delta: number): void; - to(props: Object, duration?: number, ease?: (t: number) => number): Tween; - wait(duration: number, passive?: boolean): Tween; - - } - - export class TweenJS { - // properties - static buildDate: string; - static version: string; - } -} +// Type definitions for TweenJS 0.6.0 +// Project: http://www.createjs.com/#!/TweenJS +// Definitions by: Pedro Ferreira , Chris Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* + Copyright (c) 2012 Pedro Ferreira + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +// Library documentation : http://www.createjs.com/Docs/TweenJS/modules/TweenJS.html + +/// + +declare module createjs { + export class CSSPlugin { + constructor(); + + // properties + static cssSuffixMap: Object; + + // methods + static install(): void; + } + + export class Ease { + // methods + static backIn: (amount: number) => number; + static backInOut: (amount: number) => number; + static backOut: (amount: number) => number; + static bounceIn: (amount: number) => number; + static bounceInOut: (amount: number) => number; + static bounceOut: (amount: number) => number; + static circIn: (amount: number) => number; + static circInOut: (amount: number) => number; + static circOut: (amount: number) => number; + static cubicIn: (amount: number) => number; + static cubicInOut: (amount: number) => number; + static cubicOut: (amount: number) => number; + static elasticIn: (amount: number) => number; + static elasticInOut: (amount: number) => number; + static elasticOut: (amount: number) => number; + static get(amount: number): (amount: number) => number; + static getBackIn(amount: number): (amount: number) => number; + static getBackInOut(amount: number): (amount: number) => number; + static getBackOut(amount: number): (amount: number) => number; + static getElasticIn(amplitude: number, period: number): (amount: number) => number; + static getElasticInOut(amplitude: number, period: number): (amount: number) => number; + static getElasticOut(amplitude: number, period: number): (amount: number) => number; + static getPowIn(pow: number): (amount: number) => number; + static getPowInOut(pow: number): (amount: number) => number; + static getPowOut(pow: number): (amount: number) => number; + static linear: (amount: number) => number; + static none: (amount: number) => number; // same as linear + static quadIn: (amount: number) => number; + static quadInOut: (amount: number) => number; + static quadOut: (amount: number) => number; + static quartIn: (amount: number) => number; + static quartInOut: (amount: number) => number; + static quartOut: (amount: number) => number; + static quintIn: (amount: number) => number; + static quintInOut: (amount: number) => number; + static quintOut: (amount: number) => number; + static sineIn: (amount: number) => number; + static sineInOut: (amount: number) => number; + static sineOut: (amount: number) => number; + } + + export class MotionGuidePlugin { + constructor(); + + //methods + static install(): Object; + } + + /* + NOTE: It is commented out because it conflicts with SamplePlugin Class of PreloadJS. + this class is mainly for documentation purposes. + http://www.createjs.com/Docs/TweenJS/classes/SamplePlugin.html + */ + /* + export class SamplePlugin { + constructor(); + + // properties + static priority: any; + + //methods + static init(tween: Tween, prop: string, value: any): any; + static step(tween: Tween, prop: string, startValue: any, injectProps: Object, endValue: any): void; + static install(): void; + static tween(tween: Tween, prop: string, value: any, startValues: Object, endValues: Object, ratio: number, wait: boolean, end: boolean): any; + } + */ + + export class Timeline extends EventDispatcher { + constructor (tweens: Tween[], labels: Object, props: Object); + + // properties + duration: number; + ignoreGlobalPause: boolean; + loop: boolean; + position: Object; + + // methods + addLabel(label: string, position: number): void; + addTween(...tween: Tween[]): void; + getCurrentLabel(): string; + getLabels(): Object[]; + gotoAndPlay(positionOrLabel: string | number): void; + gotoAndStop(positionOrLabel: string | number): void; + removeTween(...tween: Tween[]): void; + resolve(positionOrLabel: string | number): number; + setLabels(o: Object): void; + setPaused(value: boolean): void; + setPosition(value: number, actionsMode?: number): boolean; + tick(delta: number): void; + updateDuration(): void; + } + + + export class Tween extends EventDispatcher { + constructor(target: Object, props?: Object, pluginData?: Object); + + // properties + duration: number; + static IGNORE: Object; + ignoreGlobalPause: boolean; + static LOOP: number; + loop: boolean; + static NONE: number; + onChange: Function; // deprecated + passive: boolean; + pluginData: Object; + position: number; + static REVERSE: number; + target: Object; + + // methods + call(callback: (tweenObject: Tween) => any, params?: any[], scope?: Object): Tween; // when 'params' isn't given, the callback receives a tweenObject + call(callback: (...params: any[]) => any, params?: any[], scope?: Object): Tween; // otherwise, it receives the params only + static get(target: Object, props?: Object, pluginData?: Object, override?: boolean): Tween; + static hasActiveTweens(target?: Object): boolean; + static installPlugin(plugin: Object, properties: any[]): void; + pause(tween: Tween): Tween; + play(tween: Tween): Tween; + static removeAllTweens(): void; + static removeTweens(target: Object): void; + set(props: Object, target?: Object): Tween; + setPaused(value: boolean): Tween; + setPosition(value: number, actionsMode: number): boolean; + static tick(delta: number, paused: boolean): void; + tick(delta: number): void; + to(props: Object, duration?: number, ease?: (t: number) => number): Tween; + wait(duration: number, passive?: boolean): Tween; + + } + + export class TweenJS { + // properties + static buildDate: string; + static version: string; + } +} diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index be2f3b34b..7debe0044 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -96,8 +96,8 @@ function test_typeahead() { suggestion: 'tt-suggestion', empty: 'tt-empty', open: 'tt-open', - cursor: 'tt-cursor', - highlight: 'tt-highlight' + cursor: 'tt-cursor', + highlight: 'tt-highlight' }; } } @@ -203,8 +203,8 @@ function test_bloodhout() { function test_bloodhout_methods() { // initialize - var promise1: JQueryPromise = engine.initialize(); - var promise2: JQueryPromise = engine.initialize(); + var promise1: JQueryPromise = engine.initialize(); + var promise2: JQueryPromise = engine.initialize(); var promise3: JQueryPromise = engine.initialize(true); // add @@ -234,100 +234,100 @@ function test_bloodhout() { function test_bloodhout_options() { function test_bloodhout_options_datumTokenizer() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: (datum: string) => { return new Array(); }, - queryTokenizer: null + datumTokenizer: (datum: string) => { return new Array(); }, + queryTokenizer: null }; } function test_bloodhout_options_queryTokenizer() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: (query: string) => { return new Array(); } + datumTokenizer: null, + queryTokenizer: (query: string) => { return new Array(); } }; } function test_bloodhout_options_initialize() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - initialize: true + datumTokenizer: null, + queryTokenizer: null, + initialize: true }; } function test_bloodhout_options_sufficient() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - sufficient: 5 + datumTokenizer: null, + queryTokenizer: null, + sufficient: 5 }; } function test_bloodhout_options_sorter() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - sorter: (a: string, b: string) => { return 0 } + datumTokenizer: null, + queryTokenizer: null, + sorter: (a: string, b: string) => { return 0 } }; } function test_bloodhout_options_local_array() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - local: new Array() + datumTokenizer: null, + queryTokenizer: null, + local: new Array() }; } function test_bloodhout_options_local_function() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - local: () => { return new Array() } + datumTokenizer: null, + queryTokenizer: null, + local: () => { return new Array() } }; } function test_bloodhout_options_prefetch_string() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - prefetch: 'url' + datumTokenizer: null, + queryTokenizer: null, + prefetch: 'url' }; } function test_bloodhout_options_prefetch_object() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - prefetch: { url: 'url' } + datumTokenizer: null, + queryTokenizer: null, + prefetch: { url: 'url' } }; } function test_bloodhout_options_remote_string() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - remote: 'url' + datumTokenizer: null, + queryTokenizer: null, + remote: 'url' }; } function test_bloodhout_options_remote_object() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: null, - queryTokenizer: null, - remote: { url: 'url' } + datumTokenizer: null, + queryTokenizer: null, + remote: { url: 'url' } }; } function test_bloodhout_options_all() { var options: Bloodhound.BloodhoundOptions = { - datumTokenizer: (datum: string) => { return new Array(); }, - queryTokenizer: (query: string) => { return new Array(); }, - initialize: true, - sufficient: 5, - sorter: (a: string, b: string) => { return 0 }, - local: () => { return new Array() }, - prefetch: { url: 'url' }, - remote: { url: 'url' } + datumTokenizer: (datum: string) => { return new Array(); }, + queryTokenizer: (query: string) => { return new Array(); }, + initialize: true, + sufficient: 5, + sorter: (a: string, b: string) => { return 0 }, + local: () => { return new Array() }, + prefetch: { url: 'url' }, + remote: { url: 'url' } }; } } @@ -335,35 +335,35 @@ function test_bloodhout() { function test_bloodhout_prefetch_options() { function test_bloodhout_prefetch_options_url() { var options: Bloodhound.PrefetchOptions = { - url: 'url' + url: 'url' }; } function test_bloodhout_prefetch_options_cache() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - cache: true + url: 'url', + cache: true }; } function test_bloodhout_prefetch_options_ttl() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - ttl: 86400000 // 1 day + url: 'url', + ttl: 86400000 // 1 day }; } function test_bloodhout_prefetch_options_cacheKey() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - cacheKey: 'url' + url: 'url', + cacheKey: 'url' }; } function test_bloodhout_prefetch_options_thumbprint() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - thumbprint: 'thumbprint' + url: 'url', + thumbprint: 'thumbprint' }; } @@ -371,15 +371,15 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.PrefetchOptions = { - url: 'url', - prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; } + url: 'url', + prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; } }; } function test_bloodhout_prefetch_options_transform() { var options: Bloodhound.PrefetchOptions = { - url: 'url', - transform: (response: string[]) => { return new Array(); } + url: 'url', + transform: (response: string[]) => { return new Array(); } }; } @@ -387,13 +387,13 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.PrefetchOptions = { - url: 'url', - cache: true, - ttl: 86400000, - cacheKey: 'url', - thumbprint: 'thumbprint', - prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; }, - transform: (response: string[]) => { return new Array(); } + url: 'url', + cache: true, + ttl: 86400000, + cacheKey: 'url', + thumbprint: 'thumbprint', + prepare: (settings: JQueryAjaxSettings) => { return ajaxSettings; }, + transform: (response: string[]) => { return new Array(); } }; } } @@ -401,7 +401,7 @@ function test_bloodhout() { function test_bloodhout_remote_options() { function test_bloodhout_remote_options_url() { var options: Bloodhound.RemoteOptions = { - url: 'url' + url: 'url' }; } @@ -409,36 +409,36 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.RemoteOptions = { - url: 'url', - prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; } + url: 'url', + prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; } }; } function test_bloodhout_remote_options_wildcard() { var options: Bloodhound.RemoteOptions = { url: 'url', - wildcard: '%QUERY' + wildcard: '%QUERY' }; } function test_bloodhout_remote_options_rateLimitby() { var options: Bloodhound.RemoteOptions = { - url: 'url', - rateLimitby: 'debounce' + url: 'url', + rateLimitby: 'debounce' }; } function test_bloodhout_remote_options_rateLimitWait() { var options: Bloodhound.RemoteOptions = { - url: 'url', - rateLimitWait: 300 + url: 'url', + rateLimitWait: 300 }; } function test_bloodhout_remote_options_transform() { var options: Bloodhound.RemoteOptions = { - url: 'url', - transform: (response: string[]) => { return new Array(); } + url: 'url', + transform: (response: string[]) => { return new Array(); } }; } @@ -446,22 +446,22 @@ function test_bloodhout() { var ajaxSettings: JQueryAjaxSettings = { url: 'url' }; var options: Bloodhound.RemoteOptions = { - url: 'url', - prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; }, - wildcard: '%QUERY', - rateLimitby: 'debounce', - rateLimitWait: 300, - transform: (response: string[]) => { return new Array(); } + url: 'url', + prepare: (query: string, settings: JQueryAjaxSettings) => { return ajaxSettings; }, + wildcard: '%QUERY', + rateLimitby: 'debounce', + rateLimitWait: 300, + transform: (response: string[]) => { return new Array(); } }; } } function test_bloodhout_tokenizers() { var tokenizers: Bloodhound.Tokenizers = { - whitespace: (str: string) => { return new Array(); }, - nonword: (str: string) => { return new Array(); }, + whitespace: (str: string) => { return new Array(); }, + nonword: (str: string) => { return new Array(); }, obj: { - whitespace: (str: string) => { return new Array(); }, + whitespace: (str: string) => { return new Array(); }, nonword: (str: string) => { return new Array(); } } }; diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index 3fba4ff04..90daa580d 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -1,1207 +1,1207 @@ -// Type definitions for typeahead.js 0.11.1 -// Project: http://twitter.github.io/typeahead.js/ -// Definitions by: Ivaylo Gochkov , Gidon Junge -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -interface JQuery { - /** - * For a given input[type="text"], enables typeahead functionality. - * - * @constructor - * @param options Options hash that's used for configuration - * @param datasets Array of datasets - */ - typeahead(options: Twitter.Typeahead.Options, datasets: Twitter.Typeahead.Dataset[]): JQuery; - - /** - * For a given input[type="text"], enables typeahead functionality. - * - * @constructor - * @param options Options hash that's used for configuration - * @param dataset At least one dataset is required - * @param datasets Rest of the datasets. - */ - typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset, ...datasets: Twitter.Typeahead.Dataset[]): JQuery; - - /** - * Returns the current value of the typeahead. - * The value is the text the user has entered into the input element. - * - * @constructor - * @param methodName Method 'val' - */ - typeahead(methodName: 'val'): string; - - /** - * Accommodates the val overload. - * - * @constructor - * @param methodName Method 'val' - */ - typeahead(methodName: string): string; - - /** - * Sets the value of the typeahead. This should be used in place of jQuery#val. - * - * @constructor - * @param methodName Method 'val' - * @param val The value to be set - */ - typeahead(methodName: 'val', val: string): JQuery; - - /** - * Accommodates the set val overload. - * - * @constructor - * @param methodName Method 'val' - * @param val The value to be set - */ - typeahead(methodName: string, val: string): JQuery; - - /** - * Opens the suggestion menu. - * - * @constructor - * @param methodName Method 'open' - */ - typeahead(methodName: 'open'): JQuery; - - /** - * Closes the suggestion menu. - * - * @constructor - * @param methodName Method 'close' - */ - typeahead(methodName: 'close'): JQuery; - - /** - * Removes typeahead functionality and reverts the input element back to its original state. - * - * @constructor - * @param methodName Method 'destroy' - */ - typeahead(methodName: 'destroy'): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:active", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:active", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:active", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:active event to the selected elements. - * - * @param events typeahead:active event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:active", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:idle", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:idle", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:idle", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:idle event to the selected elements. - * - * @param events typeahead:idle event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:idle", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:open", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:open", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:open", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:open event to the selected elements. - * - * @param events typeahead:open event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:open", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:close", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:close", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:close", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:close event to the selected elements. - * - * @param events typeahead:close event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:close", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:change", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:change", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:change", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:change event to the selected elements. - * - * @param events typeahead:change event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:change", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:render", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:render", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:render", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:render event to the selected elements. - * - * @param events typeahead:render event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:render", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:select", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:select", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:select", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:select event to the selected elements. - * - * @param events typeahead:select event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:select", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:autocomplete", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:autocomplete", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:autocomplete event to the selected elements. - * - * @param events typeahead:autocomplete event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:autocomplete", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:cursorchange", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:cursorchange", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:cursorchange event to the selected elements. - * - * @param events typeahead:cursorchange event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:cursorchange", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncrequest", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncrequest", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncrequest event to the selected elements. - * - * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncrequest", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asynccancel", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asynccancel", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asynccancel event to the selected elements. - * - * @param events typeahead:asynccancel event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asynccancel", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncreceive", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncreceive", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach an event handler function for typeahead:asyncreceive event to the selected elements. - * - * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: "typeahead:asyncreceive", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:active event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:active", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:active event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:active", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:idle event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:idle", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:idle event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:idle", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:open event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:open", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:open event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:open", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:close event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:close", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:close event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:close", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:change event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:change", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:change event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:change", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:render event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:render", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:render event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:render", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:select event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:select", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:select event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:select", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:autocomplete event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:autocomplete", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:autocomplete event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:cursorchange event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:cursorchange", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:cursorchange event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncrequest event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncrequest", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncrequest event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asynccancel event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asynccancel", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asynccancel event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncreceive event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncreceive", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events typeahead:asyncreceive event. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject) => any): JQuery; -} - -declare module Twitter.Typeahead { - interface Options { - /** - * If true, when suggestions are rendered, pattern matches for the current query in text nodes will be wrapped in a strong element with its class set to {{classNames.highlight}}. - * Defaults to false. - */ - highlight?: boolean; - - /** - * If false, the typeahead will not show a hint. - * Defaults to true. - */ - hint?: boolean; - - /** - * The minimum character length needed before suggestions start getting rendered. - * Defaults to 1. - */ - minLength?: number; - - /** - * Used for overriding the default class names. - */ - classNames?: ClassNames; - } - - /** - * A typeahead is composed of one or more datasets. When an end-user - * modifies the value of a typeahead, each dataset will attempt to render - * suggestions for the new value. - * For most use cases, one dataset should suffice. It's only in the scenario - * where you want rendered suggestions to be grouped based on some sort of - * categorical relationship that you'd need to use multiple datasets. For - * example, on twitter.com, the search typeahead groups results into recent - * searches, trends, and accounts – that would be a great use case for using - * multiple datasets. - */ - interface Dataset { - /** - * The backing data source for suggestions. - * Expected to be a function with the signature (query, syncResults, asyncResults). - * syncResults should be called with suggestions computed synchronously and - * asyncResults should be called with suggestions computed asynchronously - * (e.g. suggestions that come for an AJAX request). - * source can also be a Bloodhound instance. - */ - source: Bloodhound | ((query: string, syncResults: (result: T[]) => void, asyncResults?: (result: T[]) => void) => void); - - /** - * Lets the dataset know if async suggestions should be expected. - * If not set, this information is inferred from the signature of - * source i.e. if the source function expects 3 arguments, async will - * be set to true. - */ - async?: boolean; - - /** - * The name of the dataset. - * This will be appended to {{classNames.dataset}} - to form the class name of the containing DOM element. - * Must only consist of underscores, dashes, letters (a-z), and numbers. - * Defaults to a random number. - */ - name?: string; - - /** - * The max number of suggestions to be displayed. Defaults to 5. - */ - limit?: number; - - /** - * For a given suggestion, determines the string representation of it. - * This will be used when setting the value of the input control after - * a suggestion is selected. Can be either a key string or a function - * that transforms a suggestion object into a string. - * Defaults to stringifying the suggestion. - */ - display?: string | ((obj: T) => string); - - /** - * A hash of templates to be used when rendering the dataset. Note a - * precompiled template is a function that takes a JavaScript object as - * its first argument and returns a HTML string. - */ - templates?: Templates; - } - - /** - * A hash of templates to be used when rendering the dataset. Note a - * precompiled template is a function that takes a JavaScript object as - * its first argument and returns a HTML string. - */ - interface Templates { - /** - * Rendered when 0 suggestions are available for the given query. - * Can be either a HTML string or a precompiled template. - * If it's a precompiled template, the passed in context will contain query. - */ - notFound?: string | ((query: string) => string); - - /** - * Rendered when 0 synchronous suggestions are available but asynchronous suggestions are expected. - * Can be either a HTML string or a precompiled template. - * If it's a precompiled template, the passed in context will contain query. - */ - pending?: string | ((query: string) => string); - - /** - * Rendered at the top of the dataset when suggestions are present. Can be either a HTML string or - * a precompiled template. If it's a precompiled template, the passed in context will contain - * query and suggestions. - */ - header?: string | ((query: string, suggestions: T[]) => string); - - /** - * Rendered at the bottom of the dataset when suggestions are present. Can be either a HTML string or - * a precompiled template. If it's a precompiled template, the passed in context will contain - * query and suggestions. - */ - footer?: string | ((query: string, suggestions: T[]) => string); - - /** - * Used to render a single suggestion. If set, this has to be a precompiled template. - * The associated suggestion object will serve as the context. - * Defaults to the value of display wrapped in a div tag i.e.
        {{value}}
        . - */ - suggestion?: (suggestion: T) => string; - } - - /** - * Used for overriding the default class names. - */ - interface ClassNames { - /** - * Added to input that's initialized into a typeahead. Defaults to tt-input. - */ - input?: string; - - /** - * Added to hint input.Defaults to tt- hint. - */ - hint?: string; - - /** - * Added to menu element.Defaults to tt- menu. - */ - menu?: string; - - /** - * Added to dataset elements.to Defaults to tt- dataset. - */ - dataset?: string; - /** - * Added to suggestion elements.Defaults to tt- suggestion. - */ - suggestion?: string; - - /** - * Added to menu element when it contains no content.Defaults to tt- empty. - */ - empty?: string; - - /** - * Added to menu element when it is opened.Defaults to tt- open. - */ - open?: string; - - /** - * Added to suggestion element when menu cursor moves to said suggestion.Defaults to tt- cursor. - */ - cursor?: string; - - /** - * Added to the element that wraps highlighted text.Defaults to tt- highlight. - */ - highlight?: string; - } -} - -declare module Bloodhound { - interface BloodhoundOptions { - /** - * Transforms a datum into an array of string tokens. - * - * @param datum Suggestion. - * @returns An array of string tokens. - */ - datumTokenizer: (datum: T) => string[]; - - /** - * Transforms a query into an array of string tokens. - * - * @param quiery Query. - * @returns An array of string tokens. - */ - queryTokenizer: (query: string) => string[]; - - /** - * If set to false, the Bloodhound instance will not be implicitly - * initialized by the constructor function. Defaults to true. - */ - initialize?: boolean; - - /** - * Given a datum, returns a unique id for it. - * Defaults to JSON.stringify. Note that it is highly recommended - * to override this option. - * - * @param datum Suggestion. - * @returns Unique id for the suggestion. - */ - identify?: (datum: T) => number; - - /** - * If the number of datums provided from the internal search index is - * less than sufficient, remote will be used to backfill search - * requests triggered by calling #search. Defaults to 5. - */ - sufficient?: number; - - /** - * A compare function used to sort data returned from the internal search index. - * - * @param a First suggestion. - * @param b Second suggestion. - * @returns Comparison result. - */ - sorter?: (a: T, b: T) => number; - - /** - * An array of data or a function that returns an array of data. - * The data will be added to the internal search index when #initialize is called. - */ - local?: T[] | (() => T[]); - - /** - * Can be a URL to a JSON file containing an array of data or, - * if more configurability is needed, a prefetch options hash. - */ - prefetch?: string | PrefetchOptions; - - /** - * Can be a URL to fetch data from when the data provided by the internal - * search index is insufficient or, if more configurability is needed, - * a remote options hash. - */ - remote?: string | RemoteOptions; - } - - /** - * Prefetched data is fetched and processed on initialization. If the browser - * supports local storage, the processed data will be cached there to prevent - * additional network requests on subsequent page loads. - * - * WARNING: While it's possible to get away with it for smaller data sets, - * prefetched data isn't meant to contain entire sets of data. Rather, it should - * act as a first-level cache. Ignoring this warning means you'll run the risk - * of hitting local storage limits. - */ - interface PrefetchOptions { - /** - * The URL prefetch data should be loaded from. - */ - url: string; - - /** - * If false, will not attempt to read or write to local storage and - * will always load prefetch data from url on initialization. Defaults to true. - */ - cache?: boolean; - - /** - * The time (in milliseconds) the prefetched data should be cached in - * local storage. Defaults to 86400000 (1 day). - */ - ttl?: number; - - /** - * The key that data will be stored in local storage under. - * Defaults to value of url. - */ - cacheKey?: string; - - /** - * A string used for thumbprinting prefetched data. If this doesn't - * match what's stored in local storage, the data will be refetched. - */ - thumbprint?: string; - - /** - * A function that provides a hook to allow you to prepare the settings - * object passed to transport when a request is about to be made. - * Defaults to the identity function. - * - * @param settings The default settings object created internally by the Bloodhound instance. - * @returns A settings object. - */ - prepare?: (settings: JQueryAjaxSettings) => JQueryAjaxSettings; - - /** - * A function with the signature transform(response) that allows you to - * transform the prefetch response before the Bloodhound instance operates - * on it. Defaults to the identity function. - * - * @param response Prefetch response. - * @returns Transform response. - */ - transform?: (response: T[]) => T[]; - } - - /** - * Bloodhound only goes to the network when the internal search engine cannot - * provide a sufficient number of results. In order to prevent an obscene - * number of requests being made to the remote endpoint, requests are rate-limited. - */ - interface RemoteOptions { - /** - * The URL remote data should be loaded from. - */ - url: string; - - /** - * A function that provides a hook to allow you to prepare the settings - * object passed to transport when a request is about to be made. - * The function signature should be prepare(query, settings), where query - * is the query #search was called with and settings is the default settings - * object created internally by the Bloodhound instance. The prepare function - * should return a settings object. Defaults to the identity function. - * - * @param query The query #search was called with. - * @param settings The default settings object created internally by Bloodhound. - * @returns A JqueryAjaxSettings object. - */ - prepare?: (query: string, settings: JQueryAjaxSettings) => JQueryAjaxSettings; - - /** - * A convenience option for prepare. If set, prepare will be a function - * that replaces the value of this option in url with the URI encoded query. - */ - wildcard?: string; - - /** - * The method used to rate-limit network requests. - * Can be either debounce or throttle. Defaults to debounce. - */ - rateLimitby?: string; - - /** - * The time interval in milliseconds that will be used by rateLimitBy. - * Defaults to 300. - */ - rateLimitWait?: number; - - /** - * A function with the signature transform(response) that allows you to - * transform the remote response before the Bloodhound instance operates on it. - * Defaults to the identity function. - * - * @param response Prefetch response. - * @returns Transform response. - */ - transform?: (response: T[]) => T[]; - } - - /** - * Build-in tokenization methods. - */ - interface Tokenizers { - /** - * Split a given string on whitespace characters. - */ - whitespace(str: string): string[]; - - /** - * Split a given string on non-word characters. - */ - nonword(str: string): string[]; - - /** - * Instances of the build-in tokenization methods. - */ - obj: ObjTokenizer; - } - - interface ObjTokenizer { - /** - * Split a given string on whitespace characters. - */ - whitespace(str: string): string[]; - - /** - * Split a given string on non-word characters. - */ - nonword(str: string): string[]; - } -} - -/** - * Bloodhound is the typeahead.js suggestion engine. Bloodhound is robust, - * flexible, and offers advanced functionalities such as prefetching, - * intelligent caching, fast lookups, and backfilling with remote data. - */ -declare class Bloodhound { - /** - * The constructor function. - * - * @constructor - * @param options Options hash. - */ - constructor(options: Bloodhound.BloodhoundOptions); - - /** - * Returns a reference to Bloodhound and reverts window.Bloodhound to its - * previous value. Can be used to avoid naming collisions. - */ - public static noConflict(): Bloodhound; - - /** - * The Bloodhound suggestion engine is token-based, so how datums and queries are tokenized plays a vital role in the quality of search results. - * Specify how you want datums and queries tokenized. - */ - public static tokenizers: Bloodhound.Tokenizers; - - /** - * Kicks off the initialization of the suggestion engine. Initialization - * entails adding the data provided by local and prefetch to the internal - * search index as well as setting up transport mechanism used by remote. - * Before #initialize is called, the #get and #search methods will effectively be no-ops. - * - * Note, unless the initialize option is false, this method is implicitly called by the constructor. - * - * After initialization, how subsequent invocations of #initialize behave depends on - * the reinitialize argument. If reinitialize is falsy, the method will not execute the - * initialization logic and will just return the same jQuery promise returned - * by the initial invocation. If reinitialize is truthy, the method will behave - * as if it were being called for the first time. - * - * @param reinitialize How subsequent invocations of #initialize will behave. - * @returns jQuery promise. - */ - public initialize(reinitialize?: boolean): JQueryPromise; - - /** - * Takes one argument, data, which is expected to be an array. - * The data passed in will get added to the internal search index. - * - * @param data Data to be added to the internal search index. - */ - public add(data: T[]): void; - - /** - * Returns the data in the local search index corresponding to ids. - * - * @param ids Data ids. - * @returns The corresponding data. - */ - public get(ids: number[]): T[]; - - /** - * Returns the data that matches query. Matches found in the local search - * index will be passed to the sync callback. If the data passed to sync - * doesn't contain at least sufficient number of datums, remote data will - * be requested and then passed to the async callback. - * - * @param query Query. - * @param sync Sync callback - * @param async Async callback. - * @returns The data that matches query. - */ - public search(query: string, sync: (datums: T[]) => void, async: (datums: T[]) => void): T[]; - - /** - * Returns all items from the internal search index. - */ - public all(): T[]; - - /** - * Clears the internal search index that's powered by local, prefetch, and #add. - */ - public clear(): Bloodhound; - - /** - * If you're using prefetch, data gets cached in local storage in an effort to cut down on unnecessary network requests. - * clearPrefetchCache offers a way to programmatically clear said cache. - */ - public clearPrefetchCache(): Bloodhound; - - /** - * If you're using remote, Bloodhound will cache the 10 most recent responses in an effort to provide a better user experience. - * clearRemoteCache offers a way to programmatically clear said cache. - */ - public clearRemoteCache(): Bloodhound; -} - -declare module "bloodhound" { - export = Bloodhound; -} +// Type definitions for typeahead.js 0.11.1 +// Project: http://twitter.github.io/typeahead.js/ +// Definitions by: Ivaylo Gochkov , Gidon Junge +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQuery { + /** + * For a given input[type="text"], enables typeahead functionality. + * + * @constructor + * @param options Options hash that's used for configuration + * @param datasets Array of datasets + */ + typeahead(options: Twitter.Typeahead.Options, datasets: Twitter.Typeahead.Dataset[]): JQuery; + + /** + * For a given input[type="text"], enables typeahead functionality. + * + * @constructor + * @param options Options hash that's used for configuration + * @param dataset At least one dataset is required + * @param datasets Rest of the datasets. + */ + typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset, ...datasets: Twitter.Typeahead.Dataset[]): JQuery; + + /** + * Returns the current value of the typeahead. + * The value is the text the user has entered into the input element. + * + * @constructor + * @param methodName Method 'val' + */ + typeahead(methodName: 'val'): string; + + /** + * Accommodates the val overload. + * + * @constructor + * @param methodName Method 'val' + */ + typeahead(methodName: string): string; + + /** + * Sets the value of the typeahead. This should be used in place of jQuery#val. + * + * @constructor + * @param methodName Method 'val' + * @param val The value to be set + */ + typeahead(methodName: 'val', val: string): JQuery; + + /** + * Accommodates the set val overload. + * + * @constructor + * @param methodName Method 'val' + * @param val The value to be set + */ + typeahead(methodName: string, val: string): JQuery; + + /** + * Opens the suggestion menu. + * + * @constructor + * @param methodName Method 'open' + */ + typeahead(methodName: 'open'): JQuery; + + /** + * Closes the suggestion menu. + * + * @constructor + * @param methodName Method 'close' + */ + typeahead(methodName: 'close'): JQuery; + + /** + * Removes typeahead functionality and reverts the input element back to its original state. + * + * @constructor + * @param methodName Method 'destroy' + */ + typeahead(methodName: 'destroy'): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:active", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:active", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:active", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:active event to the selected elements. + * + * @param events typeahead:active event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:active", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:idle", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:idle", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:idle", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:idle event to the selected elements. + * + * @param events typeahead:idle event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:idle", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:open", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:open", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:open", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:open event to the selected elements. + * + * @param events typeahead:open event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:open", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:close", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:close", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:close", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:close event to the selected elements. + * + * @param events typeahead:close event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:close", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:change", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:change", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:change", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:change event to the selected elements. + * + * @param events typeahead:change event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:change", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:render", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:render", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:render", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:render event to the selected elements. + * + * @param events typeahead:render event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:render", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:select", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:select", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:select", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:select event to the selected elements. + * + * @param events typeahead:select event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:select", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:autocomplete", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:autocomplete", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:autocomplete event to the selected elements. + * + * @param events typeahead:autocomplete event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:autocomplete", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:cursorchange", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:cursorchange", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:cursorchange event to the selected elements. + * + * @param events typeahead:cursorchange event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:cursorchange", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncrequest", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncrequest", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncrequest event to the selected elements. + * + * @param events typeahead:asyncrequest event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncrequest", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asynccancel", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asynccancel", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asynccancel event to the selected elements. + * + * @param events typeahead:asynccancel event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asynccancel", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncreceive", data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncreceive", selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach an event handler function for typeahead:asyncreceive event to the selected elements. + * + * @param events typeahead:asyncreceive event fired when the typeahead moves to active state. + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: "typeahead:asyncreceive", selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:active event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:active", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:active event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:active", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:idle event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:idle", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:idle event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:idle", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:open event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:open", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:open event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:open", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:close event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:close", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:close event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:close", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:change event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:change", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:change event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:change", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:render event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:render", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:render event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:render", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:select event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:select", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:select event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:select", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:autocomplete event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:autocomplete", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:autocomplete event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:autocomplete", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:cursorchange event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:cursorchange", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:cursorchange event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:cursorchange", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncrequest event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncrequest", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncrequest event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncrequest", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asynccancel event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asynccancel", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asynccancel event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asynccancel", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncreceive event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncreceive", selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events typeahead:asyncreceive event. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: "typeahead:asyncreceive", handler: (eventObject: JQueryEventObject) => any): JQuery; +} + +declare module Twitter.Typeahead { + interface Options { + /** + * If true, when suggestions are rendered, pattern matches for the current query in text nodes will be wrapped in a strong element with its class set to {{classNames.highlight}}. + * Defaults to false. + */ + highlight?: boolean; + + /** + * If false, the typeahead will not show a hint. + * Defaults to true. + */ + hint?: boolean; + + /** + * The minimum character length needed before suggestions start getting rendered. + * Defaults to 1. + */ + minLength?: number; + + /** + * Used for overriding the default class names. + */ + classNames?: ClassNames; + } + + /** + * A typeahead is composed of one or more datasets. When an end-user + * modifies the value of a typeahead, each dataset will attempt to render + * suggestions for the new value. + * For most use cases, one dataset should suffice. It's only in the scenario + * where you want rendered suggestions to be grouped based on some sort of + * categorical relationship that you'd need to use multiple datasets. For + * example, on twitter.com, the search typeahead groups results into recent + * searches, trends, and accounts – that would be a great use case for using + * multiple datasets. + */ + interface Dataset { + /** + * The backing data source for suggestions. + * Expected to be a function with the signature (query, syncResults, asyncResults). + * syncResults should be called with suggestions computed synchronously and + * asyncResults should be called with suggestions computed asynchronously + * (e.g. suggestions that come for an AJAX request). + * source can also be a Bloodhound instance. + */ + source: Bloodhound | ((query: string, syncResults: (result: T[]) => void, asyncResults?: (result: T[]) => void) => void); + + /** + * Lets the dataset know if async suggestions should be expected. + * If not set, this information is inferred from the signature of + * source i.e. if the source function expects 3 arguments, async will + * be set to true. + */ + async?: boolean; + + /** + * The name of the dataset. + * This will be appended to {{classNames.dataset}} - to form the class name of the containing DOM element. + * Must only consist of underscores, dashes, letters (a-z), and numbers. + * Defaults to a random number. + */ + name?: string; + + /** + * The max number of suggestions to be displayed. Defaults to 5. + */ + limit?: number; + + /** + * For a given suggestion, determines the string representation of it. + * This will be used when setting the value of the input control after + * a suggestion is selected. Can be either a key string or a function + * that transforms a suggestion object into a string. + * Defaults to stringifying the suggestion. + */ + display?: string | ((obj: T) => string); + + /** + * A hash of templates to be used when rendering the dataset. Note a + * precompiled template is a function that takes a JavaScript object as + * its first argument and returns a HTML string. + */ + templates?: Templates; + } + + /** + * A hash of templates to be used when rendering the dataset. Note a + * precompiled template is a function that takes a JavaScript object as + * its first argument and returns a HTML string. + */ + interface Templates { + /** + * Rendered when 0 suggestions are available for the given query. + * Can be either a HTML string or a precompiled template. + * If it's a precompiled template, the passed in context will contain query. + */ + notFound?: string | ((query: string) => string); + + /** + * Rendered when 0 synchronous suggestions are available but asynchronous suggestions are expected. + * Can be either a HTML string or a precompiled template. + * If it's a precompiled template, the passed in context will contain query. + */ + pending?: string | ((query: string) => string); + + /** + * Rendered at the top of the dataset when suggestions are present. Can be either a HTML string or + * a precompiled template. If it's a precompiled template, the passed in context will contain + * query and suggestions. + */ + header?: string | ((query: string, suggestions: T[]) => string); + + /** + * Rendered at the bottom of the dataset when suggestions are present. Can be either a HTML string or + * a precompiled template. If it's a precompiled template, the passed in context will contain + * query and suggestions. + */ + footer?: string | ((query: string, suggestions: T[]) => string); + + /** + * Used to render a single suggestion. If set, this has to be a precompiled template. + * The associated suggestion object will serve as the context. + * Defaults to the value of display wrapped in a div tag i.e.
        {{value}}
        . + */ + suggestion?: (suggestion: T) => string; + } + + /** + * Used for overriding the default class names. + */ + interface ClassNames { + /** + * Added to input that's initialized into a typeahead. Defaults to tt-input. + */ + input?: string; + + /** + * Added to hint input.Defaults to tt- hint. + */ + hint?: string; + + /** + * Added to menu element.Defaults to tt- menu. + */ + menu?: string; + + /** + * Added to dataset elements.to Defaults to tt- dataset. + */ + dataset?: string; + /** + * Added to suggestion elements.Defaults to tt- suggestion. + */ + suggestion?: string; + + /** + * Added to menu element when it contains no content.Defaults to tt- empty. + */ + empty?: string; + + /** + * Added to menu element when it is opened.Defaults to tt- open. + */ + open?: string; + + /** + * Added to suggestion element when menu cursor moves to said suggestion.Defaults to tt- cursor. + */ + cursor?: string; + + /** + * Added to the element that wraps highlighted text.Defaults to tt- highlight. + */ + highlight?: string; + } +} + +declare module Bloodhound { + interface BloodhoundOptions { + /** + * Transforms a datum into an array of string tokens. + * + * @param datum Suggestion. + * @returns An array of string tokens. + */ + datumTokenizer: (datum: T) => string[]; + + /** + * Transforms a query into an array of string tokens. + * + * @param quiery Query. + * @returns An array of string tokens. + */ + queryTokenizer: (query: string) => string[]; + + /** + * If set to false, the Bloodhound instance will not be implicitly + * initialized by the constructor function. Defaults to true. + */ + initialize?: boolean; + + /** + * Given a datum, returns a unique id for it. + * Defaults to JSON.stringify. Note that it is highly recommended + * to override this option. + * + * @param datum Suggestion. + * @returns Unique id for the suggestion. + */ + identify?: (datum: T) => number; + + /** + * If the number of datums provided from the internal search index is + * less than sufficient, remote will be used to backfill search + * requests triggered by calling #search. Defaults to 5. + */ + sufficient?: number; + + /** + * A compare function used to sort data returned from the internal search index. + * + * @param a First suggestion. + * @param b Second suggestion. + * @returns Comparison result. + */ + sorter?: (a: T, b: T) => number; + + /** + * An array of data or a function that returns an array of data. + * The data will be added to the internal search index when #initialize is called. + */ + local?: T[] | (() => T[]); + + /** + * Can be a URL to a JSON file containing an array of data or, + * if more configurability is needed, a prefetch options hash. + */ + prefetch?: string | PrefetchOptions; + + /** + * Can be a URL to fetch data from when the data provided by the internal + * search index is insufficient or, if more configurability is needed, + * a remote options hash. + */ + remote?: string | RemoteOptions; + } + + /** + * Prefetched data is fetched and processed on initialization. If the browser + * supports local storage, the processed data will be cached there to prevent + * additional network requests on subsequent page loads. + * + * WARNING: While it's possible to get away with it for smaller data sets, + * prefetched data isn't meant to contain entire sets of data. Rather, it should + * act as a first-level cache. Ignoring this warning means you'll run the risk + * of hitting local storage limits. + */ + interface PrefetchOptions { + /** + * The URL prefetch data should be loaded from. + */ + url: string; + + /** + * If false, will not attempt to read or write to local storage and + * will always load prefetch data from url on initialization. Defaults to true. + */ + cache?: boolean; + + /** + * The time (in milliseconds) the prefetched data should be cached in + * local storage. Defaults to 86400000 (1 day). + */ + ttl?: number; + + /** + * The key that data will be stored in local storage under. + * Defaults to value of url. + */ + cacheKey?: string; + + /** + * A string used for thumbprinting prefetched data. If this doesn't + * match what's stored in local storage, the data will be refetched. + */ + thumbprint?: string; + + /** + * A function that provides a hook to allow you to prepare the settings + * object passed to transport when a request is about to be made. + * Defaults to the identity function. + * + * @param settings The default settings object created internally by the Bloodhound instance. + * @returns A settings object. + */ + prepare?: (settings: JQueryAjaxSettings) => JQueryAjaxSettings; + + /** + * A function with the signature transform(response) that allows you to + * transform the prefetch response before the Bloodhound instance operates + * on it. Defaults to the identity function. + * + * @param response Prefetch response. + * @returns Transform response. + */ + transform?: (response: T[]) => T[]; + } + + /** + * Bloodhound only goes to the network when the internal search engine cannot + * provide a sufficient number of results. In order to prevent an obscene + * number of requests being made to the remote endpoint, requests are rate-limited. + */ + interface RemoteOptions { + /** + * The URL remote data should be loaded from. + */ + url: string; + + /** + * A function that provides a hook to allow you to prepare the settings + * object passed to transport when a request is about to be made. + * The function signature should be prepare(query, settings), where query + * is the query #search was called with and settings is the default settings + * object created internally by the Bloodhound instance. The prepare function + * should return a settings object. Defaults to the identity function. + * + * @param query The query #search was called with. + * @param settings The default settings object created internally by Bloodhound. + * @returns A JqueryAjaxSettings object. + */ + prepare?: (query: string, settings: JQueryAjaxSettings) => JQueryAjaxSettings; + + /** + * A convenience option for prepare. If set, prepare will be a function + * that replaces the value of this option in url with the URI encoded query. + */ + wildcard?: string; + + /** + * The method used to rate-limit network requests. + * Can be either debounce or throttle. Defaults to debounce. + */ + rateLimitby?: string; + + /** + * The time interval in milliseconds that will be used by rateLimitBy. + * Defaults to 300. + */ + rateLimitWait?: number; + + /** + * A function with the signature transform(response) that allows you to + * transform the remote response before the Bloodhound instance operates on it. + * Defaults to the identity function. + * + * @param response Prefetch response. + * @returns Transform response. + */ + transform?: (response: T[]) => T[]; + } + + /** + * Build-in tokenization methods. + */ + interface Tokenizers { + /** + * Split a given string on whitespace characters. + */ + whitespace(str: string): string[]; + + /** + * Split a given string on non-word characters. + */ + nonword(str: string): string[]; + + /** + * Instances of the build-in tokenization methods. + */ + obj: ObjTokenizer; + } + + interface ObjTokenizer { + /** + * Split a given string on whitespace characters. + */ + whitespace(str: string): string[]; + + /** + * Split a given string on non-word characters. + */ + nonword(str: string): string[]; + } +} + +/** + * Bloodhound is the typeahead.js suggestion engine. Bloodhound is robust, + * flexible, and offers advanced functionalities such as prefetching, + * intelligent caching, fast lookups, and backfilling with remote data. + */ +declare class Bloodhound { + /** + * The constructor function. + * + * @constructor + * @param options Options hash. + */ + constructor(options: Bloodhound.BloodhoundOptions); + + /** + * Returns a reference to Bloodhound and reverts window.Bloodhound to its + * previous value. Can be used to avoid naming collisions. + */ + public static noConflict(): Bloodhound; + + /** + * The Bloodhound suggestion engine is token-based, so how datums and queries are tokenized plays a vital role in the quality of search results. + * Specify how you want datums and queries tokenized. + */ + public static tokenizers: Bloodhound.Tokenizers; + + /** + * Kicks off the initialization of the suggestion engine. Initialization + * entails adding the data provided by local and prefetch to the internal + * search index as well as setting up transport mechanism used by remote. + * Before #initialize is called, the #get and #search methods will effectively be no-ops. + * + * Note, unless the initialize option is false, this method is implicitly called by the constructor. + * + * After initialization, how subsequent invocations of #initialize behave depends on + * the reinitialize argument. If reinitialize is falsy, the method will not execute the + * initialization logic and will just return the same jQuery promise returned + * by the initial invocation. If reinitialize is truthy, the method will behave + * as if it were being called for the first time. + * + * @param reinitialize How subsequent invocations of #initialize will behave. + * @returns jQuery promise. + */ + public initialize(reinitialize?: boolean): JQueryPromise; + + /** + * Takes one argument, data, which is expected to be an array. + * The data passed in will get added to the internal search index. + * + * @param data Data to be added to the internal search index. + */ + public add(data: T[]): void; + + /** + * Returns the data in the local search index corresponding to ids. + * + * @param ids Data ids. + * @returns The corresponding data. + */ + public get(ids: number[]): T[]; + + /** + * Returns the data that matches query. Matches found in the local search + * index will be passed to the sync callback. If the data passed to sync + * doesn't contain at least sufficient number of datums, remote data will + * be requested and then passed to the async callback. + * + * @param query Query. + * @param sync Sync callback + * @param async Async callback. + * @returns The data that matches query. + */ + public search(query: string, sync: (datums: T[]) => void, async: (datums: T[]) => void): T[]; + + /** + * Returns all items from the internal search index. + */ + public all(): T[]; + + /** + * Clears the internal search index that's powered by local, prefetch, and #add. + */ + public clear(): Bloodhound; + + /** + * If you're using prefetch, data gets cached in local storage in an effort to cut down on unnecessary network requests. + * clearPrefetchCache offers a way to programmatically clear said cache. + */ + public clearPrefetchCache(): Bloodhound; + + /** + * If you're using remote, Bloodhound will cache the 10 most recent responses in an effort to provide a better user experience. + * clearRemoteCache offers a way to programmatically clear said cache. + */ + public clearRemoteCache(): Bloodhound; +} + +declare module "bloodhound" { + export = Bloodhound; +} diff --git a/typescript-services/typescriptServices-tests.ts b/typescript-services/typescriptServices-tests.ts index 1c704b14e..57066d2b4 100644 --- a/typescript-services/typescriptServices-tests.ts +++ b/typescript-services/typescriptServices-tests.ts @@ -6,18 +6,18 @@ function transpile(input: string): string { } // compile -function compile(fileNames: string[], options: ts.CompilerOptions): number { - let program = ts.createProgram(fileNames, options); - let emitResult = program.emit(); - - let allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); - - allDiagnostics.forEach(diagnostic => { - let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); - let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); - console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); - }); - - let exitCode = emitResult.emitSkipped ? 1 : 0; - return exitCode; -} +function compile(fileNames: string[], options: ts.CompilerOptions): number { + let program = ts.createProgram(fileNames, options); + let emitResult = program.emit(); + + let allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + + allDiagnostics.forEach(diagnostic => { + let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); + console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); + }); + + let exitCode = emitResult.emitSkipped ? 1 : 0; + return exitCode; +} diff --git a/typescript-services/typescriptServices.d.ts b/typescript-services/typescriptServices.d.ts index dbd4919bf..3ab20d7c9 100644 --- a/typescript-services/typescriptServices.d.ts +++ b/typescript-services/typescriptServices.d.ts @@ -1,2148 +1,2148 @@ -// Type definitions for TypeScript API v0.4.0 -// Project: http://www.typescriptlang.org/ -// Definitions by: Microsoft TypeScript -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -declare namespace ts { - interface Map { - [index: string]: T; - } - interface FileMap { - get(fileName: string): T; - set(fileName: string, value: T): void; - contains(fileName: string): boolean; - remove(fileName: string): void; - forEachValue(f: (v: T) => void): void; - clear(): void; - } - interface TextRange { - pos: number; - end: number; - } - const enum SyntaxKind { - Unknown = 0, - EndOfFileToken = 1, - SingleLineCommentTrivia = 2, - MultiLineCommentTrivia = 3, - NewLineTrivia = 4, - WhitespaceTrivia = 5, - ShebangTrivia = 6, - ConflictMarkerTrivia = 7, - NumericLiteral = 8, - StringLiteral = 9, - RegularExpressionLiteral = 10, - NoSubstitutionTemplateLiteral = 11, - TemplateHead = 12, - TemplateMiddle = 13, - TemplateTail = 14, - OpenBraceToken = 15, - CloseBraceToken = 16, - OpenParenToken = 17, - CloseParenToken = 18, - OpenBracketToken = 19, - CloseBracketToken = 20, - DotToken = 21, - DotDotDotToken = 22, - SemicolonToken = 23, - CommaToken = 24, - LessThanToken = 25, - LessThanSlashToken = 26, - GreaterThanToken = 27, - LessThanEqualsToken = 28, - GreaterThanEqualsToken = 29, - EqualsEqualsToken = 30, - ExclamationEqualsToken = 31, - EqualsEqualsEqualsToken = 32, - ExclamationEqualsEqualsToken = 33, - EqualsGreaterThanToken = 34, - PlusToken = 35, - MinusToken = 36, - AsteriskToken = 37, - SlashToken = 38, - PercentToken = 39, - PlusPlusToken = 40, - MinusMinusToken = 41, - LessThanLessThanToken = 42, - GreaterThanGreaterThanToken = 43, - GreaterThanGreaterThanGreaterThanToken = 44, - AmpersandToken = 45, - BarToken = 46, - CaretToken = 47, - ExclamationToken = 48, - TildeToken = 49, - AmpersandAmpersandToken = 50, - BarBarToken = 51, - QuestionToken = 52, - ColonToken = 53, - AtToken = 54, - EqualsToken = 55, - PlusEqualsToken = 56, - MinusEqualsToken = 57, - AsteriskEqualsToken = 58, - SlashEqualsToken = 59, - PercentEqualsToken = 60, - LessThanLessThanEqualsToken = 61, - GreaterThanGreaterThanEqualsToken = 62, - GreaterThanGreaterThanGreaterThanEqualsToken = 63, - AmpersandEqualsToken = 64, - BarEqualsToken = 65, - CaretEqualsToken = 66, - Identifier = 67, - BreakKeyword = 68, - CaseKeyword = 69, - CatchKeyword = 70, - ClassKeyword = 71, - ConstKeyword = 72, - ContinueKeyword = 73, - DebuggerKeyword = 74, - DefaultKeyword = 75, - DeleteKeyword = 76, - DoKeyword = 77, - ElseKeyword = 78, - EnumKeyword = 79, - ExportKeyword = 80, - ExtendsKeyword = 81, - FalseKeyword = 82, - FinallyKeyword = 83, - ForKeyword = 84, - FunctionKeyword = 85, - IfKeyword = 86, - ImportKeyword = 87, - InKeyword = 88, - InstanceOfKeyword = 89, - NewKeyword = 90, - NullKeyword = 91, - ReturnKeyword = 92, - SuperKeyword = 93, - SwitchKeyword = 94, - ThisKeyword = 95, - ThrowKeyword = 96, - TrueKeyword = 97, - TryKeyword = 98, - TypeOfKeyword = 99, - VarKeyword = 100, - VoidKeyword = 101, - WhileKeyword = 102, - WithKeyword = 103, - ImplementsKeyword = 104, - InterfaceKeyword = 105, - LetKeyword = 106, - PackageKeyword = 107, - PrivateKeyword = 108, - ProtectedKeyword = 109, - PublicKeyword = 110, - StaticKeyword = 111, - YieldKeyword = 112, - AbstractKeyword = 113, - AsKeyword = 114, - AnyKeyword = 115, - AsyncKeyword = 116, - AwaitKeyword = 117, - BooleanKeyword = 118, - ConstructorKeyword = 119, - DeclareKeyword = 120, - GetKeyword = 121, - IsKeyword = 122, - ModuleKeyword = 123, - NamespaceKeyword = 124, - RequireKeyword = 125, - NumberKeyword = 126, - SetKeyword = 127, - StringKeyword = 128, - SymbolKeyword = 129, - TypeKeyword = 130, - FromKeyword = 131, - OfKeyword = 132, - QualifiedName = 133, - ComputedPropertyName = 134, - TypeParameter = 135, - Parameter = 136, - Decorator = 137, - PropertySignature = 138, - PropertyDeclaration = 139, - MethodSignature = 140, - MethodDeclaration = 141, - Constructor = 142, - GetAccessor = 143, - SetAccessor = 144, - CallSignature = 145, - ConstructSignature = 146, - IndexSignature = 147, - TypePredicate = 148, - TypeReference = 149, - FunctionType = 150, - ConstructorType = 151, - TypeQuery = 152, - TypeLiteral = 153, - ArrayType = 154, - TupleType = 155, - UnionType = 156, - IntersectionType = 157, - ParenthesizedType = 158, - ObjectBindingPattern = 159, - ArrayBindingPattern = 160, - BindingElement = 161, - ArrayLiteralExpression = 162, - ObjectLiteralExpression = 163, - PropertyAccessExpression = 164, - ElementAccessExpression = 165, - CallExpression = 166, - NewExpression = 167, - TaggedTemplateExpression = 168, - TypeAssertionExpression = 169, - ParenthesizedExpression = 170, - FunctionExpression = 171, - ArrowFunction = 172, - DeleteExpression = 173, - TypeOfExpression = 174, - VoidExpression = 175, - AwaitExpression = 176, - PrefixUnaryExpression = 177, - PostfixUnaryExpression = 178, - BinaryExpression = 179, - ConditionalExpression = 180, - TemplateExpression = 181, - YieldExpression = 182, - SpreadElementExpression = 183, - ClassExpression = 184, - OmittedExpression = 185, - ExpressionWithTypeArguments = 186, - AsExpression = 187, - TemplateSpan = 188, - SemicolonClassElement = 189, - Block = 190, - VariableStatement = 191, - EmptyStatement = 192, - ExpressionStatement = 193, - IfStatement = 194, - DoStatement = 195, - WhileStatement = 196, - ForStatement = 197, - ForInStatement = 198, - ForOfStatement = 199, - ContinueStatement = 200, - BreakStatement = 201, - ReturnStatement = 202, - WithStatement = 203, - SwitchStatement = 204, - LabeledStatement = 205, - ThrowStatement = 206, - TryStatement = 207, - DebuggerStatement = 208, - VariableDeclaration = 209, - VariableDeclarationList = 210, - FunctionDeclaration = 211, - ClassDeclaration = 212, - InterfaceDeclaration = 213, - TypeAliasDeclaration = 214, - EnumDeclaration = 215, - ModuleDeclaration = 216, - ModuleBlock = 217, - CaseBlock = 218, - ImportEqualsDeclaration = 219, - ImportDeclaration = 220, - ImportClause = 221, - NamespaceImport = 222, - NamedImports = 223, - ImportSpecifier = 224, - ExportAssignment = 225, - ExportDeclaration = 226, - NamedExports = 227, - ExportSpecifier = 228, - MissingDeclaration = 229, - ExternalModuleReference = 230, - JsxElement = 231, - JsxSelfClosingElement = 232, - JsxOpeningElement = 233, - JsxText = 234, - JsxClosingElement = 235, - JsxAttribute = 236, - JsxSpreadAttribute = 237, - JsxExpression = 238, - CaseClause = 239, - DefaultClause = 240, - HeritageClause = 241, - CatchClause = 242, - PropertyAssignment = 243, - ShorthandPropertyAssignment = 244, - EnumMember = 245, - SourceFile = 246, - JSDocTypeExpression = 247, - JSDocAllType = 248, - JSDocUnknownType = 249, - JSDocArrayType = 250, - JSDocUnionType = 251, - JSDocTupleType = 252, - JSDocNullableType = 253, - JSDocNonNullableType = 254, - JSDocRecordType = 255, - JSDocRecordMember = 256, - JSDocTypeReference = 257, - JSDocOptionalType = 258, - JSDocFunctionType = 259, - JSDocVariadicType = 260, - JSDocConstructorType = 261, - JSDocThisType = 262, - JSDocComment = 263, - JSDocTag = 264, - JSDocParameterTag = 265, - JSDocReturnTag = 266, - JSDocTypeTag = 267, - JSDocTemplateTag = 268, - SyntaxList = 269, - Count = 270, - FirstAssignment = 55, - LastAssignment = 66, - FirstReservedWord = 68, - LastReservedWord = 103, - FirstKeyword = 68, - LastKeyword = 132, - FirstFutureReservedWord = 104, - LastFutureReservedWord = 112, - FirstTypeNode = 149, - LastTypeNode = 158, - FirstPunctuation = 15, - LastPunctuation = 66, - FirstToken = 0, - LastToken = 132, - FirstTriviaToken = 2, - LastTriviaToken = 7, - FirstLiteralToken = 8, - LastLiteralToken = 11, - FirstTemplateToken = 11, - LastTemplateToken = 14, - FirstBinaryOperator = 25, - LastBinaryOperator = 66, - FirstNode = 133, - } - const enum NodeFlags { - Export = 1, - Ambient = 2, - Public = 16, - Private = 32, - Protected = 64, - Static = 128, - Abstract = 256, - Async = 512, - Default = 1024, - MultiLine = 2048, - Synthetic = 4096, - DeclarationFile = 8192, - Let = 16384, - Const = 32768, - OctalLiteral = 65536, - Namespace = 131072, - ExportContext = 262144, - Modifier = 2035, - AccessibilityModifier = 112, - BlockScoped = 49152, - } - const enum JsxFlags { - None = 0, - IntrinsicNamedElement = 1, - IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, - IntrinsicElement = 3, - } - interface Node extends TextRange { - kind: SyntaxKind; - flags: NodeFlags; - decorators?: NodeArray; - modifiers?: ModifiersArray; - parent?: Node; - } - interface NodeArray extends Array, TextRange { - hasTrailingComma?: boolean; - } - interface ModifiersArray extends NodeArray { - flags: number; - } - interface Identifier extends PrimaryExpression { - text: string; - originalKeywordKind?: SyntaxKind; - } - interface QualifiedName extends Node { - left: EntityName; - right: Identifier; - } - type EntityName = Identifier | QualifiedName; - type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; - interface Declaration extends Node { - _declarationBrand: any; - name?: DeclarationName; - } - interface ComputedPropertyName extends Node { - expression: Expression; - } - interface Decorator extends Node { - expression: LeftHandSideExpression; - } - interface TypeParameterDeclaration extends Declaration { - name: Identifier; - constraint?: TypeNode; - expression?: Expression; - } - interface SignatureDeclaration extends Declaration { - typeParameters?: NodeArray; - parameters: NodeArray; - type?: TypeNode; - } - interface VariableDeclaration extends Declaration { - parent?: VariableDeclarationList; - name: Identifier | BindingPattern; - type?: TypeNode; - initializer?: Expression; - } - interface VariableDeclarationList extends Node { - declarations: NodeArray; - } - interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingElement extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - initializer?: Expression; - } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface ObjectLiteralElement extends Declaration { - _objectLiteralBrandBrand: any; - } - interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; - name: DeclarationName; - questionToken?: Node; - initializer: Expression; - } - interface ShorthandPropertyAssignment extends ObjectLiteralElement { - name: Identifier; - questionToken?: Node; - } - interface VariableLikeDeclaration extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingPattern extends Node { - elements: NodeArray; - } - /** - * Several node kinds share function-like features such as a signature, - * a name, and a body. These nodes should extend FunctionLikeDeclaration. - * Examples: - * - FunctionDeclaration - * - MethodDeclaration - * - AccessorDeclaration - */ - interface FunctionLikeDeclaration extends SignatureDeclaration { - _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; - body?: Block | Expression; - } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { - name?: Identifier; - body?: Block; - } - interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; - } - interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; - } - interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; - } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; - body: Block; - } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { - _indexSignatureDeclarationBrand: any; - } - interface TypeNode extends Node { - _typeNodeBrand: any; - } - interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; - } - interface TypeReferenceNode extends TypeNode { - typeName: EntityName; - typeArguments?: NodeArray; - } - interface TypePredicateNode extends TypeNode { - parameterName: Identifier; - type: TypeNode; - } - interface TypeQueryNode extends TypeNode { - exprName: EntityName; - } - interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; - } - interface ArrayTypeNode extends TypeNode { - elementType: TypeNode; - } - interface TupleTypeNode extends TypeNode { - elementTypes: NodeArray; - } - interface UnionOrIntersectionTypeNode extends TypeNode { - types: NodeArray; - } - interface UnionTypeNode extends UnionOrIntersectionTypeNode { - } - interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { - } - interface ParenthesizedTypeNode extends TypeNode { - type: TypeNode; - } - interface StringLiteral extends LiteralExpression, TypeNode { - _stringLiteralBrand: any; - } - interface Expression extends Node { - _expressionBrand: any; - contextualType?: Type; - } - interface UnaryExpression extends Expression { - _unaryExpressionBrand: any; - } - interface PrefixUnaryExpression extends UnaryExpression { - operator: SyntaxKind; - operand: UnaryExpression; - } - interface PostfixUnaryExpression extends PostfixExpression { - operand: LeftHandSideExpression; - operator: SyntaxKind; - } - interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; - } - interface LeftHandSideExpression extends PostfixExpression { - _leftHandSideExpressionBrand: any; - } - interface MemberExpression extends LeftHandSideExpression { - _memberExpressionBrand: any; - } - interface PrimaryExpression extends MemberExpression { - _primaryExpressionBrand: any; - } - interface DeleteExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface TypeOfExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface VoidExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface AwaitExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface YieldExpression extends Expression { - asteriskToken?: Node; - expression?: Expression; - } - interface BinaryExpression extends Expression { - left: Expression; - operatorToken: Node; - right: Expression; - } - interface ConditionalExpression extends Expression { - condition: Expression; - questionToken: Node; - whenTrue: Expression; - colonToken: Node; - whenFalse: Expression; - } - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { - name?: Identifier; - body: Block | Expression; - } - interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; - } - interface LiteralExpression extends PrimaryExpression { - text: string; - isUnterminated?: boolean; - hasExtendedUnicodeEscape?: boolean; - } - interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; - templateSpans: NodeArray; - } - interface TemplateSpan extends Node { - expression: Expression; - literal: LiteralExpression; - } - interface ParenthesizedExpression extends PrimaryExpression { - expression: Expression; - } - interface ArrayLiteralExpression extends PrimaryExpression { - elements: NodeArray; - } - interface SpreadElementExpression extends Expression { - expression: Expression; - } - interface ObjectLiteralExpression extends PrimaryExpression, Declaration { - properties: NodeArray; - } - interface PropertyAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - dotToken: Node; - name: Identifier; - } - interface ElementAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - argumentExpression?: Expression; - } - interface CallExpression extends LeftHandSideExpression { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - arguments: NodeArray; - } - interface ExpressionWithTypeArguments extends TypeNode { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - } - interface NewExpression extends CallExpression, PrimaryExpression { - } - interface TaggedTemplateExpression extends MemberExpression { - tag: LeftHandSideExpression; - template: LiteralExpression | TemplateExpression; - } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; - interface AsExpression extends Expression { - expression: Expression; - type: TypeNode; - } - interface TypeAssertion extends UnaryExpression { - type: TypeNode; - expression: UnaryExpression; - } - type AssertionExpression = TypeAssertion | AsExpression; - interface JsxElement extends PrimaryExpression { - openingElement: JsxOpeningElement; - children: NodeArray; - closingElement: JsxClosingElement; - } - interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; - tagName: EntityName; - attributes: NodeArray; - } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; - } - type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; - interface JsxAttribute extends Node { - name: Identifier; - initializer?: Expression; - } - interface JsxSpreadAttribute extends Node { - expression: Expression; - } - interface JsxClosingElement extends Node { - tagName: EntityName; - } - interface JsxExpression extends Expression { - expression?: Expression; - } - interface JsxText extends Node { - _jsxTextExpressionBrand: any; - } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; - interface Statement extends Node { - _statementBrand: any; - } - interface Block extends Statement { - statements: NodeArray; - } - interface VariableStatement extends Statement { - declarationList: VariableDeclarationList; - } - interface ExpressionStatement extends Statement { - expression: Expression; - } - interface IfStatement extends Statement { - expression: Expression; - thenStatement: Statement; - elseStatement?: Statement; - } - interface IterationStatement extends Statement { - statement: Statement; - } - interface DoStatement extends IterationStatement { - expression: Expression; - } - interface WhileStatement extends IterationStatement { - expression: Expression; - } - interface ForStatement extends IterationStatement { - initializer?: VariableDeclarationList | Expression; - condition?: Expression; - incrementor?: Expression; - } - interface ForInStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface ForOfStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface BreakOrContinueStatement extends Statement { - label?: Identifier; - } - interface ReturnStatement extends Statement { - expression?: Expression; - } - interface WithStatement extends Statement { - expression: Expression; - statement: Statement; - } - interface SwitchStatement extends Statement { - expression: Expression; - caseBlock: CaseBlock; - } - interface CaseBlock extends Node { - clauses: NodeArray; - } - interface CaseClause extends Node { - expression?: Expression; - statements: NodeArray; - } - interface DefaultClause extends Node { - statements: NodeArray; - } - type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement { - label: Identifier; - statement: Statement; - } - interface ThrowStatement extends Statement { - expression: Expression; - } - interface TryStatement extends Statement { - tryBlock: Block; - catchClause?: CatchClause; - finallyBlock?: Block; - } - interface CatchClause extends Node { - variableDeclaration: VariableDeclaration; - block: Block; - } - interface ClassLikeDeclaration extends Declaration { - name?: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { - } - interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { - } - interface ClassElement extends Declaration { - _classElementBrand: any; - } - interface InterfaceDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface HeritageClause extends Node { - token: SyntaxKind; - types?: NodeArray; - } - interface TypeAliasDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - type: TypeNode; - } - interface EnumMember extends Declaration { - name: DeclarationName; - initializer?: Expression; - } - interface EnumDeclaration extends Declaration, Statement { - name: Identifier; - members: NodeArray; - } - interface ModuleDeclaration extends Declaration, Statement { - name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; - } - interface ModuleBlock extends Node, Statement { - statements: NodeArray; - } - interface ImportEqualsDeclaration extends Declaration, Statement { - name: Identifier; - moduleReference: EntityName | ExternalModuleReference; - } - interface ExternalModuleReference extends Node { - expression?: Expression; - } - interface ImportDeclaration extends Statement { - importClause?: ImportClause; - moduleSpecifier: Expression; - } - interface ImportClause extends Declaration { - name?: Identifier; - namedBindings?: NamespaceImport | NamedImports; - } - interface NamespaceImport extends Declaration { - name: Identifier; - } - interface ExportDeclaration extends Declaration, Statement { - exportClause?: NamedExports; - moduleSpecifier?: Expression; - } - interface NamedImportsOrExports extends Node { - elements: NodeArray; - } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { - propertyName?: Identifier; - name: Identifier; - } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { - isExportEquals?: boolean; - expression: Expression; - } - interface FileReference extends TextRange { - fileName: string; - } - interface CommentRange extends TextRange { - hasTrailingNewLine?: boolean; - kind: SyntaxKind; - } - interface JSDocTypeExpression extends Node { - type: JSDocType; - } - interface JSDocType extends TypeNode { - _jsDocTypeBrand: any; - } - interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; - } - interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; - } - interface JSDocArrayType extends JSDocType { - elementType: JSDocType; - } - interface JSDocUnionType extends JSDocType { - types: NodeArray; - } - interface JSDocTupleType extends JSDocType { - types: NodeArray; - } - interface JSDocNonNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { - members: NodeArray; - } - interface JSDocTypeReference extends JSDocType { - name: EntityName; - typeArguments: NodeArray; - } - interface JSDocOptionalType extends JSDocType { - type: JSDocType; - } - interface JSDocFunctionType extends JSDocType, SignatureDeclaration { - parameters: NodeArray; - type: JSDocType; - } - interface JSDocVariadicType extends JSDocType { - type: JSDocType; - } - interface JSDocConstructorType extends JSDocType { - type: JSDocType; - } - interface JSDocThisType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordMember extends PropertyDeclaration { - name: Identifier | LiteralExpression; - type?: JSDocType; - } - interface JSDocComment extends Node { - tags: NodeArray; - } - interface JSDocTag extends Node { - atToken: Node; - tagName: Identifier; - } - interface JSDocTemplateTag extends JSDocTag { - typeParameters: NodeArray; - } - interface JSDocReturnTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocTypeTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocParameterTag extends JSDocTag { - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - postParameterName?: Identifier; - isBracketed: boolean; - } - interface SourceFile extends Declaration { - statements: NodeArray; - endOfFileToken: Node; - fileName: string; - text: string; - amdDependencies: { - path: string; - name: string; - }[]; - moduleName: string; - referencedFiles: FileReference[]; - languageVariant: LanguageVariant; - /** - * lib.d.ts should have a reference comment like - * - * /// - * - * If any other file has this comment, it signals not to include lib.d.ts - * because this containing file is intended to act as a default library. - */ - hasNoDefaultLib: boolean; - languageVersion: ScriptTarget; - } - interface ScriptReferenceHost { - getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile; - getCurrentDirectory(): string; - } - interface ParseConfigHost extends ModuleResolutionHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; - } - interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; - } - class OperationCanceledException { - } - interface CancellationToken { - isCancellationRequested(): boolean; - /** @throws OperationCanceledException if isCancellationRequested is true */ - throwIfCancellationRequested(): void; - } - interface Program extends ScriptReferenceHost { - /** - * Get a list of root file names that were passed to a 'createProgram' - */ - getRootFileNames(): string[]; - /** - * Get a list of files in the program - */ - getSourceFiles(): SourceFile[]; - /** - * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then - * the JavaScript and declaration files will be produced for all the files in this program. - * If targetSourceFile is specified, then only the JavaScript and declaration for that - * specific file will be generated. - * - * If writeFile is not specified then the writeFile callback from the compiler host will be - * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter - * will be invoked when writing the JavaScript and declaration files. - */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - /** - * Gets a type checker that can be used to semantically analyze source fils in the program. - */ - getTypeChecker(): TypeChecker; - } - interface SourceMapSpan { - /** Line number in the .js file. */ - emittedLine: number; - /** Column number in the .js file. */ - emittedColumn: number; - /** Line number in the .ts file. */ - sourceLine: number; - /** Column number in the .ts file. */ - sourceColumn: number; - /** Optional name (index into names array) associated with this span. */ - nameIndex?: number; - /** .ts file (index into sources array) associated with this span */ - sourceIndex: number; - } - interface SourceMapData { - sourceMapFilePath: string; - jsSourceMappingURL: string; - sourceMapFile: string; - sourceMapSourceRoot: string; - sourceMapSources: string[]; - sourceMapSourcesContent?: string[]; - inputSourceFileNames: string[]; - sourceMapNames?: string[]; - sourceMapMappings: string; - sourceMapDecodedMappings: SourceMapSpan[]; - } - /** Return code used by getEmitOutput function to indicate status of the function */ - enum ExitStatus { - Success = 0, - DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, - } - interface EmitResult { - emitSkipped: boolean; - diagnostics: Diagnostic[]; - } - interface TypeChecker { - getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; - getDeclaredTypeOfSymbol(symbol: Symbol): Type; - getPropertiesOfType(type: Type): Symbol[]; - getPropertyOfType(type: Type, propertyName: string): Symbol; - getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; - getIndexTypeOfType(type: Type, kind: IndexKind): Type; - getBaseTypes(type: InterfaceType): ObjectType[]; - getReturnTypeOfSignature(signature: Signature): Type; - getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getTypeAtLocation(node: Node): Type; - typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; - getSymbolDisplayBuilder(): SymbolDisplayBuilder; - getFullyQualifiedName(symbol: Symbol): string; - getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; - isUndefinedSymbol(symbol: Symbol): boolean; - isArgumentsSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; - isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; - getAliasedSymbol(symbol: Symbol): Symbol; - getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; - getJsxIntrinsicTagNames(): Symbol[]; - isOptionalParameter(node: ParameterDeclaration): boolean; - } - interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - interface SymbolWriter { - writeKeyword(text: string): void; - writeOperator(text: string): void; - writePunctuation(text: string): void; - writeSpace(text: string): void; - writeStringLiteral(text: string): void; - writeParameter(text: string): void; - writeSymbol(text: string, symbol: Symbol): void; - writeLine(): void; - increaseIndent(): void; - decreaseIndent(): void; - clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - } - const enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 2, - NoTruncation = 4, - WriteArrowStyleSignature = 8, - WriteOwnNameForAnyLike = 16, - WriteTypeArgumentsOfSignature = 32, - InElementType = 64, - UseFullyQualifiedType = 128, - } - const enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, - } - interface TypePredicate { - parameterName: string; - parameterIndex: number; - type: Type; - } - const enum SymbolFlags { - None = 0, - FunctionScopedVariable = 1, - BlockScopedVariable = 2, - Property = 4, - EnumMember = 8, - Function = 16, - Class = 32, - Interface = 64, - ConstEnum = 128, - RegularEnum = 256, - ValueModule = 512, - NamespaceModule = 1024, - TypeLiteral = 2048, - ObjectLiteral = 4096, - Method = 8192, - Constructor = 16384, - GetAccessor = 32768, - SetAccessor = 65536, - Signature = 131072, - TypeParameter = 262144, - TypeAlias = 524288, - ExportValue = 1048576, - ExportType = 2097152, - ExportNamespace = 4194304, - Alias = 8388608, - Instantiated = 16777216, - Merged = 33554432, - Transient = 67108864, - Prototype = 134217728, - SyntheticProperty = 268435456, - Optional = 536870912, - ExportStar = 1073741824, - Enum = 384, - Variable = 3, - Value = 107455, - Type = 793056, - Namespace = 1536, - Module = 1536, - Accessor = 98304, - FunctionScopedVariableExcludes = 107454, - BlockScopedVariableExcludes = 107455, - ParameterExcludes = 107455, - PropertyExcludes = 107455, - EnumMemberExcludes = 107455, - FunctionExcludes = 106927, - ClassExcludes = 899519, - InterfaceExcludes = 792960, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 106639, - NamespaceModuleExcludes = 0, - MethodExcludes = 99263, - GetAccessorExcludes = 41919, - SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, - AliasExcludes = 8388608, - ModuleMember = 8914931, - ExportHasLocal = 944, - HasExports = 1952, - HasMembers = 6240, - BlockScoped = 418, - PropertyOrAccessor = 98308, - Export = 7340032, - } - interface Symbol { - flags: SymbolFlags; - name: string; - declarations?: Declaration[]; - valueDeclaration?: Declaration; - members?: SymbolTable; - exports?: SymbolTable; - } - interface SymbolTable { - [index: string]: Symbol; - } - const enum TypeFlags { - Any = 1, - String = 2, - Number = 4, - Boolean = 8, - Void = 16, - Undefined = 32, - Null = 64, - Enum = 128, - StringLiteral = 256, - TypeParameter = 512, - Class = 1024, - Interface = 2048, - Reference = 4096, - Tuple = 8192, - Union = 16384, - Intersection = 32768, - Anonymous = 65536, - Instantiated = 131072, - ObjectLiteral = 524288, - ESSymbol = 16777216, - StringLike = 258, - NumberLike = 132, - ObjectType = 80896, - UnionOrIntersection = 49152, - StructuredType = 130048, - } - interface Type { - flags: TypeFlags; - symbol?: Symbol; - } - interface StringLiteralType extends Type { - text: string; - } - interface ObjectType extends Type { - } - interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - } - interface InterfaceTypeWithDeclaredMembers extends InterfaceType { - declaredProperties: Symbol[]; - declaredCallSignatures: Signature[]; - declaredConstructSignatures: Signature[]; - declaredStringIndexType: Type; - declaredNumberIndexType: Type; - } - interface TypeReference extends ObjectType { - target: GenericType; - typeArguments: Type[]; - } - interface GenericType extends InterfaceType, TypeReference { - } - interface TupleType extends ObjectType { - elementTypes: Type[]; - baseArrayType: TypeReference; - } - interface UnionOrIntersectionType extends Type { - types: Type[]; - } - interface UnionType extends UnionOrIntersectionType { - } - interface IntersectionType extends UnionOrIntersectionType { - } - interface TypeParameter extends Type { - constraint: Type; - } - const enum SignatureKind { - Call = 0, - Construct = 1, - } - interface Signature { - declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; - parameters: Symbol[]; - typePredicate?: TypePredicate; - } - const enum IndexKind { - String = 0, - Number = 1, - } - interface DiagnosticMessage { - key: string; - category: DiagnosticCategory; - code: number; - } - /** - * A linked list of formatted diagnostic messages to be used as part of a multiline message. - * It is built from the bottom up, leaving the head to be the "main" diagnostic. - * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, - * the difference is that messages are all preformatted in DMC. - */ - interface DiagnosticMessageChain { - messageText: string; - category: DiagnosticCategory; - code: number; - next?: DiagnosticMessageChain; - } - interface Diagnostic { - file: SourceFile; - start: number; - length: number; - messageText: string | DiagnosticMessageChain; - category: DiagnosticCategory; - code: number; - } - enum DiagnosticCategory { - Warning = 0, - Error = 1, - Message = 2, - } - const enum ModuleResolutionKind { - Classic = 1, - NodeJs = 2, - } - interface CompilerOptions { - allowNonTsExtensions?: boolean; - charset?: string; - declaration?: boolean; - diagnostics?: boolean; - emitBOM?: boolean; - help?: boolean; - init?: boolean; - inlineSourceMap?: boolean; - inlineSources?: boolean; - jsx?: JsxEmit; - listFiles?: boolean; - locale?: string; - mapRoot?: string; - module?: ModuleKind; - newLine?: NewLineKind; - noEmit?: boolean; - noEmitHelpers?: boolean; - noEmitOnError?: boolean; - noErrorTruncation?: boolean; - noImplicitAny?: boolean; - noLib?: boolean; - noResolve?: boolean; - out?: string; - outFile?: string; - outDir?: string; - preserveConstEnums?: boolean; - project?: string; - removeComments?: boolean; - rootDir?: string; - sourceMap?: boolean; - sourceRoot?: string; - suppressExcessPropertyErrors?: boolean; - suppressImplicitAnyIndexErrors?: boolean; - target?: ScriptTarget; - version?: boolean; - watch?: boolean; - isolatedModules?: boolean; - experimentalDecorators?: boolean; - experimentalAsyncFunctions?: boolean; - emitDecoratorMetadata?: boolean; - moduleResolution?: ModuleResolutionKind; - [option: string]: string | number | boolean; - } - const enum ModuleKind { - None = 0, - CommonJS = 1, - AMD = 2, - UMD = 3, - System = 4, - } - const enum JsxEmit { - None = 0, - Preserve = 1, - React = 2, - } - const enum NewLineKind { - CarriageReturnLineFeed = 0, - LineFeed = 1, - } - interface LineAndCharacter { - line: number; - character: number; - } - const enum ScriptTarget { - ES3 = 0, - ES5 = 1, - ES6 = 2, - Latest = 2, - } - const enum LanguageVariant { - Standard = 0, - JSX = 1, - } - interface ParsedCommandLine { - options: CompilerOptions; - fileNames: string[]; - errors: Diagnostic[]; - } - interface ModuleResolutionHost { - fileExists(fileName: string): boolean; - readFile(fileName: string): string; - } - interface ResolvedModule { - resolvedFileName: string; - isExternalLibraryImport?: boolean; - } - interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; - failedLookupLocations: string[]; - } - interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; - getCancellationToken?(): CancellationToken; - getDefaultLibFileName(options: CompilerOptions): string; - writeFile: WriteFileCallback; - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - useCaseSensitiveFileNames(): boolean; - getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface TextSpan { - start: number; - length: number; - } - interface TextChangeRange { - span: TextSpan; - newLength: number; - } -} -declare namespace ts { - interface System { - args: string[]; - newLine: string; - useCaseSensitiveFileNames: boolean; - write(s: string): void; - readFile(path: string, encoding?: string): string; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: (path: string) => void): FileWatcher; - resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getExecutingFilePath(): string; - getCurrentDirectory(): string; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; - getMemoryUsage?(): number; - exit(exitCode?: number): void; - } - interface FileWatcher { - close(): void; - } - var sys: System; -} -declare namespace ts { - interface ErrorCallback { - (message: DiagnosticMessage, length: number): void; - } - interface Scanner { - getStartPos(): number; - getToken(): SyntaxKind; - getTextPos(): number; - getTokenPos(): number; - getTokenText(): string; - getTokenValue(): string; - hasExtendedUnicodeEscape(): boolean; - hasPrecedingLineBreak(): boolean; - isIdentifier(): boolean; - isReservedWord(): boolean; - isUnterminated(): boolean; - reScanGreaterToken(): SyntaxKind; - reScanSlashToken(): SyntaxKind; - reScanTemplateToken(): SyntaxKind; - scanJsxIdentifier(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; - scan(): SyntaxKind; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; - setScriptTarget(scriptTarget: ScriptTarget): void; - setLanguageVariant(variant: LanguageVariant): void; - setTextPos(textPos: number): void; - lookAhead(callback: () => T): T; - tryScan(callback: () => T): T; - } - function tokenToString(t: SyntaxKind): string; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; - function isWhiteSpace(ch: number): boolean; - function isLineBreak(ch: number): boolean; - function couldStartTrivia(text: string, pos: number): boolean; - function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; - function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; - /** Optionally, get the shebang */ - function getShebang(text: string): string; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; -} -declare namespace ts { - function getDefaultLibFileName(options: CompilerOptions): string; - function textSpanEnd(span: TextSpan): number; - function textSpanIsEmpty(span: TextSpan): boolean; - function textSpanContainsPosition(span: TextSpan, position: number): boolean; - function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; - function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; - function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; - function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; - function createTextSpan(start: number, length: number): TextSpan; - function createTextSpanFromBounds(start: number, end: number): TextSpan; - function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; - function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; - function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; - let unchangedTextChangeRange: TextChangeRange; - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; -} -declare namespace ts { - function getNodeConstructor(kind: SyntaxKind): new () => Node; - function createNode(kind: SyntaxKind): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; - function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; - function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; -} -declare namespace ts { - const version: string; - function findConfigFile(searchPath: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; -} -declare namespace ts { - function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readConfigFile(fileName: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file - */ - function parseConfigFileText(fileName: string, jsonText: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; -} -declare namespace ts { - /** The version of the language service API */ - let servicesVersion: string; - interface Node { - getSourceFile(): SourceFile; - getChildCount(sourceFile?: SourceFile): number; - getChildAt(index: number, sourceFile?: SourceFile): Node; - getChildren(sourceFile?: SourceFile): Node[]; - getStart(sourceFile?: SourceFile): number; - getFullStart(): number; - getEnd(): number; - getWidth(sourceFile?: SourceFile): number; - getFullWidth(): number; - getLeadingTriviaWidth(sourceFile?: SourceFile): number; - getFullText(sourceFile?: SourceFile): string; - getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; - } - interface Symbol { - getFlags(): SymbolFlags; - getName(): string; - getDeclarations(): Declaration[]; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface Type { - getFlags(): TypeFlags; - getSymbol(): Symbol; - getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol; - getApparentProperties(): Symbol[]; - getCallSignatures(): Signature[]; - getConstructSignatures(): Signature[]; - getStringIndexType(): Type; - getNumberIndexType(): Type; - getBaseTypes(): ObjectType[]; - } - interface Signature { - getDeclaration(): SignatureDeclaration; - getTypeParameters(): Type[]; - getParameters(): Symbol[]; - getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface SourceFile { - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - getLineStarts(): number[]; - getPositionOfLineAndCharacter(line: number, character: number): number; - update(newText: string, textChangeRange: TextChangeRange): SourceFile; - } - /** - * Represents an immutable snapshot of a script at a specified time.Once acquired, the - * snapshot is observably immutable. i.e. the same calls with the same parameters will return - * the same values. - */ - interface IScriptSnapshot { - /** Gets a portion of the script snapshot specified by [start, end). */ - getText(start: number, end: number): string; - /** Gets the length of this script snapshot. */ - getLength(): number; - /** - * Gets the TextChangeRange that describe how the text changed between this text and - * an older version. This information is used by the incremental parser to determine - * what sections of the script need to be re-parsed. 'undefined' can be returned if the - * change range cannot be determined. However, in that case, incremental parsing will - * not happen and the entire document will be re - parsed. - */ - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; - /** Releases all resources held by this script snapshot */ - dispose?(): void; - } - module ScriptSnapshot { - function fromString(text: string): IScriptSnapshot; - } - interface PreProcessedFileInfo { - referencedFiles: FileReference[]; - importedFiles: FileReference[]; - ambientExternalModules: string[]; - isLibFile: boolean; - } - interface HostCancellationToken { - isCancellationRequested(): boolean; - } - interface LanguageServiceHost { - getCompilationSettings(): CompilerOptions; - getNewLine?(): string; - getProjectVersion?(): string; - getScriptFileNames(): string[]; - getScriptVersion(fileName: string): string; - getScriptSnapshot(fileName: string): IScriptSnapshot; - getLocalizedDiagnosticMessages?(): any; - getCancellationToken?(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(options: CompilerOptions): string; - log?(s: string): void; - trace?(s: string): void; - error?(s: string): void; - useCaseSensitiveFileNames?(): boolean; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface LanguageService { - cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; - getSemanticDiagnostics(fileName: string): Diagnostic[]; - getCompilerOptionsDiagnostics(): Diagnostic[]; - /** - * @deprecated Use getEncodedSyntacticClassifications instead. - */ - getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - /** - * @deprecated Use getEncodedSemanticClassifications instead. - */ - getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; - getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; - /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; - getNavigationBarItems(fileName: string): NavigationBarItem[]; - getOutliningSpans(fileName: string): OutliningSpan[]; - getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; - getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; - getEmitOutput(fileName: string): EmitOutput; - getProgram(): Program; - getSourceFile(fileName: string): SourceFile; - dispose(): void; - } - interface Classifications { - spans: number[]; - endOfLineState: EndOfLineState; - } - interface ClassifiedSpan { - textSpan: TextSpan; - classificationType: string; - } - interface NavigationBarItem { - text: string; - kind: string; - kindModifiers: string; - spans: TextSpan[]; - childItems: NavigationBarItem[]; - indent: number; - bolded: boolean; - grayed: boolean; - } - interface TodoCommentDescriptor { - text: string; - priority: number; - } - interface TodoComment { - descriptor: TodoCommentDescriptor; - message: string; - position: number; - } - class TextChange { - span: TextSpan; - newText: string; - } - interface TextInsertion { - newText: string; - /** The position in newText the caret should point to after the insertion. */ - caretOffset: number; - } - interface RenameLocation { - textSpan: TextSpan; - fileName: string; - } - interface ReferenceEntry { - textSpan: TextSpan; - fileName: string; - isWriteAccess: boolean; - } - interface DocumentHighlights { - fileName: string; - highlightSpans: HighlightSpan[]; - } - module HighlightSpanKind { - const none: string; - const definition: string; - const reference: string; - const writtenReference: string; - } - interface HighlightSpan { - fileName?: string; - textSpan: TextSpan; - kind: string; - } - interface NavigateToItem { - name: string; - kind: string; - kindModifiers: string; - matchKind: string; - isCaseSensitive: boolean; - fileName: string; - textSpan: TextSpan; - containerName: string; - containerKind: string; - } - interface EditorOptions { - IndentSize: number; - TabSize: number; - NewLineCharacter: string; - ConvertTabsToSpaces: boolean; - } - interface FormatCodeOptions extends EditorOptions { - InsertSpaceAfterCommaDelimiter: boolean; - InsertSpaceAfterSemicolonInForStatements: boolean; - InsertSpaceBeforeAndAfterBinaryOperators: boolean; - InsertSpaceAfterKeywordsInControlFlowStatements: boolean; - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - PlaceOpenBraceOnNewLineForFunctions: boolean; - PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string; - } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; - kind: string; - name: string; - containerKind: string; - containerName: string; - } - interface ReferencedSymbol { - definition: DefinitionInfo; - references: ReferenceEntry[]; - } - enum SymbolDisplayPartKind { - aliasName = 0, - className = 1, - enumName = 2, - fieldName = 3, - interfaceName = 4, - keyword = 5, - lineBreak = 6, - numericLiteral = 7, - stringLiteral = 8, - localName = 9, - methodName = 10, - moduleName = 11, - operator = 12, - parameterName = 13, - propertyName = 14, - punctuation = 15, - space = 16, - text = 17, - typeParameterName = 18, - enumMemberName = 19, - functionName = 20, - regularExpressionLiteral = 21, - } - interface SymbolDisplayPart { - text: string; - kind: string; - } - interface QuickInfo { - kind: string; - kindModifiers: string; - textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage: string; - displayName: string; - fullDisplayName: string; - kind: string; - kindModifiers: string; - triggerSpan: TextSpan; - } - interface SignatureHelpParameter { - name: string; - documentation: SymbolDisplayPart[]; - displayParts: SymbolDisplayPart[]; - isOptional: boolean; - } - /** - * Represents a single signature to show in signature help. - * The id is used for subsequent calls into the language service to ask questions about the - * signature help item in the context of any documents that have been updated. i.e. after - * an edit has happened, while signature help is still active, the host can ask important - * questions like 'what parameter is the user currently contained within?'. - */ - interface SignatureHelpItem { - isVariadic: boolean; - prefixDisplayParts: SymbolDisplayPart[]; - suffixDisplayParts: SymbolDisplayPart[]; - separatorDisplayParts: SymbolDisplayPart[]; - parameters: SignatureHelpParameter[]; - documentation: SymbolDisplayPart[]; - } - /** - * Represents a set of signature help items, and the preferred item that should be selected. - */ - interface SignatureHelpItems { - items: SignatureHelpItem[]; - applicableSpan: TextSpan; - selectedItemIndex: number; - argumentIndex: number; - argumentCount: number; - } - interface CompletionInfo { - isMemberCompletion: boolean; - isNewIdentifierLocation: boolean; - entries: CompletionEntry[]; - } - interface CompletionEntry { - name: string; - kind: string; - kindModifiers: string; - sortText: string; - } - interface CompletionEntryDetails { - name: string; - kind: string; - kindModifiers: string; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface OutliningSpan { - /** The span of the document to actually collapse. */ - textSpan: TextSpan; - /** The span of the document to display when the user hovers over the collapsed span. */ - hintSpan: TextSpan; - /** The text to display in the editor for the collapsed region. */ - bannerText: string; - /** - * Whether or not this region should be automatically collapsed when - * the 'Collapse to Definitions' command is invoked. - */ - autoCollapse: boolean; - } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - const enum OutputFileType { - JavaScript = 0, - SourceMap = 1, - Declaration = 2, - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } - const enum EndOfLineState { - None = 0, - InMultiLineCommentTrivia = 1, - InSingleQuoteStringLiteral = 2, - InDoubleQuoteStringLiteral = 3, - InTemplateHeadOrNoSubstitutionTemplate = 4, - InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, - } - enum TokenClass { - Punctuation = 0, - Keyword = 1, - Operator = 2, - Comment = 3, - Whitespace = 4, - Identifier = 5, - NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8, - } - interface ClassificationResult { - finalLexState: EndOfLineState; - entries: ClassificationInfo[]; - } - interface ClassificationInfo { - length: number; - classification: TokenClass; - } - interface Classifier { - /** - * Gives lexical classifications of tokens on a line without any syntactic context. - * For instance, a token consisting of the text 'string' can be either an identifier - * named 'string' or the keyword 'string', however, because this classifier is not aware, - * it relies on certain heuristics to give acceptable results. For classifications where - * speed trumps accuracy, this function is preferable; however, for true accuracy, the - * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the - * lexical, syntactic, and semantic classifiers may issue the best user experience. - * - * @param text The text of a line to classify. - * @param lexState The state of the lexical classifier at the end of the previous line. - * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. - * If there is no syntactic classifier (syntacticClassifierAbsent=true), - * certain heuristics may be used in its place; however, if there is a - * syntactic classifier (syntacticClassifierAbsent=false), certain - * classifications which may be incorrectly categorized will be given - * back as Identifiers in order to allow the syntactic classifier to - * subsume the classification. - * @deprecated Use getLexicalClassifications instead. - */ - getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; - getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; - } - /** - * The document registry represents a store of SourceFile objects that can be shared between - * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) - * of files in the context. - * SourceFile objects account for most of the memory usage by the language service. Sharing - * the same DocumentRegistry instance between different instances of LanguageService allow - * for more efficient memory utilization since all projects will share at least the library - * file (lib.d.ts). - * - * A more advanced use of the document registry is to serialize sourceFile objects to disk - * and re-hydrate them when needed. - * - * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it - * to all subsequent createLanguageService calls. - */ - interface DocumentRegistry { - /** - * Request a stored SourceFile with a given fileName and compilationSettings. - * The first call to acquire will call createLanguageServiceSourceFile to generate - * the SourceFile if was not found in the registry. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @parm scriptSnapshot Text of the file. Only used if the file was not found - * in the registry and a new one was created. - * @parm version Current version of the file. Only used if the file was not found - * in the registry and a new one was created. - */ - acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Request an updated version of an already existing SourceFile with a given fileName - * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile - * to get an updated SourceFile. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @param scriptSnapshot Text of the file. - * @param version Current version of the file. - */ - updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Informs the DocumentRegistry that a file is not needed any longer. - * - * Note: It is not allowed to call release on a SourceFile that was not acquired from - * this registry originally. - * - * @param fileName The name of the file to be released - * @param compilationSettings The compilation settings used to acquire the file - */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; - reportStats(): string; - } - module ScriptElementKind { - const unknown: string; - const warning: string; - const keyword: string; - const scriptElement: string; - const moduleElement: string; - const classElement: string; - const localClassElement: string; - const interfaceElement: string; - const typeElement: string; - const enumElement: string; - const variableElement: string; - const localVariableElement: string; - const functionElement: string; - const localFunctionElement: string; - const memberFunctionElement: string; - const memberGetAccessorElement: string; - const memberSetAccessorElement: string; - const memberVariableElement: string; - const constructorImplementationElement: string; - const callSignatureElement: string; - const indexSignatureElement: string; - const constructSignatureElement: string; - const parameterElement: string; - const typeParameterElement: string; - const primitiveType: string; - const label: string; - const alias: string; - const constElement: string; - const letElement: string; - } - module ScriptElementKindModifier { - const none: string; - const publicMemberModifier: string; - const privateMemberModifier: string; - const protectedMemberModifier: string; - const exportedModifier: string; - const ambientModifier: string; - const staticModifier: string; - const abstractModifier: string; - } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - } - const enum ClassificationType { - comment = 1, - identifier = 2, - keyword = 3, - numericLiteral = 4, - operator = 5, - stringLiteral = 6, - regularExpressionLiteral = 7, - whiteSpace = 8, - text = 9, - punctuation = 10, - className = 11, - enumName = 12, - interfaceName = 13, - moduleName = 14, - typeParameterName = 15, - typeAliasName = 16, - parameterName = 17, - docCommentTagName = 18, - } - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; - function getDefaultCompilerOptions(): CompilerOptions; - interface TranspileOptions { - compilerOptions?: CompilerOptions; - fileName?: string; - reportDiagnostics?: boolean; - moduleName?: string; - renamedDependencies?: Map; - } - interface TranspileOutput { - outputText: string; - diagnostics?: Diagnostic[]; - sourceMapText?: string; - } - function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; - function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; - function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; - function createClassifier(): Classifier; - /** - * Get the path of the default library files (lib.d.ts) as distributed with the typescript - * node package. - * The functionality is not supported if the ts module is consumed outside of a node module. - */ - function getDefaultLibFilePath(options: CompilerOptions): string; -} +// Type definitions for TypeScript API v0.4.0 +// Project: http://www.typescriptlang.org/ +// Definitions by: Microsoft TypeScript +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +declare namespace ts { + interface Map { + [index: string]: T; + } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + clear(): void; + } + interface TextRange { + pos: number; + end: number; + } + const enum SyntaxKind { + Unknown = 0, + EndOfFileToken = 1, + SingleLineCommentTrivia = 2, + MultiLineCommentTrivia = 3, + NewLineTrivia = 4, + WhitespaceTrivia = 5, + ShebangTrivia = 6, + ConflictMarkerTrivia = 7, + NumericLiteral = 8, + StringLiteral = 9, + RegularExpressionLiteral = 10, + NoSubstitutionTemplateLiteral = 11, + TemplateHead = 12, + TemplateMiddle = 13, + TemplateTail = 14, + OpenBraceToken = 15, + CloseBraceToken = 16, + OpenParenToken = 17, + CloseParenToken = 18, + OpenBracketToken = 19, + CloseBracketToken = 20, + DotToken = 21, + DotDotDotToken = 22, + SemicolonToken = 23, + CommaToken = 24, + LessThanToken = 25, + LessThanSlashToken = 26, + GreaterThanToken = 27, + LessThanEqualsToken = 28, + GreaterThanEqualsToken = 29, + EqualsEqualsToken = 30, + ExclamationEqualsToken = 31, + EqualsEqualsEqualsToken = 32, + ExclamationEqualsEqualsToken = 33, + EqualsGreaterThanToken = 34, + PlusToken = 35, + MinusToken = 36, + AsteriskToken = 37, + SlashToken = 38, + PercentToken = 39, + PlusPlusToken = 40, + MinusMinusToken = 41, + LessThanLessThanToken = 42, + GreaterThanGreaterThanToken = 43, + GreaterThanGreaterThanGreaterThanToken = 44, + AmpersandToken = 45, + BarToken = 46, + CaretToken = 47, + ExclamationToken = 48, + TildeToken = 49, + AmpersandAmpersandToken = 50, + BarBarToken = 51, + QuestionToken = 52, + ColonToken = 53, + AtToken = 54, + EqualsToken = 55, + PlusEqualsToken = 56, + MinusEqualsToken = 57, + AsteriskEqualsToken = 58, + SlashEqualsToken = 59, + PercentEqualsToken = 60, + LessThanLessThanEqualsToken = 61, + GreaterThanGreaterThanEqualsToken = 62, + GreaterThanGreaterThanGreaterThanEqualsToken = 63, + AmpersandEqualsToken = 64, + BarEqualsToken = 65, + CaretEqualsToken = 66, + Identifier = 67, + BreakKeyword = 68, + CaseKeyword = 69, + CatchKeyword = 70, + ClassKeyword = 71, + ConstKeyword = 72, + ContinueKeyword = 73, + DebuggerKeyword = 74, + DefaultKeyword = 75, + DeleteKeyword = 76, + DoKeyword = 77, + ElseKeyword = 78, + EnumKeyword = 79, + ExportKeyword = 80, + ExtendsKeyword = 81, + FalseKeyword = 82, + FinallyKeyword = 83, + ForKeyword = 84, + FunctionKeyword = 85, + IfKeyword = 86, + ImportKeyword = 87, + InKeyword = 88, + InstanceOfKeyword = 89, + NewKeyword = 90, + NullKeyword = 91, + ReturnKeyword = 92, + SuperKeyword = 93, + SwitchKeyword = 94, + ThisKeyword = 95, + ThrowKeyword = 96, + TrueKeyword = 97, + TryKeyword = 98, + TypeOfKeyword = 99, + VarKeyword = 100, + VoidKeyword = 101, + WhileKeyword = 102, + WithKeyword = 103, + ImplementsKeyword = 104, + InterfaceKeyword = 105, + LetKeyword = 106, + PackageKeyword = 107, + PrivateKeyword = 108, + ProtectedKeyword = 109, + PublicKeyword = 110, + StaticKeyword = 111, + YieldKeyword = 112, + AbstractKeyword = 113, + AsKeyword = 114, + AnyKeyword = 115, + AsyncKeyword = 116, + AwaitKeyword = 117, + BooleanKeyword = 118, + ConstructorKeyword = 119, + DeclareKeyword = 120, + GetKeyword = 121, + IsKeyword = 122, + ModuleKeyword = 123, + NamespaceKeyword = 124, + RequireKeyword = 125, + NumberKeyword = 126, + SetKeyword = 127, + StringKeyword = 128, + SymbolKeyword = 129, + TypeKeyword = 130, + FromKeyword = 131, + OfKeyword = 132, + QualifiedName = 133, + ComputedPropertyName = 134, + TypeParameter = 135, + Parameter = 136, + Decorator = 137, + PropertySignature = 138, + PropertyDeclaration = 139, + MethodSignature = 140, + MethodDeclaration = 141, + Constructor = 142, + GetAccessor = 143, + SetAccessor = 144, + CallSignature = 145, + ConstructSignature = 146, + IndexSignature = 147, + TypePredicate = 148, + TypeReference = 149, + FunctionType = 150, + ConstructorType = 151, + TypeQuery = 152, + TypeLiteral = 153, + ArrayType = 154, + TupleType = 155, + UnionType = 156, + IntersectionType = 157, + ParenthesizedType = 158, + ObjectBindingPattern = 159, + ArrayBindingPattern = 160, + BindingElement = 161, + ArrayLiteralExpression = 162, + ObjectLiteralExpression = 163, + PropertyAccessExpression = 164, + ElementAccessExpression = 165, + CallExpression = 166, + NewExpression = 167, + TaggedTemplateExpression = 168, + TypeAssertionExpression = 169, + ParenthesizedExpression = 170, + FunctionExpression = 171, + ArrowFunction = 172, + DeleteExpression = 173, + TypeOfExpression = 174, + VoidExpression = 175, + AwaitExpression = 176, + PrefixUnaryExpression = 177, + PostfixUnaryExpression = 178, + BinaryExpression = 179, + ConditionalExpression = 180, + TemplateExpression = 181, + YieldExpression = 182, + SpreadElementExpression = 183, + ClassExpression = 184, + OmittedExpression = 185, + ExpressionWithTypeArguments = 186, + AsExpression = 187, + TemplateSpan = 188, + SemicolonClassElement = 189, + Block = 190, + VariableStatement = 191, + EmptyStatement = 192, + ExpressionStatement = 193, + IfStatement = 194, + DoStatement = 195, + WhileStatement = 196, + ForStatement = 197, + ForInStatement = 198, + ForOfStatement = 199, + ContinueStatement = 200, + BreakStatement = 201, + ReturnStatement = 202, + WithStatement = 203, + SwitchStatement = 204, + LabeledStatement = 205, + ThrowStatement = 206, + TryStatement = 207, + DebuggerStatement = 208, + VariableDeclaration = 209, + VariableDeclarationList = 210, + FunctionDeclaration = 211, + ClassDeclaration = 212, + InterfaceDeclaration = 213, + TypeAliasDeclaration = 214, + EnumDeclaration = 215, + ModuleDeclaration = 216, + ModuleBlock = 217, + CaseBlock = 218, + ImportEqualsDeclaration = 219, + ImportDeclaration = 220, + ImportClause = 221, + NamespaceImport = 222, + NamedImports = 223, + ImportSpecifier = 224, + ExportAssignment = 225, + ExportDeclaration = 226, + NamedExports = 227, + ExportSpecifier = 228, + MissingDeclaration = 229, + ExternalModuleReference = 230, + JsxElement = 231, + JsxSelfClosingElement = 232, + JsxOpeningElement = 233, + JsxText = 234, + JsxClosingElement = 235, + JsxAttribute = 236, + JsxSpreadAttribute = 237, + JsxExpression = 238, + CaseClause = 239, + DefaultClause = 240, + HeritageClause = 241, + CatchClause = 242, + PropertyAssignment = 243, + ShorthandPropertyAssignment = 244, + EnumMember = 245, + SourceFile = 246, + JSDocTypeExpression = 247, + JSDocAllType = 248, + JSDocUnknownType = 249, + JSDocArrayType = 250, + JSDocUnionType = 251, + JSDocTupleType = 252, + JSDocNullableType = 253, + JSDocNonNullableType = 254, + JSDocRecordType = 255, + JSDocRecordMember = 256, + JSDocTypeReference = 257, + JSDocOptionalType = 258, + JSDocFunctionType = 259, + JSDocVariadicType = 260, + JSDocConstructorType = 261, + JSDocThisType = 262, + JSDocComment = 263, + JSDocTag = 264, + JSDocParameterTag = 265, + JSDocReturnTag = 266, + JSDocTypeTag = 267, + JSDocTemplateTag = 268, + SyntaxList = 269, + Count = 270, + FirstAssignment = 55, + LastAssignment = 66, + FirstReservedWord = 68, + LastReservedWord = 103, + FirstKeyword = 68, + LastKeyword = 132, + FirstFutureReservedWord = 104, + LastFutureReservedWord = 112, + FirstTypeNode = 149, + LastTypeNode = 158, + FirstPunctuation = 15, + LastPunctuation = 66, + FirstToken = 0, + LastToken = 132, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, + LastLiteralToken = 11, + FirstTemplateToken = 11, + LastTemplateToken = 14, + FirstBinaryOperator = 25, + LastBinaryOperator = 66, + FirstNode = 133, + } + const enum NodeFlags { + Export = 1, + Ambient = 2, + Public = 16, + Private = 32, + Protected = 64, + Static = 128, + Abstract = 256, + Async = 512, + Default = 1024, + MultiLine = 2048, + Synthetic = 4096, + DeclarationFile = 8192, + Let = 16384, + Const = 32768, + OctalLiteral = 65536, + Namespace = 131072, + ExportContext = 262144, + Modifier = 2035, + AccessibilityModifier = 112, + BlockScoped = 49152, + } + const enum JsxFlags { + None = 0, + IntrinsicNamedElement = 1, + IntrinsicIndexedElement = 2, + ClassElement = 4, + UnknownElement = 8, + IntrinsicElement = 3, + } + interface Node extends TextRange { + kind: SyntaxKind; + flags: NodeFlags; + decorators?: NodeArray; + modifiers?: ModifiersArray; + parent?: Node; + } + interface NodeArray extends Array, TextRange { + hasTrailingComma?: boolean; + } + interface ModifiersArray extends NodeArray { + flags: number; + } + interface Identifier extends PrimaryExpression { + text: string; + originalKeywordKind?: SyntaxKind; + } + interface QualifiedName extends Node { + left: EntityName; + right: Identifier; + } + type EntityName = Identifier | QualifiedName; + type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + interface Declaration extends Node { + _declarationBrand: any; + name?: DeclarationName; + } + interface ComputedPropertyName extends Node { + expression: Expression; + } + interface Decorator extends Node { + expression: LeftHandSideExpression; + } + interface TypeParameterDeclaration extends Declaration { + name: Identifier; + constraint?: TypeNode; + expression?: Expression; + } + interface SignatureDeclaration extends Declaration { + typeParameters?: NodeArray; + parameters: NodeArray; + type?: TypeNode; + } + interface VariableDeclaration extends Declaration { + parent?: VariableDeclarationList; + name: Identifier | BindingPattern; + type?: TypeNode; + initializer?: Expression; + } + interface VariableDeclarationList extends Node { + declarations: NodeArray; + } + interface ParameterDeclaration extends Declaration { + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingElement extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + initializer?: Expression; + } + interface PropertyDeclaration extends Declaration, ClassElement { + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface ObjectLiteralElement extends Declaration { + _objectLiteralBrandBrand: any; + } + interface PropertyAssignment extends ObjectLiteralElement { + _propertyAssignmentBrand: any; + name: DeclarationName; + questionToken?: Node; + initializer: Expression; + } + interface ShorthandPropertyAssignment extends ObjectLiteralElement { + name: Identifier; + questionToken?: Node; + } + interface VariableLikeDeclaration extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingPattern extends Node { + elements: NodeArray; + } + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclaration. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ + interface FunctionLikeDeclaration extends SignatureDeclaration { + _functionLikeDeclarationBrand: any; + asteriskToken?: Node; + questionToken?: Node; + body?: Block | Expression; + } + interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + name?: Identifier; + body?: Block; + } + interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + body?: Block; + } + interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + body?: Block; + } + interface SemicolonClassElement extends ClassElement { + _semicolonClassElementBrand: any; + } + interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + _accessorDeclarationBrand: any; + body: Block; + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + _indexSignatureDeclarationBrand: any; + } + interface TypeNode extends Node { + _typeNodeBrand: any; + } + interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { + _functionOrConstructorTypeNodeBrand: any; + } + interface TypeReferenceNode extends TypeNode { + typeName: EntityName; + typeArguments?: NodeArray; + } + interface TypePredicateNode extends TypeNode { + parameterName: Identifier; + type: TypeNode; + } + interface TypeQueryNode extends TypeNode { + exprName: EntityName; + } + interface TypeLiteralNode extends TypeNode, Declaration { + members: NodeArray; + } + interface ArrayTypeNode extends TypeNode { + elementType: TypeNode; + } + interface TupleTypeNode extends TypeNode { + elementTypes: NodeArray; + } + interface UnionOrIntersectionTypeNode extends TypeNode { + types: NodeArray; + } + interface UnionTypeNode extends UnionOrIntersectionTypeNode { + } + interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + } + interface ParenthesizedTypeNode extends TypeNode { + type: TypeNode; + } + interface StringLiteral extends LiteralExpression, TypeNode { + _stringLiteralBrand: any; + } + interface Expression extends Node { + _expressionBrand: any; + contextualType?: Type; + } + interface UnaryExpression extends Expression { + _unaryExpressionBrand: any; + } + interface PrefixUnaryExpression extends UnaryExpression { + operator: SyntaxKind; + operand: UnaryExpression; + } + interface PostfixUnaryExpression extends PostfixExpression { + operand: LeftHandSideExpression; + operator: SyntaxKind; + } + interface PostfixExpression extends UnaryExpression { + _postfixExpressionBrand: any; + } + interface LeftHandSideExpression extends PostfixExpression { + _leftHandSideExpressionBrand: any; + } + interface MemberExpression extends LeftHandSideExpression { + _memberExpressionBrand: any; + } + interface PrimaryExpression extends MemberExpression { + _primaryExpressionBrand: any; + } + interface DeleteExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface TypeOfExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface VoidExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface AwaitExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface YieldExpression extends Expression { + asteriskToken?: Node; + expression?: Expression; + } + interface BinaryExpression extends Expression { + left: Expression; + operatorToken: Node; + right: Expression; + } + interface ConditionalExpression extends Expression { + condition: Expression; + questionToken: Node; + whenTrue: Expression; + colonToken: Node; + whenFalse: Expression; + } + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + name?: Identifier; + body: Block | Expression; + } + interface ArrowFunction extends Expression, FunctionLikeDeclaration { + equalsGreaterThanToken: Node; + } + interface LiteralExpression extends PrimaryExpression { + text: string; + isUnterminated?: boolean; + hasExtendedUnicodeEscape?: boolean; + } + interface TemplateExpression extends PrimaryExpression { + head: LiteralExpression; + templateSpans: NodeArray; + } + interface TemplateSpan extends Node { + expression: Expression; + literal: LiteralExpression; + } + interface ParenthesizedExpression extends PrimaryExpression { + expression: Expression; + } + interface ArrayLiteralExpression extends PrimaryExpression { + elements: NodeArray; + } + interface SpreadElementExpression extends Expression { + expression: Expression; + } + interface ObjectLiteralExpression extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface PropertyAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + dotToken: Node; + name: Identifier; + } + interface ElementAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + argumentExpression?: Expression; + } + interface CallExpression extends LeftHandSideExpression { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; + } + interface ExpressionWithTypeArguments extends TypeNode { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + } + interface NewExpression extends CallExpression, PrimaryExpression { + } + interface TaggedTemplateExpression extends MemberExpression { + tag: LeftHandSideExpression; + template: LiteralExpression | TemplateExpression; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; + interface AsExpression extends Expression { + expression: Expression; + type: TypeNode; + } + interface TypeAssertion extends UnaryExpression { + type: TypeNode; + expression: UnaryExpression; + } + type AssertionExpression = TypeAssertion | AsExpression; + interface JsxElement extends PrimaryExpression { + openingElement: JsxOpeningElement; + children: NodeArray; + closingElement: JsxClosingElement; + } + interface JsxOpeningElement extends Expression { + _openingElementBrand?: any; + tagName: EntityName; + attributes: NodeArray; + } + interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { + _selfClosingElementBrand?: any; + } + type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + interface JsxAttribute extends Node { + name: Identifier; + initializer?: Expression; + } + interface JsxSpreadAttribute extends Node { + expression: Expression; + } + interface JsxClosingElement extends Node { + tagName: EntityName; + } + interface JsxExpression extends Expression { + expression?: Expression; + } + interface JsxText extends Node { + _jsxTextExpressionBrand: any; + } + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; + interface Statement extends Node { + _statementBrand: any; + } + interface Block extends Statement { + statements: NodeArray; + } + interface VariableStatement extends Statement { + declarationList: VariableDeclarationList; + } + interface ExpressionStatement extends Statement { + expression: Expression; + } + interface IfStatement extends Statement { + expression: Expression; + thenStatement: Statement; + elseStatement?: Statement; + } + interface IterationStatement extends Statement { + statement: Statement; + } + interface DoStatement extends IterationStatement { + expression: Expression; + } + interface WhileStatement extends IterationStatement { + expression: Expression; + } + interface ForStatement extends IterationStatement { + initializer?: VariableDeclarationList | Expression; + condition?: Expression; + incrementor?: Expression; + } + interface ForInStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface ForOfStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface BreakOrContinueStatement extends Statement { + label?: Identifier; + } + interface ReturnStatement extends Statement { + expression?: Expression; + } + interface WithStatement extends Statement { + expression: Expression; + statement: Statement; + } + interface SwitchStatement extends Statement { + expression: Expression; + caseBlock: CaseBlock; + } + interface CaseBlock extends Node { + clauses: NodeArray; + } + interface CaseClause extends Node { + expression?: Expression; + statements: NodeArray; + } + interface DefaultClause extends Node { + statements: NodeArray; + } + type CaseOrDefaultClause = CaseClause | DefaultClause; + interface LabeledStatement extends Statement { + label: Identifier; + statement: Statement; + } + interface ThrowStatement extends Statement { + expression: Expression; + } + interface TryStatement extends Statement { + tryBlock: Block; + catchClause?: CatchClause; + finallyBlock?: Block; + } + interface CatchClause extends Node { + variableDeclaration: VariableDeclaration; + block: Block; + } + interface ClassLikeDeclaration extends Declaration { + name?: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface ClassDeclaration extends ClassLikeDeclaration, Statement { + } + interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + } + interface ClassElement extends Declaration { + _classElementBrand: any; + } + interface InterfaceDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface HeritageClause extends Node { + token: SyntaxKind; + types?: NodeArray; + } + interface TypeAliasDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + type: TypeNode; + } + interface EnumMember extends Declaration { + name: DeclarationName; + initializer?: Expression; + } + interface EnumDeclaration extends Declaration, Statement { + name: Identifier; + members: NodeArray; + } + interface ModuleDeclaration extends Declaration, Statement { + name: Identifier | LiteralExpression; + body: ModuleBlock | ModuleDeclaration; + } + interface ModuleBlock extends Node, Statement { + statements: NodeArray; + } + interface ImportEqualsDeclaration extends Declaration, Statement { + name: Identifier; + moduleReference: EntityName | ExternalModuleReference; + } + interface ExternalModuleReference extends Node { + expression?: Expression; + } + interface ImportDeclaration extends Statement { + importClause?: ImportClause; + moduleSpecifier: Expression; + } + interface ImportClause extends Declaration { + name?: Identifier; + namedBindings?: NamespaceImport | NamedImports; + } + interface NamespaceImport extends Declaration { + name: Identifier; + } + interface ExportDeclaration extends Declaration, Statement { + exportClause?: NamedExports; + moduleSpecifier?: Expression; + } + interface NamedImportsOrExports extends Node { + elements: NodeArray; + } + type NamedImports = NamedImportsOrExports; + type NamedExports = NamedImportsOrExports; + interface ImportOrExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportSpecifier = ImportOrExportSpecifier; + type ExportSpecifier = ImportOrExportSpecifier; + interface ExportAssignment extends Declaration, Statement { + isExportEquals?: boolean; + expression: Expression; + } + interface FileReference extends TextRange { + fileName: string; + } + interface CommentRange extends TextRange { + hasTrailingNewLine?: boolean; + kind: SyntaxKind; + } + interface JSDocTypeExpression extends Node { + type: JSDocType; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + _JSDocAllTypeBrand: any; + } + interface JSDocUnknownType extends JSDocType { + _JSDocUnknownTypeBrand: any; + } + interface JSDocArrayType extends JSDocType { + elementType: JSDocType; + } + interface JSDocUnionType extends JSDocType { + types: NodeArray; + } + interface JSDocTupleType extends JSDocType { + types: NodeArray; + } + interface JSDocNonNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordType extends JSDocType, TypeLiteralNode { + members: NodeArray; + } + interface JSDocTypeReference extends JSDocType { + name: EntityName; + typeArguments: NodeArray; + } + interface JSDocOptionalType extends JSDocType { + type: JSDocType; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + parameters: NodeArray; + type: JSDocType; + } + interface JSDocVariadicType extends JSDocType { + type: JSDocType; + } + interface JSDocConstructorType extends JSDocType { + type: JSDocType; + } + interface JSDocThisType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordMember extends PropertyDeclaration { + name: Identifier | LiteralExpression; + type?: JSDocType; + } + interface JSDocComment extends Node { + tags: NodeArray; + } + interface JSDocTag extends Node { + atToken: Node; + tagName: Identifier; + } + interface JSDocTemplateTag extends JSDocTag { + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocParameterTag extends JSDocTag { + preParameterName?: Identifier; + typeExpression?: JSDocTypeExpression; + postParameterName?: Identifier; + isBracketed: boolean; + } + interface SourceFile extends Declaration { + statements: NodeArray; + endOfFileToken: Node; + fileName: string; + text: string; + amdDependencies: { + path: string; + name: string; + }[]; + moduleName: string; + referencedFiles: FileReference[]; + languageVariant: LanguageVariant; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + hasNoDefaultLib: boolean; + languageVersion: ScriptTarget; + } + interface ScriptReferenceHost { + getCompilerOptions(): CompilerOptions; + getSourceFile(fileName: string): SourceFile; + getCurrentDirectory(): string; + } + interface ParseConfigHost extends ModuleResolutionHost { + readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + } + interface WriteFileCallback { + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; + } + class OperationCanceledException { + } + interface CancellationToken { + isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ + throwIfCancellationRequested(): void; + } + interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ + getRootFileNames(): string[]; + /** + * Get a list of files in the program + */ + getSourceFiles(): SourceFile[]; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + /** + * Gets a type checker that can be used to semantically analyze source fils in the program. + */ + getTypeChecker(): TypeChecker; + } + interface SourceMapSpan { + /** Line number in the .js file. */ + emittedLine: number; + /** Column number in the .js file. */ + emittedColumn: number; + /** Line number in the .ts file. */ + sourceLine: number; + /** Column number in the .ts file. */ + sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ + nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ + sourceIndex: number; + } + interface SourceMapData { + sourceMapFilePath: string; + jsSourceMappingURL: string; + sourceMapFile: string; + sourceMapSourceRoot: string; + sourceMapSources: string[]; + sourceMapSourcesContent?: string[]; + inputSourceFileNames: string[]; + sourceMapNames?: string[]; + sourceMapMappings: string; + sourceMapDecodedMappings: SourceMapSpan[]; + } + /** Return code used by getEmitOutput function to indicate status of the function */ + enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2, + } + interface EmitResult { + emitSkipped: boolean; + diagnostics: Diagnostic[]; + } + interface TypeChecker { + getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; + getDeclaredTypeOfSymbol(symbol: Symbol): Type; + getPropertiesOfType(type: Type): Symbol[]; + getPropertyOfType(type: Type, propertyName: string): Symbol; + getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; + getIndexTypeOfType(type: Type, kind: IndexKind): Type; + getBaseTypes(type: InterfaceType): ObjectType[]; + getReturnTypeOfSignature(signature: Signature): Type; + getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; + getSymbolAtLocation(node: Node): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol; + getTypeAtLocation(node: Node): Type; + typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + getSymbolDisplayBuilder(): SymbolDisplayBuilder; + getFullyQualifiedName(symbol: Symbol): string; + getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): Symbol[]; + getContextualType(node: Expression): Type; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + isUndefinedSymbol(symbol: Symbol): boolean; + isArgumentsSymbol(symbol: Symbol): boolean; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(moduleSymbol: Symbol): Symbol[]; + getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; + getJsxIntrinsicTagNames(): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; + } + interface SymbolDisplayBuilder { + buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; + buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + } + interface SymbolWriter { + writeKeyword(text: string): void; + writeOperator(text: string): void; + writePunctuation(text: string): void; + writeSpace(text: string): void; + writeStringLiteral(text: string): void; + writeParameter(text: string): void; + writeSymbol(text: string, symbol: Symbol): void; + writeLine(): void; + increaseIndent(): void; + decreaseIndent(): void; + clear(): void; + trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + } + const enum TypeFormatFlags { + None = 0, + WriteArrayAsGenericType = 1, + UseTypeOfFunction = 2, + NoTruncation = 4, + WriteArrowStyleSignature = 8, + WriteOwnNameForAnyLike = 16, + WriteTypeArgumentsOfSignature = 32, + InElementType = 64, + UseFullyQualifiedType = 128, + } + const enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + } + interface TypePredicate { + parameterName: string; + parameterIndex: number; + type: Type; + } + const enum SymbolFlags { + None = 0, + FunctionScopedVariable = 1, + BlockScopedVariable = 2, + Property = 4, + EnumMember = 8, + Function = 16, + Class = 32, + Interface = 64, + ConstEnum = 128, + RegularEnum = 256, + ValueModule = 512, + NamespaceModule = 1024, + TypeLiteral = 2048, + ObjectLiteral = 4096, + Method = 8192, + Constructor = 16384, + GetAccessor = 32768, + SetAccessor = 65536, + Signature = 131072, + TypeParameter = 262144, + TypeAlias = 524288, + ExportValue = 1048576, + ExportType = 2097152, + ExportNamespace = 4194304, + Alias = 8388608, + Instantiated = 16777216, + Merged = 33554432, + Transient = 67108864, + Prototype = 134217728, + SyntheticProperty = 268435456, + Optional = 536870912, + ExportStar = 1073741824, + Enum = 384, + Variable = 3, + Value = 107455, + Type = 793056, + Namespace = 1536, + Module = 1536, + Accessor = 98304, + FunctionScopedVariableExcludes = 107454, + BlockScopedVariableExcludes = 107455, + ParameterExcludes = 107455, + PropertyExcludes = 107455, + EnumMemberExcludes = 107455, + FunctionExcludes = 106927, + ClassExcludes = 899519, + InterfaceExcludes = 792960, + RegularEnumExcludes = 899327, + ConstEnumExcludes = 899967, + ValueModuleExcludes = 106639, + NamespaceModuleExcludes = 0, + MethodExcludes = 99263, + GetAccessorExcludes = 41919, + SetAccessorExcludes = 74687, + TypeParameterExcludes = 530912, + TypeAliasExcludes = 793056, + AliasExcludes = 8388608, + ModuleMember = 8914931, + ExportHasLocal = 944, + HasExports = 1952, + HasMembers = 6240, + BlockScoped = 418, + PropertyOrAccessor = 98308, + Export = 7340032, + } + interface Symbol { + flags: SymbolFlags; + name: string; + declarations?: Declaration[]; + valueDeclaration?: Declaration; + members?: SymbolTable; + exports?: SymbolTable; + } + interface SymbolTable { + [index: string]: Symbol; + } + const enum TypeFlags { + Any = 1, + String = 2, + Number = 4, + Boolean = 8, + Void = 16, + Undefined = 32, + Null = 64, + Enum = 128, + StringLiteral = 256, + TypeParameter = 512, + Class = 1024, + Interface = 2048, + Reference = 4096, + Tuple = 8192, + Union = 16384, + Intersection = 32768, + Anonymous = 65536, + Instantiated = 131072, + ObjectLiteral = 524288, + ESSymbol = 16777216, + StringLike = 258, + NumberLike = 132, + ObjectType = 80896, + UnionOrIntersection = 49152, + StructuredType = 130048, + } + interface Type { + flags: TypeFlags; + symbol?: Symbol; + } + interface StringLiteralType extends Type { + text: string; + } + interface ObjectType extends Type { + } + interface InterfaceType extends ObjectType { + typeParameters: TypeParameter[]; + outerTypeParameters: TypeParameter[]; + localTypeParameters: TypeParameter[]; + } + interface InterfaceTypeWithDeclaredMembers extends InterfaceType { + declaredProperties: Symbol[]; + declaredCallSignatures: Signature[]; + declaredConstructSignatures: Signature[]; + declaredStringIndexType: Type; + declaredNumberIndexType: Type; + } + interface TypeReference extends ObjectType { + target: GenericType; + typeArguments: Type[]; + } + interface GenericType extends InterfaceType, TypeReference { + } + interface TupleType extends ObjectType { + elementTypes: Type[]; + baseArrayType: TypeReference; + } + interface UnionOrIntersectionType extends Type { + types: Type[]; + } + interface UnionType extends UnionOrIntersectionType { + } + interface IntersectionType extends UnionOrIntersectionType { + } + interface TypeParameter extends Type { + constraint: Type; + } + const enum SignatureKind { + Call = 0, + Construct = 1, + } + interface Signature { + declaration: SignatureDeclaration; + typeParameters: TypeParameter[]; + parameters: Symbol[]; + typePredicate?: TypePredicate; + } + const enum IndexKind { + String = 0, + Number = 1, + } + interface DiagnosticMessage { + key: string; + category: DiagnosticCategory; + code: number; + } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ + interface DiagnosticMessageChain { + messageText: string; + category: DiagnosticCategory; + code: number; + next?: DiagnosticMessageChain; + } + interface Diagnostic { + file: SourceFile; + start: number; + length: number; + messageText: string | DiagnosticMessageChain; + category: DiagnosticCategory; + code: number; + } + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Message = 2, + } + const enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2, + } + interface CompilerOptions { + allowNonTsExtensions?: boolean; + charset?: string; + declaration?: boolean; + diagnostics?: boolean; + emitBOM?: boolean; + help?: boolean; + init?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + jsx?: JsxEmit; + listFiles?: boolean; + locale?: string; + mapRoot?: string; + module?: ModuleKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noImplicitAny?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outFile?: string; + outDir?: string; + preserveConstEnums?: boolean; + project?: string; + removeComments?: boolean; + rootDir?: string; + sourceMap?: boolean; + sourceRoot?: string; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + version?: boolean; + watch?: boolean; + isolatedModules?: boolean; + experimentalDecorators?: boolean; + experimentalAsyncFunctions?: boolean; + emitDecoratorMetadata?: boolean; + moduleResolution?: ModuleResolutionKind; + [option: string]: string | number | boolean; + } + const enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + } + const enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + } + const enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } + interface LineAndCharacter { + line: number; + character: number; + } + const enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES6 = 2, + Latest = 2, + } + const enum LanguageVariant { + Standard = 0, + JSX = 1, + } + interface ParsedCommandLine { + options: CompilerOptions; + fileNames: string[]; + errors: Diagnostic[]; + } + interface ModuleResolutionHost { + fileExists(fileName: string): boolean; + readFile(fileName: string): string; + } + interface ResolvedModule { + resolvedFileName: string; + isExternalLibraryImport?: boolean; + } + interface ResolvedModuleWithFailedLookupLocations { + resolvedModule: ResolvedModule; + failedLookupLocations: string[]; + } + interface CompilerHost extends ModuleResolutionHost { + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getCancellationToken?(): CancellationToken; + getDefaultLibFileName(options: CompilerOptions): string; + writeFile: WriteFileCallback; + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } +} +declare namespace ts { + interface System { + args: string[]; + newLine: string; + useCaseSensitiveFileNames: boolean; + write(s: string): void; + readFile(path: string, encoding?: string): string; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + watchFile?(path: string, callback: (path: string) => void): FileWatcher; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getExecutingFilePath(): string; + getCurrentDirectory(): string; + readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + getMemoryUsage?(): number; + exit(exitCode?: number): void; + } + interface FileWatcher { + close(): void; + } + var sys: System; +} +declare namespace ts { + interface ErrorCallback { + (message: DiagnosticMessage, length: number): void; + } + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scanJsxIdentifier(): SyntaxKind; + reScanJsxToken(): SyntaxKind; + scanJsxToken(): SyntaxKind; + scan(): SyntaxKind; + setText(text: string, start?: number, length?: number): void; + setOnError(onError: ErrorCallback): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setLanguageVariant(variant: LanguageVariant): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + tryScan(callback: () => T): T; + } + function tokenToString(t: SyntaxKind): string; + function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; + function isWhiteSpace(ch: number): boolean; + function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; + function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; + function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; + /** Optionally, get the shebang */ + function getShebang(text: string): string; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +declare namespace ts { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration; +} +declare namespace ts { + function getNodeConstructor(kind: SyntaxKind): new () => Node; + function createNode(kind: SyntaxKind): Node; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + const version: string; + function findConfigFile(searchPath: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; +} +declare namespace ts { + function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileText(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; +} +declare namespace ts { + /** The version of the language service API */ + let servicesVersion: string; + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFile): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node; + getLastToken(sourceFile?: SourceFile): Node; + } + interface Symbol { + getFlags(): SymbolFlags; + getName(): string; + getDeclarations(): Declaration[]; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol; + getApparentProperties(): Symbol[]; + getCallSignatures(): Signature[]; + getConstructSignatures(): Signature[]; + getStringIndexType(): Type; + getNumberIndexType(): Type; + getBaseTypes(): ObjectType[]; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): Type[]; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface SourceFile { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineStarts(): number[]; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ + interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ + getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ + getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + /** Releases all resources held by this script snapshot */ + dispose?(): void; + } + module ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface LanguageServiceHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ + getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; + getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + findReferences(fileName: string, position: number): ReferencedSymbol[]; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + /** @deprecated */ + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getEmitOutput(fileName: string): EmitOutput; + getProgram(): Program; + getSourceFile(fileName: string): SourceFile; + dispose(): void; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: string; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + class TextChange { + span: TextSpan; + newText: string; + } + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + interface RenameLocation { + textSpan: TextSpan; + fileName: string; + } + interface ReferenceEntry { + textSpan: TextSpan; + fileName: string; + isWriteAccess: boolean; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + module HighlightSpanKind { + const none: string; + const definition: string; + const reference: string; + const writtenReference: string; + } + interface HighlightSpan { + fileName?: string; + textSpan: TextSpan; + kind: string; + } + interface NavigateToItem { + name: string; + kind: string; + kindModifiers: string; + matchKind: string; + isCaseSensitive: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: string; + } + interface EditorOptions { + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + } + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + [s: string]: boolean | number | string; + } + interface DefinitionInfo { + fileName: string; + textSpan: TextSpan; + kind: string; + name: string; + containerKind: string; + containerName: string; + } + interface ReferencedSymbol { + definition: DefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21, + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface QuickInfo { + kind: string; + kindModifiers: string; + textSpan: TextSpan; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface CompletionInfo { + isMemberCompletion: boolean; + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + } + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + const enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2, + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } + const enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6, + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + StringLiteral = 7, + RegExpLiteral = 8, + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ + interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @parm scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @parm version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + reportStats(): string; + } + module ScriptElementKind { + const unknown: string; + const warning: string; + const keyword: string; + const scriptElement: string; + const moduleElement: string; + const classElement: string; + const localClassElement: string; + const interfaceElement: string; + const typeElement: string; + const enumElement: string; + const variableElement: string; + const localVariableElement: string; + const functionElement: string; + const localFunctionElement: string; + const memberFunctionElement: string; + const memberGetAccessorElement: string; + const memberSetAccessorElement: string; + const memberVariableElement: string; + const constructorImplementationElement: string; + const callSignatureElement: string; + const indexSignatureElement: string; + const constructSignatureElement: string; + const parameterElement: string; + const typeParameterElement: string; + const primitiveType: string; + const label: string; + const alias: string; + const constElement: string; + const letElement: string; + } + module ScriptElementKindModifier { + const none: string; + const publicMemberModifier: string; + const privateMemberModifier: string; + const protectedMemberModifier: string; + const exportedModifier: string; + const ambientModifier: string; + const staticModifier: string; + const abstractModifier: string; + } + class ClassificationTypeNames { + static comment: string; + static identifier: string; + static keyword: string; + static numericLiteral: string; + static operator: string; + static stringLiteral: string; + static whiteSpace: string; + static text: string; + static punctuation: string; + static className: string; + static enumName: string; + static interfaceName: string; + static moduleName: string; + static typeParameterName: string; + static typeAliasName: string; + static parameterName: string; + static docCommentTagName: string; + } + const enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + } + interface DisplayPartsSymbolWriter extends SymbolWriter { + displayParts(): SymbolDisplayPart[]; + } + function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function getDefaultCompilerOptions(): CompilerOptions; + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: Map; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; + let disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; + function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; + function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; + function createClassifier(): Classifier; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options: CompilerOptions): string; +} diff --git a/typescript/typescript.d.ts b/typescript/typescript.d.ts index 8078c6de2..59330b5dc 100644 --- a/typescript/typescript.d.ts +++ b/typescript/typescript.d.ts @@ -1,2148 +1,2148 @@ -// Type definitions for TypeScript API v0.4.0 -// Project: http://www.typescriptlang.org/ -// Definitions by: Microsoft TypeScript -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -declare module "typescript" { - interface Map { - [index: string]: T; - } - interface FileMap { - get(fileName: string): T; - set(fileName: string, value: T): void; - contains(fileName: string): boolean; - remove(fileName: string): void; - forEachValue(f: (v: T) => void): void; - clear(): void; - } - interface TextRange { - pos: number; - end: number; - } - const enum SyntaxKind { - Unknown = 0, - EndOfFileToken = 1, - SingleLineCommentTrivia = 2, - MultiLineCommentTrivia = 3, - NewLineTrivia = 4, - WhitespaceTrivia = 5, - ShebangTrivia = 6, - ConflictMarkerTrivia = 7, - NumericLiteral = 8, - StringLiteral = 9, - RegularExpressionLiteral = 10, - NoSubstitutionTemplateLiteral = 11, - TemplateHead = 12, - TemplateMiddle = 13, - TemplateTail = 14, - OpenBraceToken = 15, - CloseBraceToken = 16, - OpenParenToken = 17, - CloseParenToken = 18, - OpenBracketToken = 19, - CloseBracketToken = 20, - DotToken = 21, - DotDotDotToken = 22, - SemicolonToken = 23, - CommaToken = 24, - LessThanToken = 25, - LessThanSlashToken = 26, - GreaterThanToken = 27, - LessThanEqualsToken = 28, - GreaterThanEqualsToken = 29, - EqualsEqualsToken = 30, - ExclamationEqualsToken = 31, - EqualsEqualsEqualsToken = 32, - ExclamationEqualsEqualsToken = 33, - EqualsGreaterThanToken = 34, - PlusToken = 35, - MinusToken = 36, - AsteriskToken = 37, - SlashToken = 38, - PercentToken = 39, - PlusPlusToken = 40, - MinusMinusToken = 41, - LessThanLessThanToken = 42, - GreaterThanGreaterThanToken = 43, - GreaterThanGreaterThanGreaterThanToken = 44, - AmpersandToken = 45, - BarToken = 46, - CaretToken = 47, - ExclamationToken = 48, - TildeToken = 49, - AmpersandAmpersandToken = 50, - BarBarToken = 51, - QuestionToken = 52, - ColonToken = 53, - AtToken = 54, - EqualsToken = 55, - PlusEqualsToken = 56, - MinusEqualsToken = 57, - AsteriskEqualsToken = 58, - SlashEqualsToken = 59, - PercentEqualsToken = 60, - LessThanLessThanEqualsToken = 61, - GreaterThanGreaterThanEqualsToken = 62, - GreaterThanGreaterThanGreaterThanEqualsToken = 63, - AmpersandEqualsToken = 64, - BarEqualsToken = 65, - CaretEqualsToken = 66, - Identifier = 67, - BreakKeyword = 68, - CaseKeyword = 69, - CatchKeyword = 70, - ClassKeyword = 71, - ConstKeyword = 72, - ContinueKeyword = 73, - DebuggerKeyword = 74, - DefaultKeyword = 75, - DeleteKeyword = 76, - DoKeyword = 77, - ElseKeyword = 78, - EnumKeyword = 79, - ExportKeyword = 80, - ExtendsKeyword = 81, - FalseKeyword = 82, - FinallyKeyword = 83, - ForKeyword = 84, - FunctionKeyword = 85, - IfKeyword = 86, - ImportKeyword = 87, - InKeyword = 88, - InstanceOfKeyword = 89, - NewKeyword = 90, - NullKeyword = 91, - ReturnKeyword = 92, - SuperKeyword = 93, - SwitchKeyword = 94, - ThisKeyword = 95, - ThrowKeyword = 96, - TrueKeyword = 97, - TryKeyword = 98, - TypeOfKeyword = 99, - VarKeyword = 100, - VoidKeyword = 101, - WhileKeyword = 102, - WithKeyword = 103, - ImplementsKeyword = 104, - InterfaceKeyword = 105, - LetKeyword = 106, - PackageKeyword = 107, - PrivateKeyword = 108, - ProtectedKeyword = 109, - PublicKeyword = 110, - StaticKeyword = 111, - YieldKeyword = 112, - AbstractKeyword = 113, - AsKeyword = 114, - AnyKeyword = 115, - AsyncKeyword = 116, - AwaitKeyword = 117, - BooleanKeyword = 118, - ConstructorKeyword = 119, - DeclareKeyword = 120, - GetKeyword = 121, - IsKeyword = 122, - ModuleKeyword = 123, - NamespaceKeyword = 124, - RequireKeyword = 125, - NumberKeyword = 126, - SetKeyword = 127, - StringKeyword = 128, - SymbolKeyword = 129, - TypeKeyword = 130, - FromKeyword = 131, - OfKeyword = 132, - QualifiedName = 133, - ComputedPropertyName = 134, - TypeParameter = 135, - Parameter = 136, - Decorator = 137, - PropertySignature = 138, - PropertyDeclaration = 139, - MethodSignature = 140, - MethodDeclaration = 141, - Constructor = 142, - GetAccessor = 143, - SetAccessor = 144, - CallSignature = 145, - ConstructSignature = 146, - IndexSignature = 147, - TypePredicate = 148, - TypeReference = 149, - FunctionType = 150, - ConstructorType = 151, - TypeQuery = 152, - TypeLiteral = 153, - ArrayType = 154, - TupleType = 155, - UnionType = 156, - IntersectionType = 157, - ParenthesizedType = 158, - ObjectBindingPattern = 159, - ArrayBindingPattern = 160, - BindingElement = 161, - ArrayLiteralExpression = 162, - ObjectLiteralExpression = 163, - PropertyAccessExpression = 164, - ElementAccessExpression = 165, - CallExpression = 166, - NewExpression = 167, - TaggedTemplateExpression = 168, - TypeAssertionExpression = 169, - ParenthesizedExpression = 170, - FunctionExpression = 171, - ArrowFunction = 172, - DeleteExpression = 173, - TypeOfExpression = 174, - VoidExpression = 175, - AwaitExpression = 176, - PrefixUnaryExpression = 177, - PostfixUnaryExpression = 178, - BinaryExpression = 179, - ConditionalExpression = 180, - TemplateExpression = 181, - YieldExpression = 182, - SpreadElementExpression = 183, - ClassExpression = 184, - OmittedExpression = 185, - ExpressionWithTypeArguments = 186, - AsExpression = 187, - TemplateSpan = 188, - SemicolonClassElement = 189, - Block = 190, - VariableStatement = 191, - EmptyStatement = 192, - ExpressionStatement = 193, - IfStatement = 194, - DoStatement = 195, - WhileStatement = 196, - ForStatement = 197, - ForInStatement = 198, - ForOfStatement = 199, - ContinueStatement = 200, - BreakStatement = 201, - ReturnStatement = 202, - WithStatement = 203, - SwitchStatement = 204, - LabeledStatement = 205, - ThrowStatement = 206, - TryStatement = 207, - DebuggerStatement = 208, - VariableDeclaration = 209, - VariableDeclarationList = 210, - FunctionDeclaration = 211, - ClassDeclaration = 212, - InterfaceDeclaration = 213, - TypeAliasDeclaration = 214, - EnumDeclaration = 215, - ModuleDeclaration = 216, - ModuleBlock = 217, - CaseBlock = 218, - ImportEqualsDeclaration = 219, - ImportDeclaration = 220, - ImportClause = 221, - NamespaceImport = 222, - NamedImports = 223, - ImportSpecifier = 224, - ExportAssignment = 225, - ExportDeclaration = 226, - NamedExports = 227, - ExportSpecifier = 228, - MissingDeclaration = 229, - ExternalModuleReference = 230, - JsxElement = 231, - JsxSelfClosingElement = 232, - JsxOpeningElement = 233, - JsxText = 234, - JsxClosingElement = 235, - JsxAttribute = 236, - JsxSpreadAttribute = 237, - JsxExpression = 238, - CaseClause = 239, - DefaultClause = 240, - HeritageClause = 241, - CatchClause = 242, - PropertyAssignment = 243, - ShorthandPropertyAssignment = 244, - EnumMember = 245, - SourceFile = 246, - JSDocTypeExpression = 247, - JSDocAllType = 248, - JSDocUnknownType = 249, - JSDocArrayType = 250, - JSDocUnionType = 251, - JSDocTupleType = 252, - JSDocNullableType = 253, - JSDocNonNullableType = 254, - JSDocRecordType = 255, - JSDocRecordMember = 256, - JSDocTypeReference = 257, - JSDocOptionalType = 258, - JSDocFunctionType = 259, - JSDocVariadicType = 260, - JSDocConstructorType = 261, - JSDocThisType = 262, - JSDocComment = 263, - JSDocTag = 264, - JSDocParameterTag = 265, - JSDocReturnTag = 266, - JSDocTypeTag = 267, - JSDocTemplateTag = 268, - SyntaxList = 269, - Count = 270, - FirstAssignment = 55, - LastAssignment = 66, - FirstReservedWord = 68, - LastReservedWord = 103, - FirstKeyword = 68, - LastKeyword = 132, - FirstFutureReservedWord = 104, - LastFutureReservedWord = 112, - FirstTypeNode = 149, - LastTypeNode = 158, - FirstPunctuation = 15, - LastPunctuation = 66, - FirstToken = 0, - LastToken = 132, - FirstTriviaToken = 2, - LastTriviaToken = 7, - FirstLiteralToken = 8, - LastLiteralToken = 11, - FirstTemplateToken = 11, - LastTemplateToken = 14, - FirstBinaryOperator = 25, - LastBinaryOperator = 66, - FirstNode = 133, - } - const enum NodeFlags { - Export = 1, - Ambient = 2, - Public = 16, - Private = 32, - Protected = 64, - Static = 128, - Abstract = 256, - Async = 512, - Default = 1024, - MultiLine = 2048, - Synthetic = 4096, - DeclarationFile = 8192, - Let = 16384, - Const = 32768, - OctalLiteral = 65536, - Namespace = 131072, - ExportContext = 262144, - Modifier = 2035, - AccessibilityModifier = 112, - BlockScoped = 49152, - } - const enum JsxFlags { - None = 0, - IntrinsicNamedElement = 1, - IntrinsicIndexedElement = 2, - ClassElement = 4, - UnknownElement = 8, - IntrinsicElement = 3, - } - interface Node extends TextRange { - kind: SyntaxKind; - flags: NodeFlags; - decorators?: NodeArray; - modifiers?: ModifiersArray; - parent?: Node; - } - interface NodeArray extends Array, TextRange { - hasTrailingComma?: boolean; - } - interface ModifiersArray extends NodeArray { - flags: number; - } - interface Identifier extends PrimaryExpression { - text: string; - originalKeywordKind?: SyntaxKind; - } - interface QualifiedName extends Node { - left: EntityName; - right: Identifier; - } - type EntityName = Identifier | QualifiedName; - type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; - interface Declaration extends Node { - _declarationBrand: any; - name?: DeclarationName; - } - interface ComputedPropertyName extends Node { - expression: Expression; - } - interface Decorator extends Node { - expression: LeftHandSideExpression; - } - interface TypeParameterDeclaration extends Declaration { - name: Identifier; - constraint?: TypeNode; - expression?: Expression; - } - interface SignatureDeclaration extends Declaration { - typeParameters?: NodeArray; - parameters: NodeArray; - type?: TypeNode; - } - interface VariableDeclaration extends Declaration { - parent?: VariableDeclarationList; - name: Identifier | BindingPattern; - type?: TypeNode; - initializer?: Expression; - } - interface VariableDeclarationList extends Node { - declarations: NodeArray; - } - interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingElement extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: Identifier | BindingPattern; - initializer?: Expression; - } - interface PropertyDeclaration extends Declaration, ClassElement { - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface ObjectLiteralElement extends Declaration { - _objectLiteralBrandBrand: any; - } - interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; - name: DeclarationName; - questionToken?: Node; - initializer: Expression; - } - interface ShorthandPropertyAssignment extends ObjectLiteralElement { - name: Identifier; - questionToken?: Node; - } - interface VariableLikeDeclaration extends Declaration { - propertyName?: Identifier; - dotDotDotToken?: Node; - name: DeclarationName; - questionToken?: Node; - type?: TypeNode; - initializer?: Expression; - } - interface BindingPattern extends Node { - elements: NodeArray; - } - /** - * Several node kinds share function-like features such as a signature, - * a name, and a body. These nodes should extend FunctionLikeDeclaration. - * Examples: - * - FunctionDeclaration - * - MethodDeclaration - * - AccessorDeclaration - */ - interface FunctionLikeDeclaration extends SignatureDeclaration { - _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; - body?: Block | Expression; - } - interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { - name?: Identifier; - body?: Block; - } - interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - body?: Block; - } - interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { - body?: Block; - } - interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; - } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; - body: Block; - } - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { - _indexSignatureDeclarationBrand: any; - } - interface TypeNode extends Node { - _typeNodeBrand: any; - } - interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; - } - interface TypeReferenceNode extends TypeNode { - typeName: EntityName; - typeArguments?: NodeArray; - } - interface TypePredicateNode extends TypeNode { - parameterName: Identifier; - type: TypeNode; - } - interface TypeQueryNode extends TypeNode { - exprName: EntityName; - } - interface TypeLiteralNode extends TypeNode, Declaration { - members: NodeArray; - } - interface ArrayTypeNode extends TypeNode { - elementType: TypeNode; - } - interface TupleTypeNode extends TypeNode { - elementTypes: NodeArray; - } - interface UnionOrIntersectionTypeNode extends TypeNode { - types: NodeArray; - } - interface UnionTypeNode extends UnionOrIntersectionTypeNode { - } - interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { - } - interface ParenthesizedTypeNode extends TypeNode { - type: TypeNode; - } - interface StringLiteral extends LiteralExpression, TypeNode { - _stringLiteralBrand: any; - } - interface Expression extends Node { - _expressionBrand: any; - contextualType?: Type; - } - interface UnaryExpression extends Expression { - _unaryExpressionBrand: any; - } - interface PrefixUnaryExpression extends UnaryExpression { - operator: SyntaxKind; - operand: UnaryExpression; - } - interface PostfixUnaryExpression extends PostfixExpression { - operand: LeftHandSideExpression; - operator: SyntaxKind; - } - interface PostfixExpression extends UnaryExpression { - _postfixExpressionBrand: any; - } - interface LeftHandSideExpression extends PostfixExpression { - _leftHandSideExpressionBrand: any; - } - interface MemberExpression extends LeftHandSideExpression { - _memberExpressionBrand: any; - } - interface PrimaryExpression extends MemberExpression { - _primaryExpressionBrand: any; - } - interface DeleteExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface TypeOfExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface VoidExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface AwaitExpression extends UnaryExpression { - expression: UnaryExpression; - } - interface YieldExpression extends Expression { - asteriskToken?: Node; - expression?: Expression; - } - interface BinaryExpression extends Expression { - left: Expression; - operatorToken: Node; - right: Expression; - } - interface ConditionalExpression extends Expression { - condition: Expression; - questionToken: Node; - whenTrue: Expression; - colonToken: Node; - whenFalse: Expression; - } - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { - name?: Identifier; - body: Block | Expression; - } - interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; - } - interface LiteralExpression extends PrimaryExpression { - text: string; - isUnterminated?: boolean; - hasExtendedUnicodeEscape?: boolean; - } - interface TemplateExpression extends PrimaryExpression { - head: LiteralExpression; - templateSpans: NodeArray; - } - interface TemplateSpan extends Node { - expression: Expression; - literal: LiteralExpression; - } - interface ParenthesizedExpression extends PrimaryExpression { - expression: Expression; - } - interface ArrayLiteralExpression extends PrimaryExpression { - elements: NodeArray; - } - interface SpreadElementExpression extends Expression { - expression: Expression; - } - interface ObjectLiteralExpression extends PrimaryExpression, Declaration { - properties: NodeArray; - } - interface PropertyAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - dotToken: Node; - name: Identifier; - } - interface ElementAccessExpression extends MemberExpression { - expression: LeftHandSideExpression; - argumentExpression?: Expression; - } - interface CallExpression extends LeftHandSideExpression { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - arguments: NodeArray; - } - interface ExpressionWithTypeArguments extends TypeNode { - expression: LeftHandSideExpression; - typeArguments?: NodeArray; - } - interface NewExpression extends CallExpression, PrimaryExpression { - } - interface TaggedTemplateExpression extends MemberExpression { - tag: LeftHandSideExpression; - template: LiteralExpression | TemplateExpression; - } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; - interface AsExpression extends Expression { - expression: Expression; - type: TypeNode; - } - interface TypeAssertion extends UnaryExpression { - type: TypeNode; - expression: UnaryExpression; - } - type AssertionExpression = TypeAssertion | AsExpression; - interface JsxElement extends PrimaryExpression { - openingElement: JsxOpeningElement; - children: NodeArray; - closingElement: JsxClosingElement; - } - interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; - tagName: EntityName; - attributes: NodeArray; - } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; - } - type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; - interface JsxAttribute extends Node { - name: Identifier; - initializer?: Expression; - } - interface JsxSpreadAttribute extends Node { - expression: Expression; - } - interface JsxClosingElement extends Node { - tagName: EntityName; - } - interface JsxExpression extends Expression { - expression?: Expression; - } - interface JsxText extends Node { - _jsxTextExpressionBrand: any; - } - type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; - interface Statement extends Node { - _statementBrand: any; - } - interface Block extends Statement { - statements: NodeArray; - } - interface VariableStatement extends Statement { - declarationList: VariableDeclarationList; - } - interface ExpressionStatement extends Statement { - expression: Expression; - } - interface IfStatement extends Statement { - expression: Expression; - thenStatement: Statement; - elseStatement?: Statement; - } - interface IterationStatement extends Statement { - statement: Statement; - } - interface DoStatement extends IterationStatement { - expression: Expression; - } - interface WhileStatement extends IterationStatement { - expression: Expression; - } - interface ForStatement extends IterationStatement { - initializer?: VariableDeclarationList | Expression; - condition?: Expression; - incrementor?: Expression; - } - interface ForInStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface ForOfStatement extends IterationStatement { - initializer: VariableDeclarationList | Expression; - expression: Expression; - } - interface BreakOrContinueStatement extends Statement { - label?: Identifier; - } - interface ReturnStatement extends Statement { - expression?: Expression; - } - interface WithStatement extends Statement { - expression: Expression; - statement: Statement; - } - interface SwitchStatement extends Statement { - expression: Expression; - caseBlock: CaseBlock; - } - interface CaseBlock extends Node { - clauses: NodeArray; - } - interface CaseClause extends Node { - expression?: Expression; - statements: NodeArray; - } - interface DefaultClause extends Node { - statements: NodeArray; - } - type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement { - label: Identifier; - statement: Statement; - } - interface ThrowStatement extends Statement { - expression: Expression; - } - interface TryStatement extends Statement { - tryBlock: Block; - catchClause?: CatchClause; - finallyBlock?: Block; - } - interface CatchClause extends Node { - variableDeclaration: VariableDeclaration; - block: Block; - } - interface ClassLikeDeclaration extends Declaration { - name?: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface ClassDeclaration extends ClassLikeDeclaration, Statement { - } - interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { - } - interface ClassElement extends Declaration { - _classElementBrand: any; - } - interface InterfaceDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - heritageClauses?: NodeArray; - members: NodeArray; - } - interface HeritageClause extends Node { - token: SyntaxKind; - types?: NodeArray; - } - interface TypeAliasDeclaration extends Declaration, Statement { - name: Identifier; - typeParameters?: NodeArray; - type: TypeNode; - } - interface EnumMember extends Declaration { - name: DeclarationName; - initializer?: Expression; - } - interface EnumDeclaration extends Declaration, Statement { - name: Identifier; - members: NodeArray; - } - interface ModuleDeclaration extends Declaration, Statement { - name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; - } - interface ModuleBlock extends Node, Statement { - statements: NodeArray; - } - interface ImportEqualsDeclaration extends Declaration, Statement { - name: Identifier; - moduleReference: EntityName | ExternalModuleReference; - } - interface ExternalModuleReference extends Node { - expression?: Expression; - } - interface ImportDeclaration extends Statement { - importClause?: ImportClause; - moduleSpecifier: Expression; - } - interface ImportClause extends Declaration { - name?: Identifier; - namedBindings?: NamespaceImport | NamedImports; - } - interface NamespaceImport extends Declaration { - name: Identifier; - } - interface ExportDeclaration extends Declaration, Statement { - exportClause?: NamedExports; - moduleSpecifier?: Expression; - } - interface NamedImportsOrExports extends Node { - elements: NodeArray; - } - type NamedImports = NamedImportsOrExports; - type NamedExports = NamedImportsOrExports; - interface ImportOrExportSpecifier extends Declaration { - propertyName?: Identifier; - name: Identifier; - } - type ImportSpecifier = ImportOrExportSpecifier; - type ExportSpecifier = ImportOrExportSpecifier; - interface ExportAssignment extends Declaration, Statement { - isExportEquals?: boolean; - expression: Expression; - } - interface FileReference extends TextRange { - fileName: string; - } - interface CommentRange extends TextRange { - hasTrailingNewLine?: boolean; - kind: SyntaxKind; - } - interface JSDocTypeExpression extends Node { - type: JSDocType; - } - interface JSDocType extends TypeNode { - _jsDocTypeBrand: any; - } - interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; - } - interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; - } - interface JSDocArrayType extends JSDocType { - elementType: JSDocType; - } - interface JSDocUnionType extends JSDocType { - types: NodeArray; - } - interface JSDocTupleType extends JSDocType { - types: NodeArray; - } - interface JSDocNonNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocNullableType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { - members: NodeArray; - } - interface JSDocTypeReference extends JSDocType { - name: EntityName; - typeArguments: NodeArray; - } - interface JSDocOptionalType extends JSDocType { - type: JSDocType; - } - interface JSDocFunctionType extends JSDocType, SignatureDeclaration { - parameters: NodeArray; - type: JSDocType; - } - interface JSDocVariadicType extends JSDocType { - type: JSDocType; - } - interface JSDocConstructorType extends JSDocType { - type: JSDocType; - } - interface JSDocThisType extends JSDocType { - type: JSDocType; - } - interface JSDocRecordMember extends PropertyDeclaration { - name: Identifier | LiteralExpression; - type?: JSDocType; - } - interface JSDocComment extends Node { - tags: NodeArray; - } - interface JSDocTag extends Node { - atToken: Node; - tagName: Identifier; - } - interface JSDocTemplateTag extends JSDocTag { - typeParameters: NodeArray; - } - interface JSDocReturnTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocTypeTag extends JSDocTag { - typeExpression: JSDocTypeExpression; - } - interface JSDocParameterTag extends JSDocTag { - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - postParameterName?: Identifier; - isBracketed: boolean; - } - interface SourceFile extends Declaration { - statements: NodeArray; - endOfFileToken: Node; - fileName: string; - text: string; - amdDependencies: { - path: string; - name: string; - }[]; - moduleName: string; - referencedFiles: FileReference[]; - languageVariant: LanguageVariant; - /** - * lib.d.ts should have a reference comment like - * - * /// - * - * If any other file has this comment, it signals not to include lib.d.ts - * because this containing file is intended to act as a default library. - */ - hasNoDefaultLib: boolean; - languageVersion: ScriptTarget; - } - interface ScriptReferenceHost { - getCompilerOptions(): CompilerOptions; - getSourceFile(fileName: string): SourceFile; - getCurrentDirectory(): string; - } - interface ParseConfigHost extends ModuleResolutionHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; - } - interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; - } - class OperationCanceledException { - } - interface CancellationToken { - isCancellationRequested(): boolean; - /** @throws OperationCanceledException if isCancellationRequested is true */ - throwIfCancellationRequested(): void; - } - interface Program extends ScriptReferenceHost { - /** - * Get a list of root file names that were passed to a 'createProgram' - */ - getRootFileNames(): string[]; - /** - * Get a list of files in the program - */ - getSourceFiles(): SourceFile[]; - /** - * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then - * the JavaScript and declaration files will be produced for all the files in this program. - * If targetSourceFile is specified, then only the JavaScript and declaration for that - * specific file will be generated. - * - * If writeFile is not specified then the writeFile callback from the compiler host will be - * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter - * will be invoked when writing the JavaScript and declaration files. - */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - /** - * Gets a type checker that can be used to semantically analyze source fils in the program. - */ - getTypeChecker(): TypeChecker; - } - interface SourceMapSpan { - /** Line number in the .js file. */ - emittedLine: number; - /** Column number in the .js file. */ - emittedColumn: number; - /** Line number in the .ts file. */ - sourceLine: number; - /** Column number in the .ts file. */ - sourceColumn: number; - /** Optional name (index into names array) associated with this span. */ - nameIndex?: number; - /** .ts file (index into sources array) associated with this span */ - sourceIndex: number; - } - interface SourceMapData { - sourceMapFilePath: string; - jsSourceMappingURL: string; - sourceMapFile: string; - sourceMapSourceRoot: string; - sourceMapSources: string[]; - sourceMapSourcesContent?: string[]; - inputSourceFileNames: string[]; - sourceMapNames?: string[]; - sourceMapMappings: string; - sourceMapDecodedMappings: SourceMapSpan[]; - } - /** Return code used by getEmitOutput function to indicate status of the function */ - enum ExitStatus { - Success = 0, - DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, - } - interface EmitResult { - emitSkipped: boolean; - diagnostics: Diagnostic[]; - } - interface TypeChecker { - getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; - getDeclaredTypeOfSymbol(symbol: Symbol): Type; - getPropertiesOfType(type: Type): Symbol[]; - getPropertyOfType(type: Type, propertyName: string): Symbol; - getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; - getIndexTypeOfType(type: Type, kind: IndexKind): Type; - getBaseTypes(type: InterfaceType): ObjectType[]; - getReturnTypeOfSignature(signature: Signature): Type; - getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; - getSymbolAtLocation(node: Node): Symbol; - getShorthandAssignmentValueSymbol(location: Node): Symbol; - getTypeAtLocation(node: Node): Type; - typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; - getSymbolDisplayBuilder(): SymbolDisplayBuilder; - getFullyQualifiedName(symbol: Symbol): string; - getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; - getContextualType(node: Expression): Type; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; - isUndefinedSymbol(symbol: Symbol): boolean; - isArgumentsSymbol(symbol: Symbol): boolean; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; - isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; - getAliasedSymbol(symbol: Symbol): Symbol; - getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; - getJsxIntrinsicTagNames(): Symbol[]; - isOptionalParameter(node: ParameterDeclaration): boolean; - } - interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - interface SymbolWriter { - writeKeyword(text: string): void; - writeOperator(text: string): void; - writePunctuation(text: string): void; - writeSpace(text: string): void; - writeStringLiteral(text: string): void; - writeParameter(text: string): void; - writeSymbol(text: string, symbol: Symbol): void; - writeLine(): void; - increaseIndent(): void; - decreaseIndent(): void; - clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - } - const enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 2, - NoTruncation = 4, - WriteArrowStyleSignature = 8, - WriteOwnNameForAnyLike = 16, - WriteTypeArgumentsOfSignature = 32, - InElementType = 64, - UseFullyQualifiedType = 128, - } - const enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, - } - interface TypePredicate { - parameterName: string; - parameterIndex: number; - type: Type; - } - const enum SymbolFlags { - None = 0, - FunctionScopedVariable = 1, - BlockScopedVariable = 2, - Property = 4, - EnumMember = 8, - Function = 16, - Class = 32, - Interface = 64, - ConstEnum = 128, - RegularEnum = 256, - ValueModule = 512, - NamespaceModule = 1024, - TypeLiteral = 2048, - ObjectLiteral = 4096, - Method = 8192, - Constructor = 16384, - GetAccessor = 32768, - SetAccessor = 65536, - Signature = 131072, - TypeParameter = 262144, - TypeAlias = 524288, - ExportValue = 1048576, - ExportType = 2097152, - ExportNamespace = 4194304, - Alias = 8388608, - Instantiated = 16777216, - Merged = 33554432, - Transient = 67108864, - Prototype = 134217728, - SyntheticProperty = 268435456, - Optional = 536870912, - ExportStar = 1073741824, - Enum = 384, - Variable = 3, - Value = 107455, - Type = 793056, - Namespace = 1536, - Module = 1536, - Accessor = 98304, - FunctionScopedVariableExcludes = 107454, - BlockScopedVariableExcludes = 107455, - ParameterExcludes = 107455, - PropertyExcludes = 107455, - EnumMemberExcludes = 107455, - FunctionExcludes = 106927, - ClassExcludes = 899519, - InterfaceExcludes = 792960, - RegularEnumExcludes = 899327, - ConstEnumExcludes = 899967, - ValueModuleExcludes = 106639, - NamespaceModuleExcludes = 0, - MethodExcludes = 99263, - GetAccessorExcludes = 41919, - SetAccessorExcludes = 74687, - TypeParameterExcludes = 530912, - TypeAliasExcludes = 793056, - AliasExcludes = 8388608, - ModuleMember = 8914931, - ExportHasLocal = 944, - HasExports = 1952, - HasMembers = 6240, - BlockScoped = 418, - PropertyOrAccessor = 98308, - Export = 7340032, - } - interface Symbol { - flags: SymbolFlags; - name: string; - declarations?: Declaration[]; - valueDeclaration?: Declaration; - members?: SymbolTable; - exports?: SymbolTable; - } - interface SymbolTable { - [index: string]: Symbol; - } - const enum TypeFlags { - Any = 1, - String = 2, - Number = 4, - Boolean = 8, - Void = 16, - Undefined = 32, - Null = 64, - Enum = 128, - StringLiteral = 256, - TypeParameter = 512, - Class = 1024, - Interface = 2048, - Reference = 4096, - Tuple = 8192, - Union = 16384, - Intersection = 32768, - Anonymous = 65536, - Instantiated = 131072, - ObjectLiteral = 524288, - ESSymbol = 16777216, - StringLike = 258, - NumberLike = 132, - ObjectType = 80896, - UnionOrIntersection = 49152, - StructuredType = 130048, - } - interface Type { - flags: TypeFlags; - symbol?: Symbol; - } - interface StringLiteralType extends Type { - text: string; - } - interface ObjectType extends Type { - } - interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - } - interface InterfaceTypeWithDeclaredMembers extends InterfaceType { - declaredProperties: Symbol[]; - declaredCallSignatures: Signature[]; - declaredConstructSignatures: Signature[]; - declaredStringIndexType: Type; - declaredNumberIndexType: Type; - } - interface TypeReference extends ObjectType { - target: GenericType; - typeArguments: Type[]; - } - interface GenericType extends InterfaceType, TypeReference { - } - interface TupleType extends ObjectType { - elementTypes: Type[]; - baseArrayType: TypeReference; - } - interface UnionOrIntersectionType extends Type { - types: Type[]; - } - interface UnionType extends UnionOrIntersectionType { - } - interface IntersectionType extends UnionOrIntersectionType { - } - interface TypeParameter extends Type { - constraint: Type; - } - const enum SignatureKind { - Call = 0, - Construct = 1, - } - interface Signature { - declaration: SignatureDeclaration; - typeParameters: TypeParameter[]; - parameters: Symbol[]; - typePredicate?: TypePredicate; - } - const enum IndexKind { - String = 0, - Number = 1, - } - interface DiagnosticMessage { - key: string; - category: DiagnosticCategory; - code: number; - } - /** - * A linked list of formatted diagnostic messages to be used as part of a multiline message. - * It is built from the bottom up, leaving the head to be the "main" diagnostic. - * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, - * the difference is that messages are all preformatted in DMC. - */ - interface DiagnosticMessageChain { - messageText: string; - category: DiagnosticCategory; - code: number; - next?: DiagnosticMessageChain; - } - interface Diagnostic { - file: SourceFile; - start: number; - length: number; - messageText: string | DiagnosticMessageChain; - category: DiagnosticCategory; - code: number; - } - enum DiagnosticCategory { - Warning = 0, - Error = 1, - Message = 2, - } - const enum ModuleResolutionKind { - Classic = 1, - NodeJs = 2, - } - interface CompilerOptions { - allowNonTsExtensions?: boolean; - charset?: string; - declaration?: boolean; - diagnostics?: boolean; - emitBOM?: boolean; - help?: boolean; - init?: boolean; - inlineSourceMap?: boolean; - inlineSources?: boolean; - jsx?: JsxEmit; - listFiles?: boolean; - locale?: string; - mapRoot?: string; - module?: ModuleKind; - newLine?: NewLineKind; - noEmit?: boolean; - noEmitHelpers?: boolean; - noEmitOnError?: boolean; - noErrorTruncation?: boolean; - noImplicitAny?: boolean; - noLib?: boolean; - noResolve?: boolean; - out?: string; - outFile?: string; - outDir?: string; - preserveConstEnums?: boolean; - project?: string; - removeComments?: boolean; - rootDir?: string; - sourceMap?: boolean; - sourceRoot?: string; - suppressExcessPropertyErrors?: boolean; - suppressImplicitAnyIndexErrors?: boolean; - target?: ScriptTarget; - version?: boolean; - watch?: boolean; - isolatedModules?: boolean; - experimentalDecorators?: boolean; - experimentalAsyncFunctions?: boolean; - emitDecoratorMetadata?: boolean; - moduleResolution?: ModuleResolutionKind; - [option: string]: string | number | boolean; - } - const enum ModuleKind { - None = 0, - CommonJS = 1, - AMD = 2, - UMD = 3, - System = 4, - } - const enum JsxEmit { - None = 0, - Preserve = 1, - React = 2, - } - const enum NewLineKind { - CarriageReturnLineFeed = 0, - LineFeed = 1, - } - interface LineAndCharacter { - line: number; - character: number; - } - const enum ScriptTarget { - ES3 = 0, - ES5 = 1, - ES6 = 2, - Latest = 2, - } - const enum LanguageVariant { - Standard = 0, - JSX = 1, - } - interface ParsedCommandLine { - options: CompilerOptions; - fileNames: string[]; - errors: Diagnostic[]; - } - interface ModuleResolutionHost { - fileExists(fileName: string): boolean; - readFile(fileName: string): string; - } - interface ResolvedModule { - resolvedFileName: string; - isExternalLibraryImport?: boolean; - } - interface ResolvedModuleWithFailedLookupLocations { - resolvedModule: ResolvedModule; - failedLookupLocations: string[]; - } - interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; - getCancellationToken?(): CancellationToken; - getDefaultLibFileName(options: CompilerOptions): string; - writeFile: WriteFileCallback; - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - useCaseSensitiveFileNames(): boolean; - getNewLine(): string; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface TextSpan { - start: number; - length: number; - } - interface TextChangeRange { - span: TextSpan; - newLength: number; - } -} -declare module "typescript" { - interface System { - args: string[]; - newLine: string; - useCaseSensitiveFileNames: boolean; - write(s: string): void; - readFile(path: string, encoding?: string): string; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - watchFile?(path: string, callback: (path: string) => void): FileWatcher; - resolvePath(path: string): string; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getExecutingFilePath(): string; - getCurrentDirectory(): string; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; - getMemoryUsage?(): number; - exit(exitCode?: number): void; - } - interface FileWatcher { - close(): void; - } - var sys: System; -} -declare module "typescript" { - interface ErrorCallback { - (message: DiagnosticMessage, length: number): void; - } - interface Scanner { - getStartPos(): number; - getToken(): SyntaxKind; - getTextPos(): number; - getTokenPos(): number; - getTokenText(): string; - getTokenValue(): string; - hasExtendedUnicodeEscape(): boolean; - hasPrecedingLineBreak(): boolean; - isIdentifier(): boolean; - isReservedWord(): boolean; - isUnterminated(): boolean; - reScanGreaterToken(): SyntaxKind; - reScanSlashToken(): SyntaxKind; - reScanTemplateToken(): SyntaxKind; - scanJsxIdentifier(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; - scan(): SyntaxKind; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; - setScriptTarget(scriptTarget: ScriptTarget): void; - setLanguageVariant(variant: LanguageVariant): void; - setTextPos(textPos: number): void; - lookAhead(callback: () => T): T; - tryScan(callback: () => T): T; - } - function tokenToString(t: SyntaxKind): string; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; - function isWhiteSpace(ch: number): boolean; - function isLineBreak(ch: number): boolean; - function couldStartTrivia(text: string, pos: number): boolean; - function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; - function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; - /** Optionally, get the shebang */ - function getShebang(text: string): string; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; -} -declare module "typescript" { - function getDefaultLibFileName(options: CompilerOptions): string; - function textSpanEnd(span: TextSpan): number; - function textSpanIsEmpty(span: TextSpan): boolean; - function textSpanContainsPosition(span: TextSpan, position: number): boolean; - function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; - function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; - function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; - function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; - function createTextSpan(start: number, length: number): TextSpan; - function createTextSpanFromBounds(start: number, end: number): TextSpan; - function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; - function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; - function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; - let unchangedTextChangeRange: TextChangeRange; - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; -} -declare module "typescript" { - function getNodeConstructor(kind: SyntaxKind): new () => Node; - function createNode(kind: SyntaxKind): Node; - function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; - function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; - function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; -} -declare module "typescript" { - const version: string; - function findConfigFile(searchPath: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; -} -declare module "typescript" { - function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readConfigFile(fileName: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file - */ - function parseConfigFileText(fileName: string, jsonText: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; -} -declare module "typescript" { - /** The version of the language service API */ - let servicesVersion: string; - interface Node { - getSourceFile(): SourceFile; - getChildCount(sourceFile?: SourceFile): number; - getChildAt(index: number, sourceFile?: SourceFile): Node; - getChildren(sourceFile?: SourceFile): Node[]; - getStart(sourceFile?: SourceFile): number; - getFullStart(): number; - getEnd(): number; - getWidth(sourceFile?: SourceFile): number; - getFullWidth(): number; - getLeadingTriviaWidth(sourceFile?: SourceFile): number; - getFullText(sourceFile?: SourceFile): string; - getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; - } - interface Symbol { - getFlags(): SymbolFlags; - getName(): string; - getDeclarations(): Declaration[]; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface Type { - getFlags(): TypeFlags; - getSymbol(): Symbol; - getProperties(): Symbol[]; - getProperty(propertyName: string): Symbol; - getApparentProperties(): Symbol[]; - getCallSignatures(): Signature[]; - getConstructSignatures(): Signature[]; - getStringIndexType(): Type; - getNumberIndexType(): Type; - getBaseTypes(): ObjectType[]; - } - interface Signature { - getDeclaration(): SignatureDeclaration; - getTypeParameters(): Type[]; - getParameters(): Symbol[]; - getReturnType(): Type; - getDocumentationComment(): SymbolDisplayPart[]; - } - interface SourceFile { - getLineAndCharacterOfPosition(pos: number): LineAndCharacter; - getLineStarts(): number[]; - getPositionOfLineAndCharacter(line: number, character: number): number; - update(newText: string, textChangeRange: TextChangeRange): SourceFile; - } - /** - * Represents an immutable snapshot of a script at a specified time.Once acquired, the - * snapshot is observably immutable. i.e. the same calls with the same parameters will return - * the same values. - */ - interface IScriptSnapshot { - /** Gets a portion of the script snapshot specified by [start, end). */ - getText(start: number, end: number): string; - /** Gets the length of this script snapshot. */ - getLength(): number; - /** - * Gets the TextChangeRange that describe how the text changed between this text and - * an older version. This information is used by the incremental parser to determine - * what sections of the script need to be re-parsed. 'undefined' can be returned if the - * change range cannot be determined. However, in that case, incremental parsing will - * not happen and the entire document will be re - parsed. - */ - getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; - /** Releases all resources held by this script snapshot */ - dispose?(): void; - } - module ScriptSnapshot { - function fromString(text: string): IScriptSnapshot; - } - interface PreProcessedFileInfo { - referencedFiles: FileReference[]; - importedFiles: FileReference[]; - ambientExternalModules: string[]; - isLibFile: boolean; - } - interface HostCancellationToken { - isCancellationRequested(): boolean; - } - interface LanguageServiceHost { - getCompilationSettings(): CompilerOptions; - getNewLine?(): string; - getProjectVersion?(): string; - getScriptFileNames(): string[]; - getScriptVersion(fileName: string): string; - getScriptSnapshot(fileName: string): IScriptSnapshot; - getLocalizedDiagnosticMessages?(): any; - getCancellationToken?(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(options: CompilerOptions): string; - log?(s: string): void; - trace?(s: string): void; - error?(s: string): void; - useCaseSensitiveFileNames?(): boolean; - resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; - } - interface LanguageService { - cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; - getSemanticDiagnostics(fileName: string): Diagnostic[]; - getCompilerOptionsDiagnostics(): Diagnostic[]; - /** - * @deprecated Use getEncodedSyntacticClassifications instead. - */ - getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - /** - * @deprecated Use getEncodedSemanticClassifications instead. - */ - getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; - getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; - /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; - getNavigationBarItems(fileName: string): NavigationBarItem[]; - getOutliningSpans(fileName: string): OutliningSpan[]; - getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; - getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; - getEmitOutput(fileName: string): EmitOutput; - getProgram(): Program; - getSourceFile(fileName: string): SourceFile; - dispose(): void; - } - interface Classifications { - spans: number[]; - endOfLineState: EndOfLineState; - } - interface ClassifiedSpan { - textSpan: TextSpan; - classificationType: string; - } - interface NavigationBarItem { - text: string; - kind: string; - kindModifiers: string; - spans: TextSpan[]; - childItems: NavigationBarItem[]; - indent: number; - bolded: boolean; - grayed: boolean; - } - interface TodoCommentDescriptor { - text: string; - priority: number; - } - interface TodoComment { - descriptor: TodoCommentDescriptor; - message: string; - position: number; - } - class TextChange { - span: TextSpan; - newText: string; - } - interface TextInsertion { - newText: string; - /** The position in newText the caret should point to after the insertion. */ - caretOffset: number; - } - interface RenameLocation { - textSpan: TextSpan; - fileName: string; - } - interface ReferenceEntry { - textSpan: TextSpan; - fileName: string; - isWriteAccess: boolean; - } - interface DocumentHighlights { - fileName: string; - highlightSpans: HighlightSpan[]; - } - module HighlightSpanKind { - const none: string; - const definition: string; - const reference: string; - const writtenReference: string; - } - interface HighlightSpan { - fileName?: string; - textSpan: TextSpan; - kind: string; - } - interface NavigateToItem { - name: string; - kind: string; - kindModifiers: string; - matchKind: string; - isCaseSensitive: boolean; - fileName: string; - textSpan: TextSpan; - containerName: string; - containerKind: string; - } - interface EditorOptions { - IndentSize: number; - TabSize: number; - NewLineCharacter: string; - ConvertTabsToSpaces: boolean; - } - interface FormatCodeOptions extends EditorOptions { - InsertSpaceAfterCommaDelimiter: boolean; - InsertSpaceAfterSemicolonInForStatements: boolean; - InsertSpaceBeforeAndAfterBinaryOperators: boolean; - InsertSpaceAfterKeywordsInControlFlowStatements: boolean; - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - PlaceOpenBraceOnNewLineForFunctions: boolean; - PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string; - } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; - kind: string; - name: string; - containerKind: string; - containerName: string; - } - interface ReferencedSymbol { - definition: DefinitionInfo; - references: ReferenceEntry[]; - } - enum SymbolDisplayPartKind { - aliasName = 0, - className = 1, - enumName = 2, - fieldName = 3, - interfaceName = 4, - keyword = 5, - lineBreak = 6, - numericLiteral = 7, - stringLiteral = 8, - localName = 9, - methodName = 10, - moduleName = 11, - operator = 12, - parameterName = 13, - propertyName = 14, - punctuation = 15, - space = 16, - text = 17, - typeParameterName = 18, - enumMemberName = 19, - functionName = 20, - regularExpressionLiteral = 21, - } - interface SymbolDisplayPart { - text: string; - kind: string; - } - interface QuickInfo { - kind: string; - kindModifiers: string; - textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage: string; - displayName: string; - fullDisplayName: string; - kind: string; - kindModifiers: string; - triggerSpan: TextSpan; - } - interface SignatureHelpParameter { - name: string; - documentation: SymbolDisplayPart[]; - displayParts: SymbolDisplayPart[]; - isOptional: boolean; - } - /** - * Represents a single signature to show in signature help. - * The id is used for subsequent calls into the language service to ask questions about the - * signature help item in the context of any documents that have been updated. i.e. after - * an edit has happened, while signature help is still active, the host can ask important - * questions like 'what parameter is the user currently contained within?'. - */ - interface SignatureHelpItem { - isVariadic: boolean; - prefixDisplayParts: SymbolDisplayPart[]; - suffixDisplayParts: SymbolDisplayPart[]; - separatorDisplayParts: SymbolDisplayPart[]; - parameters: SignatureHelpParameter[]; - documentation: SymbolDisplayPart[]; - } - /** - * Represents a set of signature help items, and the preferred item that should be selected. - */ - interface SignatureHelpItems { - items: SignatureHelpItem[]; - applicableSpan: TextSpan; - selectedItemIndex: number; - argumentIndex: number; - argumentCount: number; - } - interface CompletionInfo { - isMemberCompletion: boolean; - isNewIdentifierLocation: boolean; - entries: CompletionEntry[]; - } - interface CompletionEntry { - name: string; - kind: string; - kindModifiers: string; - sortText: string; - } - interface CompletionEntryDetails { - name: string; - kind: string; - kindModifiers: string; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - } - interface OutliningSpan { - /** The span of the document to actually collapse. */ - textSpan: TextSpan; - /** The span of the document to display when the user hovers over the collapsed span. */ - hintSpan: TextSpan; - /** The text to display in the editor for the collapsed region. */ - bannerText: string; - /** - * Whether or not this region should be automatically collapsed when - * the 'Collapse to Definitions' command is invoked. - */ - autoCollapse: boolean; - } - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - const enum OutputFileType { - JavaScript = 0, - SourceMap = 1, - Declaration = 2, - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } - const enum EndOfLineState { - None = 0, - InMultiLineCommentTrivia = 1, - InSingleQuoteStringLiteral = 2, - InDoubleQuoteStringLiteral = 3, - InTemplateHeadOrNoSubstitutionTemplate = 4, - InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, - } - enum TokenClass { - Punctuation = 0, - Keyword = 1, - Operator = 2, - Comment = 3, - Whitespace = 4, - Identifier = 5, - NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8, - } - interface ClassificationResult { - finalLexState: EndOfLineState; - entries: ClassificationInfo[]; - } - interface ClassificationInfo { - length: number; - classification: TokenClass; - } - interface Classifier { - /** - * Gives lexical classifications of tokens on a line without any syntactic context. - * For instance, a token consisting of the text 'string' can be either an identifier - * named 'string' or the keyword 'string', however, because this classifier is not aware, - * it relies on certain heuristics to give acceptable results. For classifications where - * speed trumps accuracy, this function is preferable; however, for true accuracy, the - * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the - * lexical, syntactic, and semantic classifiers may issue the best user experience. - * - * @param text The text of a line to classify. - * @param lexState The state of the lexical classifier at the end of the previous line. - * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. - * If there is no syntactic classifier (syntacticClassifierAbsent=true), - * certain heuristics may be used in its place; however, if there is a - * syntactic classifier (syntacticClassifierAbsent=false), certain - * classifications which may be incorrectly categorized will be given - * back as Identifiers in order to allow the syntactic classifier to - * subsume the classification. - * @deprecated Use getLexicalClassifications instead. - */ - getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; - getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; - } - /** - * The document registry represents a store of SourceFile objects that can be shared between - * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) - * of files in the context. - * SourceFile objects account for most of the memory usage by the language service. Sharing - * the same DocumentRegistry instance between different instances of LanguageService allow - * for more efficient memory utilization since all projects will share at least the library - * file (lib.d.ts). - * - * A more advanced use of the document registry is to serialize sourceFile objects to disk - * and re-hydrate them when needed. - * - * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it - * to all subsequent createLanguageService calls. - */ - interface DocumentRegistry { - /** - * Request a stored SourceFile with a given fileName and compilationSettings. - * The first call to acquire will call createLanguageServiceSourceFile to generate - * the SourceFile if was not found in the registry. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @parm scriptSnapshot Text of the file. Only used if the file was not found - * in the registry and a new one was created. - * @parm version Current version of the file. Only used if the file was not found - * in the registry and a new one was created. - */ - acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Request an updated version of an already existing SourceFile with a given fileName - * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile - * to get an updated SourceFile. - * - * @param fileName The name of the file requested - * @param compilationSettings Some compilation settings like target affects the - * shape of a the resulting SourceFile. This allows the DocumentRegistry to store - * multiple copies of the same file for different compilation settings. - * @param scriptSnapshot Text of the file. - * @param version Current version of the file. - */ - updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; - /** - * Informs the DocumentRegistry that a file is not needed any longer. - * - * Note: It is not allowed to call release on a SourceFile that was not acquired from - * this registry originally. - * - * @param fileName The name of the file to be released - * @param compilationSettings The compilation settings used to acquire the file - */ - releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; - reportStats(): string; - } - module ScriptElementKind { - const unknown: string; - const warning: string; - const keyword: string; - const scriptElement: string; - const moduleElement: string; - const classElement: string; - const localClassElement: string; - const interfaceElement: string; - const typeElement: string; - const enumElement: string; - const variableElement: string; - const localVariableElement: string; - const functionElement: string; - const localFunctionElement: string; - const memberFunctionElement: string; - const memberGetAccessorElement: string; - const memberSetAccessorElement: string; - const memberVariableElement: string; - const constructorImplementationElement: string; - const callSignatureElement: string; - const indexSignatureElement: string; - const constructSignatureElement: string; - const parameterElement: string; - const typeParameterElement: string; - const primitiveType: string; - const label: string; - const alias: string; - const constElement: string; - const letElement: string; - } - module ScriptElementKindModifier { - const none: string; - const publicMemberModifier: string; - const privateMemberModifier: string; - const protectedMemberModifier: string; - const exportedModifier: string; - const ambientModifier: string; - const staticModifier: string; - const abstractModifier: string; - } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - } - const enum ClassificationType { - comment = 1, - identifier = 2, - keyword = 3, - numericLiteral = 4, - operator = 5, - stringLiteral = 6, - regularExpressionLiteral = 7, - whiteSpace = 8, - text = 9, - punctuation = 10, - className = 11, - enumName = 12, - interfaceName = 13, - moduleName = 14, - typeParameterName = 15, - typeAliasName = 16, - parameterName = 17, - docCommentTagName = 18, - } - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; - function getDefaultCompilerOptions(): CompilerOptions; - interface TranspileOptions { - compilerOptions?: CompilerOptions; - fileName?: string; - reportDiagnostics?: boolean; - moduleName?: string; - renamedDependencies?: Map; - } - interface TranspileOutput { - outputText: string; - diagnostics?: Diagnostic[]; - sourceMapText?: string; - } - function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; - function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; - function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; - function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; - function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; - function createClassifier(): Classifier; - /** - * Get the path of the default library files (lib.d.ts) as distributed with the typescript - * node package. - * The functionality is not supported if the ts module is consumed outside of a node module. - */ - function getDefaultLibFilePath(options: CompilerOptions): string; -} +// Type definitions for TypeScript API v0.4.0 +// Project: http://www.typescriptlang.org/ +// Definitions by: Microsoft TypeScript +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +declare module "typescript" { + interface Map { + [index: string]: T; + } + interface FileMap { + get(fileName: string): T; + set(fileName: string, value: T): void; + contains(fileName: string): boolean; + remove(fileName: string): void; + forEachValue(f: (v: T) => void): void; + clear(): void; + } + interface TextRange { + pos: number; + end: number; + } + const enum SyntaxKind { + Unknown = 0, + EndOfFileToken = 1, + SingleLineCommentTrivia = 2, + MultiLineCommentTrivia = 3, + NewLineTrivia = 4, + WhitespaceTrivia = 5, + ShebangTrivia = 6, + ConflictMarkerTrivia = 7, + NumericLiteral = 8, + StringLiteral = 9, + RegularExpressionLiteral = 10, + NoSubstitutionTemplateLiteral = 11, + TemplateHead = 12, + TemplateMiddle = 13, + TemplateTail = 14, + OpenBraceToken = 15, + CloseBraceToken = 16, + OpenParenToken = 17, + CloseParenToken = 18, + OpenBracketToken = 19, + CloseBracketToken = 20, + DotToken = 21, + DotDotDotToken = 22, + SemicolonToken = 23, + CommaToken = 24, + LessThanToken = 25, + LessThanSlashToken = 26, + GreaterThanToken = 27, + LessThanEqualsToken = 28, + GreaterThanEqualsToken = 29, + EqualsEqualsToken = 30, + ExclamationEqualsToken = 31, + EqualsEqualsEqualsToken = 32, + ExclamationEqualsEqualsToken = 33, + EqualsGreaterThanToken = 34, + PlusToken = 35, + MinusToken = 36, + AsteriskToken = 37, + SlashToken = 38, + PercentToken = 39, + PlusPlusToken = 40, + MinusMinusToken = 41, + LessThanLessThanToken = 42, + GreaterThanGreaterThanToken = 43, + GreaterThanGreaterThanGreaterThanToken = 44, + AmpersandToken = 45, + BarToken = 46, + CaretToken = 47, + ExclamationToken = 48, + TildeToken = 49, + AmpersandAmpersandToken = 50, + BarBarToken = 51, + QuestionToken = 52, + ColonToken = 53, + AtToken = 54, + EqualsToken = 55, + PlusEqualsToken = 56, + MinusEqualsToken = 57, + AsteriskEqualsToken = 58, + SlashEqualsToken = 59, + PercentEqualsToken = 60, + LessThanLessThanEqualsToken = 61, + GreaterThanGreaterThanEqualsToken = 62, + GreaterThanGreaterThanGreaterThanEqualsToken = 63, + AmpersandEqualsToken = 64, + BarEqualsToken = 65, + CaretEqualsToken = 66, + Identifier = 67, + BreakKeyword = 68, + CaseKeyword = 69, + CatchKeyword = 70, + ClassKeyword = 71, + ConstKeyword = 72, + ContinueKeyword = 73, + DebuggerKeyword = 74, + DefaultKeyword = 75, + DeleteKeyword = 76, + DoKeyword = 77, + ElseKeyword = 78, + EnumKeyword = 79, + ExportKeyword = 80, + ExtendsKeyword = 81, + FalseKeyword = 82, + FinallyKeyword = 83, + ForKeyword = 84, + FunctionKeyword = 85, + IfKeyword = 86, + ImportKeyword = 87, + InKeyword = 88, + InstanceOfKeyword = 89, + NewKeyword = 90, + NullKeyword = 91, + ReturnKeyword = 92, + SuperKeyword = 93, + SwitchKeyword = 94, + ThisKeyword = 95, + ThrowKeyword = 96, + TrueKeyword = 97, + TryKeyword = 98, + TypeOfKeyword = 99, + VarKeyword = 100, + VoidKeyword = 101, + WhileKeyword = 102, + WithKeyword = 103, + ImplementsKeyword = 104, + InterfaceKeyword = 105, + LetKeyword = 106, + PackageKeyword = 107, + PrivateKeyword = 108, + ProtectedKeyword = 109, + PublicKeyword = 110, + StaticKeyword = 111, + YieldKeyword = 112, + AbstractKeyword = 113, + AsKeyword = 114, + AnyKeyword = 115, + AsyncKeyword = 116, + AwaitKeyword = 117, + BooleanKeyword = 118, + ConstructorKeyword = 119, + DeclareKeyword = 120, + GetKeyword = 121, + IsKeyword = 122, + ModuleKeyword = 123, + NamespaceKeyword = 124, + RequireKeyword = 125, + NumberKeyword = 126, + SetKeyword = 127, + StringKeyword = 128, + SymbolKeyword = 129, + TypeKeyword = 130, + FromKeyword = 131, + OfKeyword = 132, + QualifiedName = 133, + ComputedPropertyName = 134, + TypeParameter = 135, + Parameter = 136, + Decorator = 137, + PropertySignature = 138, + PropertyDeclaration = 139, + MethodSignature = 140, + MethodDeclaration = 141, + Constructor = 142, + GetAccessor = 143, + SetAccessor = 144, + CallSignature = 145, + ConstructSignature = 146, + IndexSignature = 147, + TypePredicate = 148, + TypeReference = 149, + FunctionType = 150, + ConstructorType = 151, + TypeQuery = 152, + TypeLiteral = 153, + ArrayType = 154, + TupleType = 155, + UnionType = 156, + IntersectionType = 157, + ParenthesizedType = 158, + ObjectBindingPattern = 159, + ArrayBindingPattern = 160, + BindingElement = 161, + ArrayLiteralExpression = 162, + ObjectLiteralExpression = 163, + PropertyAccessExpression = 164, + ElementAccessExpression = 165, + CallExpression = 166, + NewExpression = 167, + TaggedTemplateExpression = 168, + TypeAssertionExpression = 169, + ParenthesizedExpression = 170, + FunctionExpression = 171, + ArrowFunction = 172, + DeleteExpression = 173, + TypeOfExpression = 174, + VoidExpression = 175, + AwaitExpression = 176, + PrefixUnaryExpression = 177, + PostfixUnaryExpression = 178, + BinaryExpression = 179, + ConditionalExpression = 180, + TemplateExpression = 181, + YieldExpression = 182, + SpreadElementExpression = 183, + ClassExpression = 184, + OmittedExpression = 185, + ExpressionWithTypeArguments = 186, + AsExpression = 187, + TemplateSpan = 188, + SemicolonClassElement = 189, + Block = 190, + VariableStatement = 191, + EmptyStatement = 192, + ExpressionStatement = 193, + IfStatement = 194, + DoStatement = 195, + WhileStatement = 196, + ForStatement = 197, + ForInStatement = 198, + ForOfStatement = 199, + ContinueStatement = 200, + BreakStatement = 201, + ReturnStatement = 202, + WithStatement = 203, + SwitchStatement = 204, + LabeledStatement = 205, + ThrowStatement = 206, + TryStatement = 207, + DebuggerStatement = 208, + VariableDeclaration = 209, + VariableDeclarationList = 210, + FunctionDeclaration = 211, + ClassDeclaration = 212, + InterfaceDeclaration = 213, + TypeAliasDeclaration = 214, + EnumDeclaration = 215, + ModuleDeclaration = 216, + ModuleBlock = 217, + CaseBlock = 218, + ImportEqualsDeclaration = 219, + ImportDeclaration = 220, + ImportClause = 221, + NamespaceImport = 222, + NamedImports = 223, + ImportSpecifier = 224, + ExportAssignment = 225, + ExportDeclaration = 226, + NamedExports = 227, + ExportSpecifier = 228, + MissingDeclaration = 229, + ExternalModuleReference = 230, + JsxElement = 231, + JsxSelfClosingElement = 232, + JsxOpeningElement = 233, + JsxText = 234, + JsxClosingElement = 235, + JsxAttribute = 236, + JsxSpreadAttribute = 237, + JsxExpression = 238, + CaseClause = 239, + DefaultClause = 240, + HeritageClause = 241, + CatchClause = 242, + PropertyAssignment = 243, + ShorthandPropertyAssignment = 244, + EnumMember = 245, + SourceFile = 246, + JSDocTypeExpression = 247, + JSDocAllType = 248, + JSDocUnknownType = 249, + JSDocArrayType = 250, + JSDocUnionType = 251, + JSDocTupleType = 252, + JSDocNullableType = 253, + JSDocNonNullableType = 254, + JSDocRecordType = 255, + JSDocRecordMember = 256, + JSDocTypeReference = 257, + JSDocOptionalType = 258, + JSDocFunctionType = 259, + JSDocVariadicType = 260, + JSDocConstructorType = 261, + JSDocThisType = 262, + JSDocComment = 263, + JSDocTag = 264, + JSDocParameterTag = 265, + JSDocReturnTag = 266, + JSDocTypeTag = 267, + JSDocTemplateTag = 268, + SyntaxList = 269, + Count = 270, + FirstAssignment = 55, + LastAssignment = 66, + FirstReservedWord = 68, + LastReservedWord = 103, + FirstKeyword = 68, + LastKeyword = 132, + FirstFutureReservedWord = 104, + LastFutureReservedWord = 112, + FirstTypeNode = 149, + LastTypeNode = 158, + FirstPunctuation = 15, + LastPunctuation = 66, + FirstToken = 0, + LastToken = 132, + FirstTriviaToken = 2, + LastTriviaToken = 7, + FirstLiteralToken = 8, + LastLiteralToken = 11, + FirstTemplateToken = 11, + LastTemplateToken = 14, + FirstBinaryOperator = 25, + LastBinaryOperator = 66, + FirstNode = 133, + } + const enum NodeFlags { + Export = 1, + Ambient = 2, + Public = 16, + Private = 32, + Protected = 64, + Static = 128, + Abstract = 256, + Async = 512, + Default = 1024, + MultiLine = 2048, + Synthetic = 4096, + DeclarationFile = 8192, + Let = 16384, + Const = 32768, + OctalLiteral = 65536, + Namespace = 131072, + ExportContext = 262144, + Modifier = 2035, + AccessibilityModifier = 112, + BlockScoped = 49152, + } + const enum JsxFlags { + None = 0, + IntrinsicNamedElement = 1, + IntrinsicIndexedElement = 2, + ClassElement = 4, + UnknownElement = 8, + IntrinsicElement = 3, + } + interface Node extends TextRange { + kind: SyntaxKind; + flags: NodeFlags; + decorators?: NodeArray; + modifiers?: ModifiersArray; + parent?: Node; + } + interface NodeArray extends Array, TextRange { + hasTrailingComma?: boolean; + } + interface ModifiersArray extends NodeArray { + flags: number; + } + interface Identifier extends PrimaryExpression { + text: string; + originalKeywordKind?: SyntaxKind; + } + interface QualifiedName extends Node { + left: EntityName; + right: Identifier; + } + type EntityName = Identifier | QualifiedName; + type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; + interface Declaration extends Node { + _declarationBrand: any; + name?: DeclarationName; + } + interface ComputedPropertyName extends Node { + expression: Expression; + } + interface Decorator extends Node { + expression: LeftHandSideExpression; + } + interface TypeParameterDeclaration extends Declaration { + name: Identifier; + constraint?: TypeNode; + expression?: Expression; + } + interface SignatureDeclaration extends Declaration { + typeParameters?: NodeArray; + parameters: NodeArray; + type?: TypeNode; + } + interface VariableDeclaration extends Declaration { + parent?: VariableDeclarationList; + name: Identifier | BindingPattern; + type?: TypeNode; + initializer?: Expression; + } + interface VariableDeclarationList extends Node { + declarations: NodeArray; + } + interface ParameterDeclaration extends Declaration { + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingElement extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: Identifier | BindingPattern; + initializer?: Expression; + } + interface PropertyDeclaration extends Declaration, ClassElement { + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface ObjectLiteralElement extends Declaration { + _objectLiteralBrandBrand: any; + } + interface PropertyAssignment extends ObjectLiteralElement { + _propertyAssignmentBrand: any; + name: DeclarationName; + questionToken?: Node; + initializer: Expression; + } + interface ShorthandPropertyAssignment extends ObjectLiteralElement { + name: Identifier; + questionToken?: Node; + } + interface VariableLikeDeclaration extends Declaration { + propertyName?: Identifier; + dotDotDotToken?: Node; + name: DeclarationName; + questionToken?: Node; + type?: TypeNode; + initializer?: Expression; + } + interface BindingPattern extends Node { + elements: NodeArray; + } + /** + * Several node kinds share function-like features such as a signature, + * a name, and a body. These nodes should extend FunctionLikeDeclaration. + * Examples: + * - FunctionDeclaration + * - MethodDeclaration + * - AccessorDeclaration + */ + interface FunctionLikeDeclaration extends SignatureDeclaration { + _functionLikeDeclarationBrand: any; + asteriskToken?: Node; + questionToken?: Node; + body?: Block | Expression; + } + interface FunctionDeclaration extends FunctionLikeDeclaration, Statement { + name?: Identifier; + body?: Block; + } + interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + body?: Block; + } + interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + body?: Block; + } + interface SemicolonClassElement extends ClassElement { + _semicolonClassElementBrand: any; + } + interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + _accessorDeclarationBrand: any; + body: Block; + } + interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement { + _indexSignatureDeclarationBrand: any; + } + interface TypeNode extends Node { + _typeNodeBrand: any; + } + interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { + _functionOrConstructorTypeNodeBrand: any; + } + interface TypeReferenceNode extends TypeNode { + typeName: EntityName; + typeArguments?: NodeArray; + } + interface TypePredicateNode extends TypeNode { + parameterName: Identifier; + type: TypeNode; + } + interface TypeQueryNode extends TypeNode { + exprName: EntityName; + } + interface TypeLiteralNode extends TypeNode, Declaration { + members: NodeArray; + } + interface ArrayTypeNode extends TypeNode { + elementType: TypeNode; + } + interface TupleTypeNode extends TypeNode { + elementTypes: NodeArray; + } + interface UnionOrIntersectionTypeNode extends TypeNode { + types: NodeArray; + } + interface UnionTypeNode extends UnionOrIntersectionTypeNode { + } + interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + } + interface ParenthesizedTypeNode extends TypeNode { + type: TypeNode; + } + interface StringLiteral extends LiteralExpression, TypeNode { + _stringLiteralBrand: any; + } + interface Expression extends Node { + _expressionBrand: any; + contextualType?: Type; + } + interface UnaryExpression extends Expression { + _unaryExpressionBrand: any; + } + interface PrefixUnaryExpression extends UnaryExpression { + operator: SyntaxKind; + operand: UnaryExpression; + } + interface PostfixUnaryExpression extends PostfixExpression { + operand: LeftHandSideExpression; + operator: SyntaxKind; + } + interface PostfixExpression extends UnaryExpression { + _postfixExpressionBrand: any; + } + interface LeftHandSideExpression extends PostfixExpression { + _leftHandSideExpressionBrand: any; + } + interface MemberExpression extends LeftHandSideExpression { + _memberExpressionBrand: any; + } + interface PrimaryExpression extends MemberExpression { + _primaryExpressionBrand: any; + } + interface DeleteExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface TypeOfExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface VoidExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface AwaitExpression extends UnaryExpression { + expression: UnaryExpression; + } + interface YieldExpression extends Expression { + asteriskToken?: Node; + expression?: Expression; + } + interface BinaryExpression extends Expression { + left: Expression; + operatorToken: Node; + right: Expression; + } + interface ConditionalExpression extends Expression { + condition: Expression; + questionToken: Node; + whenTrue: Expression; + colonToken: Node; + whenFalse: Expression; + } + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + name?: Identifier; + body: Block | Expression; + } + interface ArrowFunction extends Expression, FunctionLikeDeclaration { + equalsGreaterThanToken: Node; + } + interface LiteralExpression extends PrimaryExpression { + text: string; + isUnterminated?: boolean; + hasExtendedUnicodeEscape?: boolean; + } + interface TemplateExpression extends PrimaryExpression { + head: LiteralExpression; + templateSpans: NodeArray; + } + interface TemplateSpan extends Node { + expression: Expression; + literal: LiteralExpression; + } + interface ParenthesizedExpression extends PrimaryExpression { + expression: Expression; + } + interface ArrayLiteralExpression extends PrimaryExpression { + elements: NodeArray; + } + interface SpreadElementExpression extends Expression { + expression: Expression; + } + interface ObjectLiteralExpression extends PrimaryExpression, Declaration { + properties: NodeArray; + } + interface PropertyAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + dotToken: Node; + name: Identifier; + } + interface ElementAccessExpression extends MemberExpression { + expression: LeftHandSideExpression; + argumentExpression?: Expression; + } + interface CallExpression extends LeftHandSideExpression { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; + } + interface ExpressionWithTypeArguments extends TypeNode { + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + } + interface NewExpression extends CallExpression, PrimaryExpression { + } + interface TaggedTemplateExpression extends MemberExpression { + tag: LeftHandSideExpression; + template: LiteralExpression | TemplateExpression; + } + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; + interface AsExpression extends Expression { + expression: Expression; + type: TypeNode; + } + interface TypeAssertion extends UnaryExpression { + type: TypeNode; + expression: UnaryExpression; + } + type AssertionExpression = TypeAssertion | AsExpression; + interface JsxElement extends PrimaryExpression { + openingElement: JsxOpeningElement; + children: NodeArray; + closingElement: JsxClosingElement; + } + interface JsxOpeningElement extends Expression { + _openingElementBrand?: any; + tagName: EntityName; + attributes: NodeArray; + } + interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { + _selfClosingElementBrand?: any; + } + type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + interface JsxAttribute extends Node { + name: Identifier; + initializer?: Expression; + } + interface JsxSpreadAttribute extends Node { + expression: Expression; + } + interface JsxClosingElement extends Node { + tagName: EntityName; + } + interface JsxExpression extends Expression { + expression?: Expression; + } + interface JsxText extends Node { + _jsxTextExpressionBrand: any; + } + type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; + interface Statement extends Node { + _statementBrand: any; + } + interface Block extends Statement { + statements: NodeArray; + } + interface VariableStatement extends Statement { + declarationList: VariableDeclarationList; + } + interface ExpressionStatement extends Statement { + expression: Expression; + } + interface IfStatement extends Statement { + expression: Expression; + thenStatement: Statement; + elseStatement?: Statement; + } + interface IterationStatement extends Statement { + statement: Statement; + } + interface DoStatement extends IterationStatement { + expression: Expression; + } + interface WhileStatement extends IterationStatement { + expression: Expression; + } + interface ForStatement extends IterationStatement { + initializer?: VariableDeclarationList | Expression; + condition?: Expression; + incrementor?: Expression; + } + interface ForInStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface ForOfStatement extends IterationStatement { + initializer: VariableDeclarationList | Expression; + expression: Expression; + } + interface BreakOrContinueStatement extends Statement { + label?: Identifier; + } + interface ReturnStatement extends Statement { + expression?: Expression; + } + interface WithStatement extends Statement { + expression: Expression; + statement: Statement; + } + interface SwitchStatement extends Statement { + expression: Expression; + caseBlock: CaseBlock; + } + interface CaseBlock extends Node { + clauses: NodeArray; + } + interface CaseClause extends Node { + expression?: Expression; + statements: NodeArray; + } + interface DefaultClause extends Node { + statements: NodeArray; + } + type CaseOrDefaultClause = CaseClause | DefaultClause; + interface LabeledStatement extends Statement { + label: Identifier; + statement: Statement; + } + interface ThrowStatement extends Statement { + expression: Expression; + } + interface TryStatement extends Statement { + tryBlock: Block; + catchClause?: CatchClause; + finallyBlock?: Block; + } + interface CatchClause extends Node { + variableDeclaration: VariableDeclaration; + block: Block; + } + interface ClassLikeDeclaration extends Declaration { + name?: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface ClassDeclaration extends ClassLikeDeclaration, Statement { + } + interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + } + interface ClassElement extends Declaration { + _classElementBrand: any; + } + interface InterfaceDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + heritageClauses?: NodeArray; + members: NodeArray; + } + interface HeritageClause extends Node { + token: SyntaxKind; + types?: NodeArray; + } + interface TypeAliasDeclaration extends Declaration, Statement { + name: Identifier; + typeParameters?: NodeArray; + type: TypeNode; + } + interface EnumMember extends Declaration { + name: DeclarationName; + initializer?: Expression; + } + interface EnumDeclaration extends Declaration, Statement { + name: Identifier; + members: NodeArray; + } + interface ModuleDeclaration extends Declaration, Statement { + name: Identifier | LiteralExpression; + body: ModuleBlock | ModuleDeclaration; + } + interface ModuleBlock extends Node, Statement { + statements: NodeArray; + } + interface ImportEqualsDeclaration extends Declaration, Statement { + name: Identifier; + moduleReference: EntityName | ExternalModuleReference; + } + interface ExternalModuleReference extends Node { + expression?: Expression; + } + interface ImportDeclaration extends Statement { + importClause?: ImportClause; + moduleSpecifier: Expression; + } + interface ImportClause extends Declaration { + name?: Identifier; + namedBindings?: NamespaceImport | NamedImports; + } + interface NamespaceImport extends Declaration { + name: Identifier; + } + interface ExportDeclaration extends Declaration, Statement { + exportClause?: NamedExports; + moduleSpecifier?: Expression; + } + interface NamedImportsOrExports extends Node { + elements: NodeArray; + } + type NamedImports = NamedImportsOrExports; + type NamedExports = NamedImportsOrExports; + interface ImportOrExportSpecifier extends Declaration { + propertyName?: Identifier; + name: Identifier; + } + type ImportSpecifier = ImportOrExportSpecifier; + type ExportSpecifier = ImportOrExportSpecifier; + interface ExportAssignment extends Declaration, Statement { + isExportEquals?: boolean; + expression: Expression; + } + interface FileReference extends TextRange { + fileName: string; + } + interface CommentRange extends TextRange { + hasTrailingNewLine?: boolean; + kind: SyntaxKind; + } + interface JSDocTypeExpression extends Node { + type: JSDocType; + } + interface JSDocType extends TypeNode { + _jsDocTypeBrand: any; + } + interface JSDocAllType extends JSDocType { + _JSDocAllTypeBrand: any; + } + interface JSDocUnknownType extends JSDocType { + _JSDocUnknownTypeBrand: any; + } + interface JSDocArrayType extends JSDocType { + elementType: JSDocType; + } + interface JSDocUnionType extends JSDocType { + types: NodeArray; + } + interface JSDocTupleType extends JSDocType { + types: NodeArray; + } + interface JSDocNonNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocNullableType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordType extends JSDocType, TypeLiteralNode { + members: NodeArray; + } + interface JSDocTypeReference extends JSDocType { + name: EntityName; + typeArguments: NodeArray; + } + interface JSDocOptionalType extends JSDocType { + type: JSDocType; + } + interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + parameters: NodeArray; + type: JSDocType; + } + interface JSDocVariadicType extends JSDocType { + type: JSDocType; + } + interface JSDocConstructorType extends JSDocType { + type: JSDocType; + } + interface JSDocThisType extends JSDocType { + type: JSDocType; + } + interface JSDocRecordMember extends PropertyDeclaration { + name: Identifier | LiteralExpression; + type?: JSDocType; + } + interface JSDocComment extends Node { + tags: NodeArray; + } + interface JSDocTag extends Node { + atToken: Node; + tagName: Identifier; + } + interface JSDocTemplateTag extends JSDocTag { + typeParameters: NodeArray; + } + interface JSDocReturnTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocTypeTag extends JSDocTag { + typeExpression: JSDocTypeExpression; + } + interface JSDocParameterTag extends JSDocTag { + preParameterName?: Identifier; + typeExpression?: JSDocTypeExpression; + postParameterName?: Identifier; + isBracketed: boolean; + } + interface SourceFile extends Declaration { + statements: NodeArray; + endOfFileToken: Node; + fileName: string; + text: string; + amdDependencies: { + path: string; + name: string; + }[]; + moduleName: string; + referencedFiles: FileReference[]; + languageVariant: LanguageVariant; + /** + * lib.d.ts should have a reference comment like + * + * /// + * + * If any other file has this comment, it signals not to include lib.d.ts + * because this containing file is intended to act as a default library. + */ + hasNoDefaultLib: boolean; + languageVersion: ScriptTarget; + } + interface ScriptReferenceHost { + getCompilerOptions(): CompilerOptions; + getSourceFile(fileName: string): SourceFile; + getCurrentDirectory(): string; + } + interface ParseConfigHost extends ModuleResolutionHost { + readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + } + interface WriteFileCallback { + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; + } + class OperationCanceledException { + } + interface CancellationToken { + isCancellationRequested(): boolean; + /** @throws OperationCanceledException if isCancellationRequested is true */ + throwIfCancellationRequested(): void; + } + interface Program extends ScriptReferenceHost { + /** + * Get a list of root file names that were passed to a 'createProgram' + */ + getRootFileNames(): string[]; + /** + * Get a list of files in the program + */ + getSourceFiles(): SourceFile[]; + /** + * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then + * the JavaScript and declaration files will be produced for all the files in this program. + * If targetSourceFile is specified, then only the JavaScript and declaration for that + * specific file will be generated. + * + * If writeFile is not specified then the writeFile callback from the compiler host will be + * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter + * will be invoked when writing the JavaScript and declaration files. + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + /** + * Gets a type checker that can be used to semantically analyze source fils in the program. + */ + getTypeChecker(): TypeChecker; + } + interface SourceMapSpan { + /** Line number in the .js file. */ + emittedLine: number; + /** Column number in the .js file. */ + emittedColumn: number; + /** Line number in the .ts file. */ + sourceLine: number; + /** Column number in the .ts file. */ + sourceColumn: number; + /** Optional name (index into names array) associated with this span. */ + nameIndex?: number; + /** .ts file (index into sources array) associated with this span */ + sourceIndex: number; + } + interface SourceMapData { + sourceMapFilePath: string; + jsSourceMappingURL: string; + sourceMapFile: string; + sourceMapSourceRoot: string; + sourceMapSources: string[]; + sourceMapSourcesContent?: string[]; + inputSourceFileNames: string[]; + sourceMapNames?: string[]; + sourceMapMappings: string; + sourceMapDecodedMappings: SourceMapSpan[]; + } + /** Return code used by getEmitOutput function to indicate status of the function */ + enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2, + } + interface EmitResult { + emitSkipped: boolean; + diagnostics: Diagnostic[]; + } + interface TypeChecker { + getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; + getDeclaredTypeOfSymbol(symbol: Symbol): Type; + getPropertiesOfType(type: Type): Symbol[]; + getPropertyOfType(type: Type, propertyName: string): Symbol; + getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; + getIndexTypeOfType(type: Type, kind: IndexKind): Type; + getBaseTypes(type: InterfaceType): ObjectType[]; + getReturnTypeOfSignature(signature: Signature): Type; + getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; + getSymbolAtLocation(node: Node): Symbol; + getShorthandAssignmentValueSymbol(location: Node): Symbol; + getTypeAtLocation(node: Node): Type; + typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + getSymbolDisplayBuilder(): SymbolDisplayBuilder; + getFullyQualifiedName(symbol: Symbol): string; + getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): Symbol[]; + getContextualType(node: Expression): Type; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; + getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; + isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; + isUndefinedSymbol(symbol: Symbol): boolean; + isArgumentsSymbol(symbol: Symbol): boolean; + getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; + getAliasedSymbol(symbol: Symbol): Symbol; + getExportsOfModule(moduleSymbol: Symbol): Symbol[]; + getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; + getJsxIntrinsicTagNames(): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; + } + interface SymbolDisplayBuilder { + buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void; + buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + } + interface SymbolWriter { + writeKeyword(text: string): void; + writeOperator(text: string): void; + writePunctuation(text: string): void; + writeSpace(text: string): void; + writeStringLiteral(text: string): void; + writeParameter(text: string): void; + writeSymbol(text: string, symbol: Symbol): void; + writeLine(): void; + increaseIndent(): void; + decreaseIndent(): void; + clear(): void; + trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + } + const enum TypeFormatFlags { + None = 0, + WriteArrayAsGenericType = 1, + UseTypeOfFunction = 2, + NoTruncation = 4, + WriteArrowStyleSignature = 8, + WriteOwnNameForAnyLike = 16, + WriteTypeArgumentsOfSignature = 32, + InElementType = 64, + UseFullyQualifiedType = 128, + } + const enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + } + interface TypePredicate { + parameterName: string; + parameterIndex: number; + type: Type; + } + const enum SymbolFlags { + None = 0, + FunctionScopedVariable = 1, + BlockScopedVariable = 2, + Property = 4, + EnumMember = 8, + Function = 16, + Class = 32, + Interface = 64, + ConstEnum = 128, + RegularEnum = 256, + ValueModule = 512, + NamespaceModule = 1024, + TypeLiteral = 2048, + ObjectLiteral = 4096, + Method = 8192, + Constructor = 16384, + GetAccessor = 32768, + SetAccessor = 65536, + Signature = 131072, + TypeParameter = 262144, + TypeAlias = 524288, + ExportValue = 1048576, + ExportType = 2097152, + ExportNamespace = 4194304, + Alias = 8388608, + Instantiated = 16777216, + Merged = 33554432, + Transient = 67108864, + Prototype = 134217728, + SyntheticProperty = 268435456, + Optional = 536870912, + ExportStar = 1073741824, + Enum = 384, + Variable = 3, + Value = 107455, + Type = 793056, + Namespace = 1536, + Module = 1536, + Accessor = 98304, + FunctionScopedVariableExcludes = 107454, + BlockScopedVariableExcludes = 107455, + ParameterExcludes = 107455, + PropertyExcludes = 107455, + EnumMemberExcludes = 107455, + FunctionExcludes = 106927, + ClassExcludes = 899519, + InterfaceExcludes = 792960, + RegularEnumExcludes = 899327, + ConstEnumExcludes = 899967, + ValueModuleExcludes = 106639, + NamespaceModuleExcludes = 0, + MethodExcludes = 99263, + GetAccessorExcludes = 41919, + SetAccessorExcludes = 74687, + TypeParameterExcludes = 530912, + TypeAliasExcludes = 793056, + AliasExcludes = 8388608, + ModuleMember = 8914931, + ExportHasLocal = 944, + HasExports = 1952, + HasMembers = 6240, + BlockScoped = 418, + PropertyOrAccessor = 98308, + Export = 7340032, + } + interface Symbol { + flags: SymbolFlags; + name: string; + declarations?: Declaration[]; + valueDeclaration?: Declaration; + members?: SymbolTable; + exports?: SymbolTable; + } + interface SymbolTable { + [index: string]: Symbol; + } + const enum TypeFlags { + Any = 1, + String = 2, + Number = 4, + Boolean = 8, + Void = 16, + Undefined = 32, + Null = 64, + Enum = 128, + StringLiteral = 256, + TypeParameter = 512, + Class = 1024, + Interface = 2048, + Reference = 4096, + Tuple = 8192, + Union = 16384, + Intersection = 32768, + Anonymous = 65536, + Instantiated = 131072, + ObjectLiteral = 524288, + ESSymbol = 16777216, + StringLike = 258, + NumberLike = 132, + ObjectType = 80896, + UnionOrIntersection = 49152, + StructuredType = 130048, + } + interface Type { + flags: TypeFlags; + symbol?: Symbol; + } + interface StringLiteralType extends Type { + text: string; + } + interface ObjectType extends Type { + } + interface InterfaceType extends ObjectType { + typeParameters: TypeParameter[]; + outerTypeParameters: TypeParameter[]; + localTypeParameters: TypeParameter[]; + } + interface InterfaceTypeWithDeclaredMembers extends InterfaceType { + declaredProperties: Symbol[]; + declaredCallSignatures: Signature[]; + declaredConstructSignatures: Signature[]; + declaredStringIndexType: Type; + declaredNumberIndexType: Type; + } + interface TypeReference extends ObjectType { + target: GenericType; + typeArguments: Type[]; + } + interface GenericType extends InterfaceType, TypeReference { + } + interface TupleType extends ObjectType { + elementTypes: Type[]; + baseArrayType: TypeReference; + } + interface UnionOrIntersectionType extends Type { + types: Type[]; + } + interface UnionType extends UnionOrIntersectionType { + } + interface IntersectionType extends UnionOrIntersectionType { + } + interface TypeParameter extends Type { + constraint: Type; + } + const enum SignatureKind { + Call = 0, + Construct = 1, + } + interface Signature { + declaration: SignatureDeclaration; + typeParameters: TypeParameter[]; + parameters: Symbol[]; + typePredicate?: TypePredicate; + } + const enum IndexKind { + String = 0, + Number = 1, + } + interface DiagnosticMessage { + key: string; + category: DiagnosticCategory; + code: number; + } + /** + * A linked list of formatted diagnostic messages to be used as part of a multiline message. + * It is built from the bottom up, leaving the head to be the "main" diagnostic. + * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, + * the difference is that messages are all preformatted in DMC. + */ + interface DiagnosticMessageChain { + messageText: string; + category: DiagnosticCategory; + code: number; + next?: DiagnosticMessageChain; + } + interface Diagnostic { + file: SourceFile; + start: number; + length: number; + messageText: string | DiagnosticMessageChain; + category: DiagnosticCategory; + code: number; + } + enum DiagnosticCategory { + Warning = 0, + Error = 1, + Message = 2, + } + const enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2, + } + interface CompilerOptions { + allowNonTsExtensions?: boolean; + charset?: string; + declaration?: boolean; + diagnostics?: boolean; + emitBOM?: boolean; + help?: boolean; + init?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + jsx?: JsxEmit; + listFiles?: boolean; + locale?: string; + mapRoot?: string; + module?: ModuleKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noImplicitAny?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outFile?: string; + outDir?: string; + preserveConstEnums?: boolean; + project?: string; + removeComments?: boolean; + rootDir?: string; + sourceMap?: boolean; + sourceRoot?: string; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + version?: boolean; + watch?: boolean; + isolatedModules?: boolean; + experimentalDecorators?: boolean; + experimentalAsyncFunctions?: boolean; + emitDecoratorMetadata?: boolean; + moduleResolution?: ModuleResolutionKind; + [option: string]: string | number | boolean; + } + const enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + } + const enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + } + const enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } + interface LineAndCharacter { + line: number; + character: number; + } + const enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES6 = 2, + Latest = 2, + } + const enum LanguageVariant { + Standard = 0, + JSX = 1, + } + interface ParsedCommandLine { + options: CompilerOptions; + fileNames: string[]; + errors: Diagnostic[]; + } + interface ModuleResolutionHost { + fileExists(fileName: string): boolean; + readFile(fileName: string): string; + } + interface ResolvedModule { + resolvedFileName: string; + isExternalLibraryImport?: boolean; + } + interface ResolvedModuleWithFailedLookupLocations { + resolvedModule: ResolvedModule; + failedLookupLocations: string[]; + } + interface CompilerHost extends ModuleResolutionHost { + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getCancellationToken?(): CancellationToken; + getDefaultLibFileName(options: CompilerOptions): string; + writeFile: WriteFileCallback; + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } +} +declare module "typescript" { + interface System { + args: string[]; + newLine: string; + useCaseSensitiveFileNames: boolean; + write(s: string): void; + readFile(path: string, encoding?: string): string; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; + watchFile?(path: string, callback: (path: string) => void): FileWatcher; + resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; + getExecutingFilePath(): string; + getCurrentDirectory(): string; + readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + getMemoryUsage?(): number; + exit(exitCode?: number): void; + } + interface FileWatcher { + close(): void; + } + var sys: System; +} +declare module "typescript" { + interface ErrorCallback { + (message: DiagnosticMessage, length: number): void; + } + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scanJsxIdentifier(): SyntaxKind; + reScanJsxToken(): SyntaxKind; + scanJsxToken(): SyntaxKind; + scan(): SyntaxKind; + setText(text: string, start?: number, length?: number): void; + setOnError(onError: ErrorCallback): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setLanguageVariant(variant: LanguageVariant): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + tryScan(callback: () => T): T; + } + function tokenToString(t: SyntaxKind): string; + function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; + function isWhiteSpace(ch: number): boolean; + function isLineBreak(ch: number): boolean; + function couldStartTrivia(text: string, pos: number): boolean; + function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; + function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; + /** Optionally, get the shebang */ + function getShebang(text: string): string; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +declare module "typescript" { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration; +} +declare module "typescript" { + function getNodeConstructor(kind: SyntaxKind): new () => Node; + function createNode(kind: SyntaxKind): Node; + function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare module "typescript" { + const version: string; + function findConfigFile(searchPath: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; +} +declare module "typescript" { + function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileText(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine; +} +declare module "typescript" { + /** The version of the language service API */ + let servicesVersion: string; + interface Node { + getSourceFile(): SourceFile; + getChildCount(sourceFile?: SourceFile): number; + getChildAt(index: number, sourceFile?: SourceFile): Node; + getChildren(sourceFile?: SourceFile): Node[]; + getStart(sourceFile?: SourceFile): number; + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: SourceFile): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: SourceFile): number; + getFullText(sourceFile?: SourceFile): string; + getText(sourceFile?: SourceFile): string; + getFirstToken(sourceFile?: SourceFile): Node; + getLastToken(sourceFile?: SourceFile): Node; + } + interface Symbol { + getFlags(): SymbolFlags; + getName(): string; + getDeclarations(): Declaration[]; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface Type { + getFlags(): TypeFlags; + getSymbol(): Symbol; + getProperties(): Symbol[]; + getProperty(propertyName: string): Symbol; + getApparentProperties(): Symbol[]; + getCallSignatures(): Signature[]; + getConstructSignatures(): Signature[]; + getStringIndexType(): Type; + getNumberIndexType(): Type; + getBaseTypes(): ObjectType[]; + } + interface Signature { + getDeclaration(): SignatureDeclaration; + getTypeParameters(): Type[]; + getParameters(): Symbol[]; + getReturnType(): Type; + getDocumentationComment(): SymbolDisplayPart[]; + } + interface SourceFile { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + getLineStarts(): number[]; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + } + /** + * Represents an immutable snapshot of a script at a specified time.Once acquired, the + * snapshot is observably immutable. i.e. the same calls with the same parameters will return + * the same values. + */ + interface IScriptSnapshot { + /** Gets a portion of the script snapshot specified by [start, end). */ + getText(start: number, end: number): string; + /** Gets the length of this script snapshot. */ + getLength(): number; + /** + * Gets the TextChangeRange that describe how the text changed between this text and + * an older version. This information is used by the incremental parser to determine + * what sections of the script need to be re-parsed. 'undefined' can be returned if the + * change range cannot be determined. However, in that case, incremental parsing will + * not happen and the entire document will be re - parsed. + */ + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + /** Releases all resources held by this script snapshot */ + dispose?(): void; + } + module ScriptSnapshot { + function fromString(text: string): IScriptSnapshot; + } + interface PreProcessedFileInfo { + referencedFiles: FileReference[]; + importedFiles: FileReference[]; + ambientExternalModules: string[]; + isLibFile: boolean; + } + interface HostCancellationToken { + isCancellationRequested(): boolean; + } + interface LanguageServiceHost { + getCompilationSettings(): CompilerOptions; + getNewLine?(): string; + getProjectVersion?(): string; + getScriptFileNames(): string[]; + getScriptVersion(fileName: string): string; + getScriptSnapshot(fileName: string): IScriptSnapshot; + getLocalizedDiagnosticMessages?(): any; + getCancellationToken?(): HostCancellationToken; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + log?(s: string): void; + trace?(s: string): void; + error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; + resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; + } + interface LanguageService { + cleanupSemanticCache(): void; + getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSemanticDiagnostics(fileName: string): Diagnostic[]; + getCompilerOptionsDiagnostics(): Diagnostic[]; + /** + * @deprecated Use getEncodedSyntacticClassifications instead. + */ + getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + /** + * @deprecated Use getEncodedSemanticClassifications instead. + */ + getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; + getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; + getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; + getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; + getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getRenameInfo(fileName: string, position: number): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + findReferences(fileName: string, position: number): ReferencedSymbol[]; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + /** @deprecated */ + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; + getNavigationBarItems(fileName: string): NavigationBarItem[]; + getOutliningSpans(fileName: string): OutliningSpan[]; + getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; + getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getEmitOutput(fileName: string): EmitOutput; + getProgram(): Program; + getSourceFile(fileName: string): SourceFile; + dispose(): void; + } + interface Classifications { + spans: number[]; + endOfLineState: EndOfLineState; + } + interface ClassifiedSpan { + textSpan: TextSpan; + classificationType: string; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems: NavigationBarItem[]; + indent: number; + bolded: boolean; + grayed: boolean; + } + interface TodoCommentDescriptor { + text: string; + priority: number; + } + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + class TextChange { + span: TextSpan; + newText: string; + } + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + interface RenameLocation { + textSpan: TextSpan; + fileName: string; + } + interface ReferenceEntry { + textSpan: TextSpan; + fileName: string; + isWriteAccess: boolean; + } + interface DocumentHighlights { + fileName: string; + highlightSpans: HighlightSpan[]; + } + module HighlightSpanKind { + const none: string; + const definition: string; + const reference: string; + const writtenReference: string; + } + interface HighlightSpan { + fileName?: string; + textSpan: TextSpan; + kind: string; + } + interface NavigateToItem { + name: string; + kind: string; + kindModifiers: string; + matchKind: string; + isCaseSensitive: boolean; + fileName: string; + textSpan: TextSpan; + containerName: string; + containerKind: string; + } + interface EditorOptions { + IndentSize: number; + TabSize: number; + NewLineCharacter: string; + ConvertTabsToSpaces: boolean; + } + interface FormatCodeOptions extends EditorOptions { + InsertSpaceAfterCommaDelimiter: boolean; + InsertSpaceAfterSemicolonInForStatements: boolean; + InsertSpaceBeforeAndAfterBinaryOperators: boolean; + InsertSpaceAfterKeywordsInControlFlowStatements: boolean; + InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; + InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + PlaceOpenBraceOnNewLineForFunctions: boolean; + PlaceOpenBraceOnNewLineForControlBlocks: boolean; + [s: string]: boolean | number | string; + } + interface DefinitionInfo { + fileName: string; + textSpan: TextSpan; + kind: string; + name: string; + containerKind: string; + containerName: string; + } + interface ReferencedSymbol { + definition: DefinitionInfo; + references: ReferenceEntry[]; + } + enum SymbolDisplayPartKind { + aliasName = 0, + className = 1, + enumName = 2, + fieldName = 3, + interfaceName = 4, + keyword = 5, + lineBreak = 6, + numericLiteral = 7, + stringLiteral = 8, + localName = 9, + methodName = 10, + moduleName = 11, + operator = 12, + parameterName = 13, + propertyName = 14, + punctuation = 15, + space = 16, + text = 17, + typeParameterName = 18, + enumMemberName = 19, + functionName = 20, + regularExpressionLiteral = 21, + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface QuickInfo { + kind: string; + kindModifiers: string; + textSpan: TextSpan; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + triggerSpan: TextSpan; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + * The id is used for subsequent calls into the language service to ask questions about the + * signature help item in the context of any documents that have been updated. i.e. after + * an edit has happened, while signature help is still active, the host can ask important + * questions like 'what parameter is the user currently contained within?'. + */ + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + /** + * Represents a set of signature help items, and the preferred item that should be selected. + */ + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface CompletionInfo { + isMemberCompletion: boolean; + isNewIdentifierLocation: boolean; + entries: CompletionEntry[]; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface OutliningSpan { + /** The span of the document to actually collapse. */ + textSpan: TextSpan; + /** The span of the document to display when the user hovers over the collapsed span. */ + hintSpan: TextSpan; + /** The text to display in the editor for the collapsed region. */ + bannerText: string; + /** + * Whether or not this region should be automatically collapsed when + * the 'Collapse to Definitions' command is invoked. + */ + autoCollapse: boolean; + } + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + const enum OutputFileType { + JavaScript = 0, + SourceMap = 1, + Declaration = 2, + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } + const enum EndOfLineState { + None = 0, + InMultiLineCommentTrivia = 1, + InSingleQuoteStringLiteral = 2, + InDoubleQuoteStringLiteral = 3, + InTemplateHeadOrNoSubstitutionTemplate = 4, + InTemplateMiddleOrTail = 5, + InTemplateSubstitutionPosition = 6, + } + enum TokenClass { + Punctuation = 0, + Keyword = 1, + Operator = 2, + Comment = 3, + Whitespace = 4, + Identifier = 5, + NumberLiteral = 6, + StringLiteral = 7, + RegExpLiteral = 8, + } + interface ClassificationResult { + finalLexState: EndOfLineState; + entries: ClassificationInfo[]; + } + interface ClassificationInfo { + length: number; + classification: TokenClass; + } + interface Classifier { + /** + * Gives lexical classifications of tokens on a line without any syntactic context. + * For instance, a token consisting of the text 'string' can be either an identifier + * named 'string' or the keyword 'string', however, because this classifier is not aware, + * it relies on certain heuristics to give acceptable results. For classifications where + * speed trumps accuracy, this function is preferable; however, for true accuracy, the + * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the + * lexical, syntactic, and semantic classifiers may issue the best user experience. + * + * @param text The text of a line to classify. + * @param lexState The state of the lexical classifier at the end of the previous line. + * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. + * If there is no syntactic classifier (syntacticClassifierAbsent=true), + * certain heuristics may be used in its place; however, if there is a + * syntactic classifier (syntacticClassifierAbsent=false), certain + * classifications which may be incorrectly categorized will be given + * back as Identifiers in order to allow the syntactic classifier to + * subsume the classification. + * @deprecated Use getLexicalClassifications instead. + */ + getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; + getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; + } + /** + * The document registry represents a store of SourceFile objects that can be shared between + * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) + * of files in the context. + * SourceFile objects account for most of the memory usage by the language service. Sharing + * the same DocumentRegistry instance between different instances of LanguageService allow + * for more efficient memory utilization since all projects will share at least the library + * file (lib.d.ts). + * + * A more advanced use of the document registry is to serialize sourceFile objects to disk + * and re-hydrate them when needed. + * + * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it + * to all subsequent createLanguageService calls. + */ + interface DocumentRegistry { + /** + * Request a stored SourceFile with a given fileName and compilationSettings. + * The first call to acquire will call createLanguageServiceSourceFile to generate + * the SourceFile if was not found in the registry. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @parm scriptSnapshot Text of the file. Only used if the file was not found + * in the registry and a new one was created. + * @parm version Current version of the file. Only used if the file was not found + * in the registry and a new one was created. + */ + acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Request an updated version of an already existing SourceFile with a given fileName + * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile + * to get an updated SourceFile. + * + * @param fileName The name of the file requested + * @param compilationSettings Some compilation settings like target affects the + * shape of a the resulting SourceFile. This allows the DocumentRegistry to store + * multiple copies of the same file for different compilation settings. + * @param scriptSnapshot Text of the file. + * @param version Current version of the file. + */ + updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile; + /** + * Informs the DocumentRegistry that a file is not needed any longer. + * + * Note: It is not allowed to call release on a SourceFile that was not acquired from + * this registry originally. + * + * @param fileName The name of the file to be released + * @param compilationSettings The compilation settings used to acquire the file + */ + releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; + reportStats(): string; + } + module ScriptElementKind { + const unknown: string; + const warning: string; + const keyword: string; + const scriptElement: string; + const moduleElement: string; + const classElement: string; + const localClassElement: string; + const interfaceElement: string; + const typeElement: string; + const enumElement: string; + const variableElement: string; + const localVariableElement: string; + const functionElement: string; + const localFunctionElement: string; + const memberFunctionElement: string; + const memberGetAccessorElement: string; + const memberSetAccessorElement: string; + const memberVariableElement: string; + const constructorImplementationElement: string; + const callSignatureElement: string; + const indexSignatureElement: string; + const constructSignatureElement: string; + const parameterElement: string; + const typeParameterElement: string; + const primitiveType: string; + const label: string; + const alias: string; + const constElement: string; + const letElement: string; + } + module ScriptElementKindModifier { + const none: string; + const publicMemberModifier: string; + const privateMemberModifier: string; + const protectedMemberModifier: string; + const exportedModifier: string; + const ambientModifier: string; + const staticModifier: string; + const abstractModifier: string; + } + class ClassificationTypeNames { + static comment: string; + static identifier: string; + static keyword: string; + static numericLiteral: string; + static operator: string; + static stringLiteral: string; + static whiteSpace: string; + static text: string; + static punctuation: string; + static className: string; + static enumName: string; + static interfaceName: string; + static moduleName: string; + static typeParameterName: string; + static typeAliasName: string; + static parameterName: string; + static docCommentTagName: string; + } + const enum ClassificationType { + comment = 1, + identifier = 2, + keyword = 3, + numericLiteral = 4, + operator = 5, + stringLiteral = 6, + regularExpressionLiteral = 7, + whiteSpace = 8, + text = 9, + punctuation = 10, + className = 11, + enumName = 12, + interfaceName = 13, + moduleName = 14, + typeParameterName = 15, + typeAliasName = 16, + parameterName = 17, + docCommentTagName = 18, + } + interface DisplayPartsSymbolWriter extends SymbolWriter { + displayParts(): SymbolDisplayPart[]; + } + function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function getDefaultCompilerOptions(): CompilerOptions; + interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + renamedDependencies?: Map; + } + interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; + function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; + function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; + let disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; + function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; + function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; + function createClassifier(): Classifier; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options: CompilerOptions): string; +} diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index e14bac94e..4fb680885 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -1,508 +1,508 @@ -/// - -declare var $: any; - -_.each([1, 2, 3], (num) => alert(num.toString())); -_.each({ one: 1, two: 2, three: 3 }, (value, key) => alert(value.toString())); - -_.map([1, 2, 3], (num) => num * 3); -_.map({ one: 1, two: 2, three: 3 }, (value, key) => value * 3); - -//var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); // https://typescript.codeplex.com/workitem/1960 -var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); -sum = _.reduce([1, 2, 3], (memo, num) => memo + num); // memo is optional #issue 5 github -sum = _.reduce({'a':'1', 'b':'2', 'c':'3'}, (memo, numstr) => memo + (+numstr)); - -var list = [[0, 1], [2, 3], [4, 5]]; -//var flat = _.reduceRight(list, (a, b) => a.concat(b), []); // https://typescript.codeplex.com/workitem/1960 -var flat = _.reduceRight(list, (a, b) => a.concat(b), []); - -module TestFind { - let array: {a: string}[] = [{a: 'a'}, {a: 'b'}]; - let list: _.List<{a: string}> = {0: {a: 'a'}, 1: {a: 'b'}, length: 2}; - let dict: _.Dictionary<{a: string}> = {a: {a: 'a'}, b: {a: 'b'}}; - let context = {}; - - { - let iterator = (value: {a: string}, index: number, list: _.List<{a: string}>) => value.a === 'b'; - let result: {a: string}; - - result = _.find<{a: string}>(array, iterator); - result = _.find<{a: string}>(array, iterator, context); - result = _.find<{a: string}, {a: string}>(array, {a: 'b'}); - result = _.find<{a: string}>(array, 'a'); - - result = _(array).find<{a: string}>(iterator); - result = _(array).find<{a: string}>(iterator, context); - result = _(array).find<{a: string}, {a: string}>({a: 'b'}); - result = _(array).find<{a: string}>('a'); - - result = _(array).chain().find<{a: string}>(iterator).value(); - result = _(array).chain().find<{a: string}>(iterator, context).value(); - result = _(array).chain().find<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(array).chain().find<{a: string}>('a').value(); - - result = _.find<{a: string}>(list, iterator); - result = _.find<{a: string}>(list, iterator, context); - result = _.find<{a: string}, {a: string}>(list, {a: 'b'}); - result = _.find<{a: string}>(list, 'a'); - - result = _(list).find<{a: string}>(iterator); - result = _(list).find<{a: string}>(iterator, context); - result = _(list).find<{a: string}, {a: string}>({a: 'b'}); - result = _(list).find<{a: string}>('a'); - - result = _(list).chain().find<{a: string}>(iterator).value(); - result = _(list).chain().find<{a: string}>(iterator, context).value(); - result = _(list).chain().find<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(list).chain().find<{a: string}>('a').value(); - - result = _.detect<{a: string}>(array, iterator); - result = _.detect<{a: string}>(array, iterator, context); - result = _.detect<{a: string}, {a: string}>(array, {a: 'b'}); - result = _.detect<{a: string}>(array, 'a'); - - result = _(array).detect<{a: string}>(iterator); - result = _(array).detect<{a: string}>(iterator, context); - result = _(array).detect<{a: string}, {a: string}>({a: 'b'}); - result = _(array).detect<{a: string}>('a'); - - result = _(array).chain().detect<{a: string}>(iterator).value(); - result = _(array).chain().detect<{a: string}>(iterator, context).value(); - result = _(array).chain().detect<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(array).chain().detect<{a: string}>('a').value(); - - result = _.detect<{a: string}>(list, iterator); - result = _.detect<{a: string}>(list, iterator, context); - result = _.detect<{a: string}, {a: string}>(list, {a: 'b'}); - result = _.detect<{a: string}>(list, 'a'); - - result = _(list).detect<{a: string}>(iterator); - result = _(list).detect<{a: string}>(iterator, context); - result = _(list).detect<{a: string}, {a: string}>({a: 'b'}); - result = _(list).detect<{a: string}>('a'); - - result = _(list).chain().detect<{a: string}>(iterator).value(); - result = _(list).chain().detect<{a: string}>(iterator, context).value(); - result = _(list).chain().detect<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(list).chain().detect<{a: string}>('a').value(); - } - - { - let iterator = (element: {a: string}, key: string, list: _.Dictionary<{a: string}>) => element.a === 'b'; - let result: {a: string}; - - result = _.find<{a: string}>(dict, iterator); - result = _.find<{a: string}>(dict, iterator, context); - result = _.find<{a: string}, {a: string}>(dict, {a: 'b'}); - result = _.find<{a: string}>(dict, 'a'); - - result = _(dict).find<{a: string}>(iterator); - result = _(dict).find<{a: string}>(iterator, context); - result = _(dict).find<{a: string}, {a: string}>({a: 'b'}); - result = _(dict).find<{a: string}>('a'); - - result = _(dict).chain().find<{a: string}>(iterator).value(); - result = _(dict).chain().find<{a: string}>(iterator, context).value(); - result = _(dict).chain().find<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(dict).chain().find<{a: string}>('a').value(); - - result = _.detect<{a: string}>(dict, iterator); - result = _.detect<{a: string}>(dict, iterator, context); - result = _.detect<{a: string}, {a: string}>(dict, {a: 'b'}); - result = _.detect<{a: string}>(dict, 'a'); - - result = _(dict).detect<{a: string}>(iterator); - result = _(dict).detect<{a: string}>(iterator, context); - result = _(dict).detect<{a: string}, {a: string}>({a: 'b'}); - result = _(dict).detect<{a: string}>('a'); - - result = _(dict).chain().detect<{a: string}>(iterator).value(); - result = _(dict).chain().detect<{a: string}>(iterator, context).value(); - result = _(dict).chain().detect<{a: string}, {a: string}>({a: 'b'}).value(); - result = _(dict).chain().detect<{a: string}>('a').value(); - } - - { - let iterator = (value: string, index: number, list: _.List) => value === 'b'; - let result: string; - - result = _.find('abc', iterator); - result = _.find('abc', iterator, context); - - result = _('abc').find(iterator); - result = _('abc').find(iterator, context); - - result = _('abc').chain().find(iterator).value(); - result = _('abc').chain().find(iterator, context).value(); - - result = _.detect('abc', iterator); - result = _.detect('abc', iterator, context); - - result = _('abc').detect(iterator); - result = _('abc').detect(iterator, context); - - result = _('abc').chain().detect(iterator).value(); - result = _('abc').chain().detect(iterator, context).value(); - } -} - -var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); - -var capitalLetters = _.filter({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); - -var listOfPlays = [{ title: "Cymbeline", author: "Shakespeare", year: 1611 }, { title: "The Tempest", author: "Shakespeare", year: 1611 }, { title: "Other", author: "Not Shakespeare", year: 2012 }]; -_.where(listOfPlays, { author: "Shakespeare", year: 1611 }); - -var odds = _.reject([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); - -_.every([true, 1, null, 'yes'], _.identity); - -_.any([null, 0, 'yes', false]); - -_.some([1, 2, 3, 4], l => l % 3 === 0); - -_.some({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); - -_.contains([1, 2, 3], 3); - -_.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); - -var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }]; -_.pluck(stooges, 'name'); - -_.max(stooges, (stooge) => stooge.age); -_.min(stooges, (stooge) => stooge.age); - -var numbers = [10, 5, 100, 2, 1000]; -_.max(numbers); -_.min(numbers); - -_.sortBy([1, 2, 3, 4, 5, 6], (num) => Math.sin(num)); - - -_([1.3, 2.1, 2.4]).groupBy((e) => Math.floor(e)); -_.groupBy([1.3, 2.1, 2.4], (num) => Math.floor(num).toString()); -_.groupBy(['one', 'two', 'three'], 'length'); - -_.indexBy(stooges, 'age')['40'].age; -_(stooges).indexBy('age')['40'].name; -_(stooges) - .chain() - .indexBy('age') - .value()['40'].age; - -_.countBy([1, 2, 3, 4, 5], (num) => (num % 2 == 0) ? 'even' : 'odd'); - -_.shuffle([1, 2, 3, 4, 5, 6]); - -(function (a, b, c, d) { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); - -_.size({ one: 1, two: 2, three: 3 }); - -_.partition([0, 1, 2, 3, 4, 5], (num) => {return num % 2 == 0 }); - -interface Family { - name: string; - relation: string; -} -var isUncleMoe = _.matches({ name: 'moe', relation: 'uncle' }); -_.filter([{ name: 'larry', relation: 'father' }, { name: 'moe', relation: 'uncle' }], isUncleMoe); - - - -/////////////////////////////////////////////////////////////////////////////////////// - -_.first([5, 4, 3, 2, 1]); -_.initial([5, 4, 3, 2, 1]); -_.last([5, 4, 3, 2, 1]); -_.rest([5, 4, 3, 2, 1]); -_.compact([0, 1, false, 2, '', 3]); - -_.flatten([1, 2, 3, 4]); -_.flatten([1, [2]]); - -// typescript doesn't like the elements being different -_.flatten([1, [2], [3, [[4]]]]); -_.flatten([1, [2], [3, [[4]]]], true); -_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); -_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); -_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); -_.difference([1, 2, 3, 4, 5], [5, 2, 10]); -_.uniq([1, 2, 1, 3, 1, 4]); -_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); -var r = _.object(['moe', 'larry', 'curly'], [30, 40, 50]); -_.object([['moe', 30], ['larry', 40], ['curly', 50]]); -_.indexOf([1, 2, 3], 2); -_.lastIndexOf([1, 2, 3, 1, 2, 3], 2); -_.sortedIndex([10, 20, 30, 40, 50], 35); -_.range(10); -_.range(1, 11); -_.range(0, 30, 5); -_.range(0, 30, 5); -_.range(0); - -/////////////////////////////////////////////////////////////////////////////////////// - -var func = function (greeting) { return greeting + ': ' + this.name }; -// need a second var otherwise typescript thinks func signature is the above func type, -// instead of the newly returned _bind => func type. -var func2 = _.bind(func, { name: 'moe' }, 'hi'); -func2(); - -var buttonView = { - label: 'underscore', - onClick: function () { alert('clicked: ' + this.label); }, - onHover: function () { console.log('hovering: ' + this.label); } -}; -_.bindAll(buttonView); -$('#underscore_button').bind('click', buttonView.onClick); - -var fibonacci = _.memoize(function (n) { - return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); -}); - -var log = _.bind(console.log, console); -_.delay(log, 1000, 'logged later'); - -_.defer(function () { alert('deferred'); }); - -var updatePosition = (param:string) => alert('updating position... Param: ' + param); -var throttled = _.throttle(updatePosition, 100); -$(window).scroll(throttled); - -var calculateLayout = (param:string) => alert('calculating layout... Param: ' + param); -var lazyLayout = _.debounce(calculateLayout, 300); -$(window).resize(lazyLayout); - -var createApplication = (param:string) => alert('creating application... Param: ' + param); -var initialize = _.once(createApplication); -initialize("me"); -initialize("me"); - -var notes: any[]; -var render = () => alert("rendering..."); -var renderNotes = _.after(notes.length, render); -_.each(notes, (note) => note.asyncSave({ success: renderNotes })); - -var hello = function (name) { return "hello: " + name; }; -// can't use the same "hello" var otherwise typescript fails -var hello2 = _.wrap(hello, (func) => { return "before, " + func("moe") + ", after"; }); -hello2(); - -var greet = function (name) { return "hi: " + name; }; -var exclaim = function (statement) { return statement + "!"; }; -var welcome = _.compose(exclaim, greet); -welcome('moe'); - -var partialApplicationTestFunction = (a: string, b: number, c: boolean, d: string, e: number, f: string) => { } -var partialApplicationResult = _.partial(partialApplicationTestFunction, "", 1); -var parametersCanBeStubbed = _.partial(partialApplicationResult, _, _, _, ""); - -/////////////////////////////////////////////////////////////////////////////////////// - -_.keys({ one: 1, two: 2, three: 3 }); -_.values({ one: 1, two: 2, three: 3 }); -_.pairs({ one: 1, two: 2, three: 3 }); -_.invert({ Moe: "Moses", Larry: "Louis", Curly: "Jerome" }); -_.functions(_); -_.extend({ name: 'moe' }, { age: 50 }); -_.extendOwn({ name: 'moe'}, { age: 50 }); -_.assign({ name: 'moe'}, { age: 50 }); -_.pick({ name: 'moe', age: 50, userid: 'moe1' }, 'name', 'age'); -_.omit({ name: 'moe', age: 50, userid: 'moe1' }, 'name'); -_.omit({ name: 'moe', age: 50, userid: 'moe1' }, 'name', 'age'); -_.omit({ name: 'moe', age: 50, userid: 'moe1' }, ['name', 'age']); - -_.mapObject({ a: 1, b: 2 }, val => val * 2) === _.mapObject({ a: 2, b: 4 }, _.identity); -_.mapObject({ a: 1, b: 2 }, (val, key, o) => o[key] * 2) === _.mapObject({ a: 2, b: 4}, _.identity); -_.mapObject({ x: "string 1", y: "string 2" }, 'length') === _.mapObject({ x: "string 1", y: "string 2"}, _.property('length')); - -var iceCream = { flavor: "chocolate" }; -_.defaults(iceCream, { flavor: "vanilla", sprinkles: "lots" }); - -_.clone({ name: 'moe' }); -_.clone(['i', 'am', 'an', 'object!']); - -_([1, 2, 3, 4]) - .chain() - .filter((num) => { return num % 2 == 0; }) - .tap(alert) - .map((num) => { return num * num; }) - .value(); - -_.chain([1, 2, 3, 200]) - .filter((num) => { return num % 2 == 0; }) - .tap(alert) - .map((num) => { return num * num; }) - .value(); - -_.has({ a: 1, b: 2, c: 3 }, "b"); - -var moe = { name: 'moe', luckyNumbers: [13, 27, 34] }; -var clone = { name: 'moe', luckyNumbers: [13, 27, 34] }; -moe == clone; -_.isEqual(moe, clone); - -_.isEmpty([1, 2, 3]); -_.isEmpty({}); - -_.isElement($('body')[0]); - -(function () { return _.isArray(arguments); })(); -_.isArray([1, 2, 3]); - -_.isObject({}); -_.isObject(1); - -_.property('name')(moe); - - -// (() => { return _.isArguments(arguments); })(1, 2, 3); -_.isArguments([1, 2, 3]); - -_.isFunction(alert); - -_.isString("moe"); - -_.isNumber(8.4 * 5); - -_.isFinite(-101); - -_.isFinite(-Infinity); - -_.isBoolean(null); - -_.isDate(new Date()); - -_.isRegExp(/moe/); - -_.isNaN(NaN); -isNaN(undefined); -_.isNaN(undefined); - -_.isNull(null); -_.isNull(undefined); - -_.isUndefined((window).missingVariable); - -/////////////////////////////////////////////////////////////////////////////////////// - -var UncleMoe = { name: 'moe' }; -_.constant(UncleMoe)(); - -typeof _.now() === "number"; - -var underscore = _.noConflict(); - -var moe2 = { name: 'moe' }; -moe2 === _.identity(moe); - -var genie; -var r2 = _.times(3, (n) => { return n * n }); -_(3).times(function (n) { genie.grantWishNumber(n); }); - -_.random(0, 100); - -_.mixin({ - capitalize: function (string) { - return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase(); - } -}); -(_("fabio")).capitalize(); - -_.uniqueId('contact_'); - -_.escape('Curly, Larry & Moe'); - -var object = { cheese: 'crumpets', stuff: function () { return 'nonsense'; } }; -_.result(object, 'cheese'); - -_.result(object, 'stuff'); - -var compiled = _.template("hello: <%= name %>"); -compiled({ name: 'moe' }); -var list2 = "<% _.each(people, function(name) { %>
      • <%= name %>
      • <% }); %>"; -_.template(list2)({ people: ['moe', 'curly', 'larry'] }); -var template = _.template("<%- value %>"); -template({ value: '