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-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/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/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/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/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/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/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/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/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.tscparams b/underscore/underscore-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/underscore/underscore-tests.ts.tscparams +++ b/underscore/underscore-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/unity-webapi/unity-webapi-tests.ts b/unity-webapi/unity-webapi-tests.ts index b1b8eb377..15703e2c9 100644 --- a/unity-webapi/unity-webapi-tests.ts +++ b/unity-webapi/unity-webapi-tests.ts @@ -1,58 +1,58 @@ -/// - -var Unity = external.getUnityObject(1.0); -var settings = new UnitySettings(); -Unity.init(settings); - -// Actions -Unity.addAction("boom", function() {}); -Unity.removeAction("boom"); -Unity.removeActions(); - -// Notification -Unity.Notification.showNotification("sum", "body"); -Unity.Notification.showNotification("sum", "body", "optional"); - -// Messaging -var props = new UnityIndicatorProperties(); -props.count = 0; -props.time = new Date(); - -Unity.MessagingIndicator.showIndicator("boom", props); -Unity.MessagingIndicator.clearIndicator("boom"); -Unity.MessagingIndicator.clearIndicators(); - -Unity.MessagingIndicator.addAction("boom", function() {}); -Unity.MessagingIndicator.removeAction("boom"); -Unity.MessagingIndicator.removeActions(); -Unity.MessagingIndicator.onPresenceChanged(function() {}); - -// Launcher -Unity.Launcher.setCount(1); -Unity.Launcher.clearCount(); - -Unity.Launcher.setProgress(100); -Unity.Launcher.clearProgress(); - -Unity.Launcher.setUrgent(true); - -Unity.Launcher.addAction("boom", function(){}); -Unity.Launcher.removeAction("boom"); -Unity.Launcher.removeActions(); - - -// MediaPlayer -var metadata = new UnityTrackMetadata(); -Unity.MediaPlayer.setTrack(metadata); - -Unity.MediaPlayer.onPrevious(function(){}); -Unity.MediaPlayer.onNext(function(){}); -Unity.MediaPlayer.onPlayPause(function(){}); - -Unity.MediaPlayer.getPlaybackstate(function(){}); -Unity.MediaPlayer.setPlaybackstate(UnityPlaybackState.Playing); - -Unity.MediaPlayer.setCanGoNext(true); -Unity.MediaPlayer.setCanGoPrev(true); -Unity.MediaPlayer.setCanPlay(true); +/// + +var Unity = external.getUnityObject(1.0); +var settings = new UnitySettings(); +Unity.init(settings); + +// Actions +Unity.addAction("boom", function() {}); +Unity.removeAction("boom"); +Unity.removeActions(); + +// Notification +Unity.Notification.showNotification("sum", "body"); +Unity.Notification.showNotification("sum", "body", "optional"); + +// Messaging +var props = new UnityIndicatorProperties(); +props.count = 0; +props.time = new Date(); + +Unity.MessagingIndicator.showIndicator("boom", props); +Unity.MessagingIndicator.clearIndicator("boom"); +Unity.MessagingIndicator.clearIndicators(); + +Unity.MessagingIndicator.addAction("boom", function() {}); +Unity.MessagingIndicator.removeAction("boom"); +Unity.MessagingIndicator.removeActions(); +Unity.MessagingIndicator.onPresenceChanged(function() {}); + +// Launcher +Unity.Launcher.setCount(1); +Unity.Launcher.clearCount(); + +Unity.Launcher.setProgress(100); +Unity.Launcher.clearProgress(); + +Unity.Launcher.setUrgent(true); + +Unity.Launcher.addAction("boom", function(){}); +Unity.Launcher.removeAction("boom"); +Unity.Launcher.removeActions(); + + +// MediaPlayer +var metadata = new UnityTrackMetadata(); +Unity.MediaPlayer.setTrack(metadata); + +Unity.MediaPlayer.onPrevious(function(){}); +Unity.MediaPlayer.onNext(function(){}); +Unity.MediaPlayer.onPlayPause(function(){}); + +Unity.MediaPlayer.getPlaybackstate(function(){}); +Unity.MediaPlayer.setPlaybackstate(UnityPlaybackState.Playing); + +Unity.MediaPlayer.setCanGoNext(true); +Unity.MediaPlayer.setCanGoPrev(true); +Unity.MediaPlayer.setCanPlay(true); Unity.MediaPlayer.setCanPause(true); \ No newline at end of file diff --git a/unity-webapi/unity-webapi-tests.ts.tscparams b/unity-webapi/unity-webapi-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/unity-webapi/unity-webapi-tests.ts.tscparams +++ b/unity-webapi/unity-webapi-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/unity-webapi/unity-webapi.d.ts.tscparams b/unity-webapi/unity-webapi.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/unity-webapi/unity-webapi.d.ts.tscparams +++ b/unity-webapi/unity-webapi.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/urlrouter/urlrouter-tests.ts b/urlrouter/urlrouter-tests.ts index 713b8cfe4..ceb7e27d4 100644 --- a/urlrouter/urlrouter-tests.ts +++ b/urlrouter/urlrouter-tests.ts @@ -1,19 +1,19 @@ -/// - -import http = require("http"); -import urlrouter = require("urlrouter"); - -var result = urlrouter((app) => { - app.get('/', (req, res, next) => { - res.end('hello urlrouter'); - }); - app.get('/user/:id([0-9]+)', (req, res, next) => { - res.end('hello user ' + req.params.id); - }); -}); - -var req: urlrouter.ServerRequest; -var res: urlrouter.ServerResponse; -function next() { } - -result(req, res, next); +/// + +import http = require("http"); +import urlrouter = require("urlrouter"); + +var result = urlrouter((app) => { + app.get('/', (req, res, next) => { + res.end('hello urlrouter'); + }); + app.get('/user/:id([0-9]+)', (req, res, next) => { + res.end('hello user ' + req.params.id); + }); +}); + +var req: urlrouter.ServerRequest; +var res: urlrouter.ServerResponse; +function next() { } + +result(req, res, next); diff --git a/uuid/UUID-tests.ts b/uuid/UUID-tests.ts index 0c6d5874e..3603ca81f 100644 --- a/uuid/UUID-tests.ts +++ b/uuid/UUID-tests.ts @@ -1,46 +1,46 @@ -/// -// Copied below from readme at https://github.com/LiosK/UUID.js - - - - -// the simplest way to get an UUID (as a hexadecimal string) -console.log(UUID.generate()); // "0db9a5fa-f532-4736-89d6-8819c7f3ac7b" - -// create a version 4 (random-numbers-based) UUID object -var objV4 = UUID.genV4(); - -// create a version 1 (time-based) UUID object -var objV1 = UUID.genV1(); - -// create an UUID object from a hexadecimal string -var uuid = UUID.parse("a0e0f130-8c21-11df-92d9-95795a3bcd40"); - - -// UUID object as a string -console.log(uuid.toString()); // "a0e0f130-8c21-11df-92d9-95795a3bcd40" -console.log(uuid.hexString); // "a0e0f130-8c21-11df-92d9-95795a3bcd40" -console.log(uuid.bitString); // "101000001110000 ... 1100110101000000" -console.log(uuid.urn); // "urn:uuid:a0e0f130-8c21-11df-92d9-95795a3bcd40" - -// compare UUID objects -console.log(objV4.equals(objV1)); // false - -// show version numbers -console.log(objV4.version); // 4 -console.log(objV1.version); // 1 - -// get UUID field values in 3 different formats by 2 different accessors -console.log(uuid.intFields.timeLow); // 2699096368 -console.log(uuid.bitFields.timeMid); // "1000110000100001" -console.log(uuid.hexFields.timeHiAndVersion); // "11df" -console.log(uuid.intFields.clockSeqHiAndReserved); // 146 -console.log(uuid.bitFields.clockSeqLow); // "11011001" -console.log(uuid.hexFields.node); // "95795a3bcd40" - -console.log(uuid.intFields[0]); // 2699096368 -console.log(uuid.bitFields[1]); // "1000110000100001" -console.log(uuid.hexFields[2]); // "11df" -console.log(uuid.intFields[3]); // 146 -console.log(uuid.bitFields[4]); // "11011001" -console.log(uuid.hexFields[5]); // "95795a3bcd40" +/// +// Copied below from readme at https://github.com/LiosK/UUID.js + + + + +// the simplest way to get an UUID (as a hexadecimal string) +console.log(UUID.generate()); // "0db9a5fa-f532-4736-89d6-8819c7f3ac7b" + +// create a version 4 (random-numbers-based) UUID object +var objV4 = UUID.genV4(); + +// create a version 1 (time-based) UUID object +var objV1 = UUID.genV1(); + +// create an UUID object from a hexadecimal string +var uuid = UUID.parse("a0e0f130-8c21-11df-92d9-95795a3bcd40"); + + +// UUID object as a string +console.log(uuid.toString()); // "a0e0f130-8c21-11df-92d9-95795a3bcd40" +console.log(uuid.hexString); // "a0e0f130-8c21-11df-92d9-95795a3bcd40" +console.log(uuid.bitString); // "101000001110000 ... 1100110101000000" +console.log(uuid.urn); // "urn:uuid:a0e0f130-8c21-11df-92d9-95795a3bcd40" + +// compare UUID objects +console.log(objV4.equals(objV1)); // false + +// show version numbers +console.log(objV4.version); // 4 +console.log(objV1.version); // 1 + +// get UUID field values in 3 different formats by 2 different accessors +console.log(uuid.intFields.timeLow); // 2699096368 +console.log(uuid.bitFields.timeMid); // "1000110000100001" +console.log(uuid.hexFields.timeHiAndVersion); // "11df" +console.log(uuid.intFields.clockSeqHiAndReserved); // 146 +console.log(uuid.bitFields.clockSeqLow); // "11011001" +console.log(uuid.hexFields.node); // "95795a3bcd40" + +console.log(uuid.intFields[0]); // 2699096368 +console.log(uuid.bitFields[1]); // "1000110000100001" +console.log(uuid.hexFields[2]); // "11df" +console.log(uuid.intFields[3]); // 146 +console.log(uuid.bitFields[4]); // "11011001" +console.log(uuid.hexFields[5]); // "95795a3bcd40" diff --git a/uuid/UUID.d.ts b/uuid/UUID.d.ts index 03aa3c216..d4bc33f02 100644 --- a/uuid/UUID.d.ts +++ b/uuid/UUID.d.ts @@ -1,88 +1,88 @@ -// Type definitions for UUID.js core-1.0 -// Project: https://github.com/LiosK/UUID.js -// Definitions by: Jason Jarrett -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module UUID { - - interface UUIDStatic { - - /** - * The simplest function to get an UUID string. - * @returns {string} A version 4 UUID string. - */ - generate(): string; - - /** - * Generates a version 4 {@link UUID}. - * @returns {UUID} A version 4 {@link UUID} object. - * @since 3.0 - */ - genV4(): UUID; - - - /** - * Generates a version 1 {@link UUID}. - * @returns {UUID} A version 1 {@link UUID} object. - * @since 3.0 - */ - genV1(): UUID; - - /** - * Converts hexadecimal UUID string to an {@link UUID} object. - * @param {string} strId UUID hexadecimal string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"). - * @returns {UUID} {@link UUID} object or null. - * @since 3.0 - */ - parse(uuid: string): UUID; - - - /** - * Re-initializes version 1 UUID state. - * @since 3.0 - */ - resetState(): void; - - /** - * Reinstalls {@link UUID.generate} method to emulate the interface of UUID.js version 2.x. - * @since 3.1 - * @deprecated Version 2.x. compatible interface is not recommended. - */ - makeBackwardCompatible(): void; - } - - interface UUIDArray extends Array { - timeLow: string; - timeMid: string; - timeHiAndVersion: string; - clockSeqHiAndReserved: string; - clockSeqLow: string; - node: string; - } - - interface UUID { - intFields: UUIDArray; - bitFields: UUIDArray; - hexFields: UUIDArray; - version: number; - bitString: string; - hexString: string; - urn: string; - - - /** - * Tests if two {@link UUID} objects are equal. - * @param {UUID} uuid - * @returns {bool} True if two {@link UUID} objects are equal. - */ - equals(uuid: UUID): boolean; - - /** - * Returns UUID string representation. - * @returns {string} {@link UUID#hexString}. - */ - toString(): string; - } -} - -declare var UUID: UUID.UUIDStatic; +// Type definitions for UUID.js core-1.0 +// Project: https://github.com/LiosK/UUID.js +// Definitions by: Jason Jarrett +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module UUID { + + interface UUIDStatic { + + /** + * The simplest function to get an UUID string. + * @returns {string} A version 4 UUID string. + */ + generate(): string; + + /** + * Generates a version 4 {@link UUID}. + * @returns {UUID} A version 4 {@link UUID} object. + * @since 3.0 + */ + genV4(): UUID; + + + /** + * Generates a version 1 {@link UUID}. + * @returns {UUID} A version 1 {@link UUID} object. + * @since 3.0 + */ + genV1(): UUID; + + /** + * Converts hexadecimal UUID string to an {@link UUID} object. + * @param {string} strId UUID hexadecimal string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"). + * @returns {UUID} {@link UUID} object or null. + * @since 3.0 + */ + parse(uuid: string): UUID; + + + /** + * Re-initializes version 1 UUID state. + * @since 3.0 + */ + resetState(): void; + + /** + * Reinstalls {@link UUID.generate} method to emulate the interface of UUID.js version 2.x. + * @since 3.1 + * @deprecated Version 2.x. compatible interface is not recommended. + */ + makeBackwardCompatible(): void; + } + + interface UUIDArray extends Array { + timeLow: string; + timeMid: string; + timeHiAndVersion: string; + clockSeqHiAndReserved: string; + clockSeqLow: string; + node: string; + } + + interface UUID { + intFields: UUIDArray; + bitFields: UUIDArray; + hexFields: UUIDArray; + version: number; + bitString: string; + hexString: string; + urn: string; + + + /** + * Tests if two {@link UUID} objects are equal. + * @param {UUID} uuid + * @returns {bool} True if two {@link UUID} objects are equal. + */ + equals(uuid: UUID): boolean; + + /** + * Returns UUID string representation. + * @returns {string} {@link UUID#hexString}. + */ + toString(): string; + } +} + +declare var UUID: UUID.UUIDStatic; diff --git a/viewporter/viewporter-tests.ts b/viewporter/viewporter-tests.ts index 9ce0be298..532f80335 100644 --- a/viewporter/viewporter-tests.ts +++ b/viewporter/viewporter-tests.ts @@ -1,175 +1,175 @@ -/// -/// -/// - -function test_map() { - viewporter.preventPageScroll = true; - var eventName = viewporter.ACTIVE ? 'viewportready' : "load"; - google.maps.event.addDomListener(window, eventName, function () { - var map = new google.maps.Map(document.getElementById("map"), { - zoom: 2, - center: new google.maps.LatLng(10, 0), - mapTypeId: google.maps.MapTypeId.ROADMAP - }); - window.addEventListener("resize", viewporter.refresh); - if (navigator.geolocation) { - navigator.geolocation.getCurrentPosition(function (position) { - map.setCenter(new google.maps.LatLng( - position.coords.latitude, - position.coords.longitude - )); - map.setZoom(14); - }); - } - }); -} - -function test_resize() { - viewporter.preventPageScroll = true; - document.addEventListener('DOMContentLoaded', function () { - // listen for "resize" events and trigger "refresh" method. - window.addEventListener("resize", function () { - viewporter.refresh(); - document.getElementById("events").innerHTML += "resize
        "; - }); - if (navigator.geolocation) { - function success(position) { - var coords = [position.coords.latitude, position.coords.longitude] - document.getElementById("coords").innerHTML = coords.join(", "); - } - navigator.geolocation.getCurrentPosition(success); - } - }); -} - -function test_swipey() { - function rainbow(numOfSteps, step) { - var r, g, b, h = step / numOfSteps, i = ~~(h * 6), f = h * 6 - i, q = 1 - f; - switch (i % 6) { - case 0: r = 1, g = f, b = 0; break; - case 1: r = q, g = 1, b = 0; break; - case 2: r = 0, g = 1, b = f; break; - case 3: r = 0, g = q, b = 1; break; - case 4: r = f, g = 0, b = 1; break; - case 5: r = 1, g = 0, b = q; break; - } - return [((~ ~(r * 255))), (~ ~(g * 255)), (~ ~(b * 255))]; - } - - function drawingPointer(context, color) { - var clickX = []; - var clickY = []; - var clickDrag = []; - - this.painting = false; - var timestamp = null; - - this.addPoint = function (x, y, dragging) { - clickX.push(x); - clickY.push(y); - clickDrag.push(dragging); - }; - this.start = function () { - this.clear(); - this.painting = true; - }; - this.clear = function () { - clickX = []; - clickY = []; - clickDrag = []; - timestamp = null; - }; - this.stop = function () { - this.painting = false; - timestamp = Date.now(); - }; - this.redraw = function () { - var opacity = timestamp ? (300 - (Date.now() - timestamp)) / 300 : 1; - if (opacity <= 0) { - this.clear(); - return; - } - context.strokeStyle = "rgba(" + color[0] + "," + color[1] + "," + color[2] + "," + opacity + ")"; - context.lineJoin = "round"; - context.lineWidth = ((window).devicePixelRatio || 1) * 5; - for (var i = 0; i < clickX.length; i++) { - context.beginPath(); - if (clickDrag[i] && i) { - context.moveTo(clickX[i - 1], clickY[i - 1]); - } else { - context.moveTo(clickX[i] - 1, clickY[i]); - } - context.lineTo(clickX[i], clickY[i]); - context.closePath(); - context.stroke(); - } - }; - }; - - $(window).bind(viewporter.ACTIVE ? 'viewportready' : 'load', function () { - var canvas = $('canvas')[0]; - var context = canvas.getContext('2d'); - var iOS = (/iphone|ipad/i).test(navigator.userAgent); - var pointers = {}; - // handle resizing / rotating of the viewport - var width, height; - $(window).bind(viewporter.ACTIVE ? 'viewportchange' : 'resize', function () { - width = canvas.width = window.innerWidth; - height = canvas.height = window.innerHeight - }).trigger(viewporter.ACTIVE ? 'viewportchange' : 'resize'); - $('canvas').bind(iOS ? 'touchstart' : 'mousedown', function (e) { - e.preventDefault(); - var touches = iOS ? (e.originalEvent).changedTouches : [e.originalEvent]; - var identifier; - for (var i = 0; i < touches.length; i++) { - identifier = touches[i].identifier || 'mouse'; - // if no pointer has been created for this finger yet, do it - if (!pointers[identifier]) { - pointers[identifier] = new drawingPointer(context, rainbow(8, Object.keys(pointers).length)); - } - pointers[identifier].start(); - pointers[identifier].addPoint(touches[i].pageX, touches[i].pageY); - } - }); - - $('canvas').bind(iOS ? 'touchmove' : 'mousemove', function (e) { - var touches = iOS ? (e.originalEvent).changedTouches : [e.originalEvent]; - var identifier; - for (var i = 0; i < touches.length; i++) { - identifier = touches[i].identifier || 'mouse'; - if (pointers[identifier] && pointers[identifier].painting) { - pointers[identifier].addPoint(touches[i].pageX, touches[i].pageY, true); - } - } - }); - - $('canvas').bind(iOS ? 'touchend' : 'mouseup', function (e) { - var touches = iOS ? (e.originalEvent).changedTouches : [e.originalEvent]; - var identifier; - for (var i = 0; i < touches.length; i++) { - identifier = touches[i].identifier || 'mouse'; - if (pointers[identifier]) { - pointers[identifier].stop(); - (function (identifier) { - setTimeout(function () { - delete pointers[identifier]; - }, 300); - })(identifier); - } - } - }); - - window.setInterval(function () { - context.clearRect(0, 0, width, height); - var counter = 0, ratio = (window).devicePixelRatio || 1; - for (var identifier in pointers) { - pointers[identifier].redraw(); - counter++; - } - context.font = (10 * ratio) + 'pt Arial'; - context.fillText(counter + ' active pointers', 15 * ratio, 25 * ratio); - - }, 16); - - }); +/// +/// +/// + +function test_map() { + viewporter.preventPageScroll = true; + var eventName = viewporter.ACTIVE ? 'viewportready' : "load"; + google.maps.event.addDomListener(window, eventName, function () { + var map = new google.maps.Map(document.getElementById("map"), { + zoom: 2, + center: new google.maps.LatLng(10, 0), + mapTypeId: google.maps.MapTypeId.ROADMAP + }); + window.addEventListener("resize", viewporter.refresh); + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition(function (position) { + map.setCenter(new google.maps.LatLng( + position.coords.latitude, + position.coords.longitude + )); + map.setZoom(14); + }); + } + }); +} + +function test_resize() { + viewporter.preventPageScroll = true; + document.addEventListener('DOMContentLoaded', function () { + // listen for "resize" events and trigger "refresh" method. + window.addEventListener("resize", function () { + viewporter.refresh(); + document.getElementById("events").innerHTML += "resize
        "; + }); + if (navigator.geolocation) { + function success(position) { + var coords = [position.coords.latitude, position.coords.longitude] + document.getElementById("coords").innerHTML = coords.join(", "); + } + navigator.geolocation.getCurrentPosition(success); + } + }); +} + +function test_swipey() { + function rainbow(numOfSteps, step) { + var r, g, b, h = step / numOfSteps, i = ~~(h * 6), f = h * 6 - i, q = 1 - f; + switch (i % 6) { + case 0: r = 1, g = f, b = 0; break; + case 1: r = q, g = 1, b = 0; break; + case 2: r = 0, g = 1, b = f; break; + case 3: r = 0, g = q, b = 1; break; + case 4: r = f, g = 0, b = 1; break; + case 5: r = 1, g = 0, b = q; break; + } + return [((~ ~(r * 255))), (~ ~(g * 255)), (~ ~(b * 255))]; + } + + function drawingPointer(context, color) { + var clickX = []; + var clickY = []; + var clickDrag = []; + + this.painting = false; + var timestamp = null; + + this.addPoint = function (x, y, dragging) { + clickX.push(x); + clickY.push(y); + clickDrag.push(dragging); + }; + this.start = function () { + this.clear(); + this.painting = true; + }; + this.clear = function () { + clickX = []; + clickY = []; + clickDrag = []; + timestamp = null; + }; + this.stop = function () { + this.painting = false; + timestamp = Date.now(); + }; + this.redraw = function () { + var opacity = timestamp ? (300 - (Date.now() - timestamp)) / 300 : 1; + if (opacity <= 0) { + this.clear(); + return; + } + context.strokeStyle = "rgba(" + color[0] + "," + color[1] + "," + color[2] + "," + opacity + ")"; + context.lineJoin = "round"; + context.lineWidth = ((window).devicePixelRatio || 1) * 5; + for (var i = 0; i < clickX.length; i++) { + context.beginPath(); + if (clickDrag[i] && i) { + context.moveTo(clickX[i - 1], clickY[i - 1]); + } else { + context.moveTo(clickX[i] - 1, clickY[i]); + } + context.lineTo(clickX[i], clickY[i]); + context.closePath(); + context.stroke(); + } + }; + }; + + $(window).bind(viewporter.ACTIVE ? 'viewportready' : 'load', function () { + var canvas = $('canvas')[0]; + var context = canvas.getContext('2d'); + var iOS = (/iphone|ipad/i).test(navigator.userAgent); + var pointers = {}; + // handle resizing / rotating of the viewport + var width, height; + $(window).bind(viewporter.ACTIVE ? 'viewportchange' : 'resize', function () { + width = canvas.width = window.innerWidth; + height = canvas.height = window.innerHeight + }).trigger(viewporter.ACTIVE ? 'viewportchange' : 'resize'); + $('canvas').bind(iOS ? 'touchstart' : 'mousedown', function (e) { + e.preventDefault(); + var touches = iOS ? (e.originalEvent).changedTouches : [e.originalEvent]; + var identifier; + for (var i = 0; i < touches.length; i++) { + identifier = touches[i].identifier || 'mouse'; + // if no pointer has been created for this finger yet, do it + if (!pointers[identifier]) { + pointers[identifier] = new drawingPointer(context, rainbow(8, Object.keys(pointers).length)); + } + pointers[identifier].start(); + pointers[identifier].addPoint(touches[i].pageX, touches[i].pageY); + } + }); + + $('canvas').bind(iOS ? 'touchmove' : 'mousemove', function (e) { + var touches = iOS ? (e.originalEvent).changedTouches : [e.originalEvent]; + var identifier; + for (var i = 0; i < touches.length; i++) { + identifier = touches[i].identifier || 'mouse'; + if (pointers[identifier] && pointers[identifier].painting) { + pointers[identifier].addPoint(touches[i].pageX, touches[i].pageY, true); + } + } + }); + + $('canvas').bind(iOS ? 'touchend' : 'mouseup', function (e) { + var touches = iOS ? (e.originalEvent).changedTouches : [e.originalEvent]; + var identifier; + for (var i = 0; i < touches.length; i++) { + identifier = touches[i].identifier || 'mouse'; + if (pointers[identifier]) { + pointers[identifier].stop(); + (function (identifier) { + setTimeout(function () { + delete pointers[identifier]; + }, 300); + })(identifier); + } + } + }); + + window.setInterval(function () { + context.clearRect(0, 0, width, height); + var counter = 0, ratio = (window).devicePixelRatio || 1; + for (var identifier in pointers) { + pointers[identifier].redraw(); + counter++; + } + context.font = (10 * ratio) + 'pt Arial'; + context.fillText(counter + ' active pointers', 15 * ratio, 25 * ratio); + + }, 16); + + }); } \ No newline at end of file diff --git a/viewporter/viewporter-tests.ts.tscparams b/viewporter/viewporter-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/viewporter/viewporter-tests.ts.tscparams +++ b/viewporter/viewporter-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/viewporter/viewporter.d.ts b/viewporter/viewporter.d.ts index 1e85cc5f6..9e8ac8b1d 100644 --- a/viewporter/viewporter.d.ts +++ b/viewporter/viewporter.d.ts @@ -1,18 +1,18 @@ -// Type definitions for Zynga Viewporter v2.1 -// Project: https://github.com/zynga/viewporter -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Viewporter { - preventPageScroll: boolean; - forceDetection: boolean; - ACTIVE: boolean; - READY: boolean; - - isLandscape(): boolean; - ready(callback: EventListener): void; - change(callback: EventListener): void; - refresh(): void; -} - -declare var viewporter: Viewporter; +// Type definitions for Zynga Viewporter v2.1 +// Project: https://github.com/zynga/viewporter +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Viewporter { + preventPageScroll: boolean; + forceDetection: boolean; + ACTIVE: boolean; + READY: boolean; + + isLandscape(): boolean; + ready(callback: EventListener): void; + change(callback: EventListener): void; + refresh(): void; +} + +declare var viewporter: Viewporter; diff --git a/vimeo/froogaloop.d.ts b/vimeo/froogaloop.d.ts index 3a68a6da4..61f58e284 100644 --- a/vimeo/froogaloop.d.ts +++ b/vimeo/froogaloop.d.ts @@ -1,28 +1,28 @@ -// Type definitions for Vimeo -// Project: http://developer.vimeo.com/player/js-api -// Definitions by: Daz Wilkin -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface VimeoParams { - name:string; - value:any; -} -interface VimeoPlayerAPI { - (method: string): any; - (method: string, callback: (value: any, player_id: any) =>void ): any; - (method: string, value: any): any; - (method: string, value: VimeoParams[]): any; -} -interface VimeoPlayer { - api: VimeoPlayerAPI; - addEvent(eventName: string, callback: (e: any) =>void ): any; - removeEvent(eventName: string): void; - postMessage(method: string, params:VimeoParams[], target): void; - onMessagReceived(event); - storeCallback(eventName: string, callback, target_id: string); - getCallback(eventName: string, target_id: string); - removeCallback(eventName: string, target_id: string); - getDomainFromUrl(url: string): string; -} - +// Type definitions for Vimeo +// Project: http://developer.vimeo.com/player/js-api +// Definitions by: Daz Wilkin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface VimeoParams { + name:string; + value:any; +} +interface VimeoPlayerAPI { + (method: string): any; + (method: string, callback: (value: any, player_id: any) =>void ): any; + (method: string, value: any): any; + (method: string, value: VimeoParams[]): any; +} +interface VimeoPlayer { + api: VimeoPlayerAPI; + addEvent(eventName: string, callback: (e: any) =>void ): any; + removeEvent(eventName: string): void; + postMessage(method: string, params:VimeoParams[], target): void; + onMessagReceived(event); + storeCallback(eventName: string, callback, target_id: string); + getCallback(eventName: string, target_id: string); + removeCallback(eventName: string, target_id: string); + getDomainFromUrl(url: string): string; +} + declare var $f: VimeoPlayerAPI; \ No newline at end of file diff --git a/vimeo/froogaloop.d.ts.tscparams b/vimeo/froogaloop.d.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/vimeo/froogaloop.d.ts.tscparams +++ b/vimeo/froogaloop.d.ts.tscparams @@ -1 +1 @@ - + diff --git a/vinyl-fs/vinyl-fs-tests.ts b/vinyl-fs/vinyl-fs-tests.ts index c8ca09070..09758e053 100644 --- a/vinyl-fs/vinyl-fs-tests.ts +++ b/vinyl-fs/vinyl-fs-tests.ts @@ -909,4 +909,15 @@ describe('symlink stream', function () { stream.end(); }); }); + it('should check if it"s a vinyl file', function () { + var srcPath = path.join(__dirname, './fixtures/test.coffee'); + var options = { + path: srcPath, + cwd: __dirname, + contents: new Buffer("1234567890") + }; + var file = new File(options); + File.isVinyl(file).should.equal(true); + File.isVinyl(options).should.equal(false); + }) }); diff --git a/vinyl-fs/vinyl-fs.d.ts b/vinyl-fs/vinyl-fs.d.ts index 70fc32aba..e06813243 100644 --- a/vinyl-fs/vinyl-fs.d.ts +++ b/vinyl-fs/vinyl-fs.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// /// declare module NodeJS { @@ -15,8 +16,9 @@ declare module NodeJS { declare module "vinyl-fs" { import _events = require("events"); import File = require("vinyl"); + import globStream = require("glob-stream"); - interface ISrcOptions { + interface ISrcOptions extends globStream.Options { /** Specifies the working directory the folder is relative to */ cwd?: string; diff --git a/vinyl/vinyl.d.ts b/vinyl/vinyl.d.ts index 77bf252b7..293ce5114 100644 --- a/vinyl/vinyl.d.ts +++ b/vinyl/vinyl.d.ts @@ -135,6 +135,11 @@ declare module "vinyl" { * Returns a pretty String interpretation of the File. Useful for console.log. */ public inspect(): string; + + /** + * Checks if a given object is a vinyl file. + */ + public static isVinyl(obj: any): boolean; } export = File; diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index c309a281b..a2f8f3f4b 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -1,47 +1,47 @@ -/// -var mediaStreamConstraints: MediaStreamConstraints = { audio: true, video: true }; - -var mediaTrackConstraintSet: MediaTrackConstraintSet = {}; -var mediaTrackConstraintArray: MediaTrackConstraintSet[] = []; -var mediaTrackConstraints: MediaTrackConstraints = mediaTrackConstraintSet; -var mediaTrackConstraints2: MediaTrackConstraints = { advanced: mediaTrackConstraintArray }; - -navigator.getUserMedia(mediaStreamConstraints, - stream => { - var track: MediaStreamTrack = stream.getTracks()[0]; - console.log('label:' + track.label); - console.log('ended:' + track.readyState); - track.onended = (event:Event) => console.log('Track ended'); - var objectUrl = URL.createObjectURL(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); - -navigator.webkitGetUserMedia(mediaStreamConstraints, - stream => { - var track: MediaStreamTrack = stream.getTracks()[0]; - console.log('label:' + track.label); - console.log('ended:' + track.readyState); - track.onended = (event:Event) => console.log('Track ended'); - var objectUrl = URL.createObjectURL(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); - - -navigator.mozGetUserMedia(mediaStreamConstraints, - stream => { - var track: MediaStreamTrack = stream.getTracks()[0]; - console.log('label:' + track.label); - console.log('ended:' + track.readyState); - track.onended = (event:Event) => console.log('Track ended'); - var objectUrl = URL.createObjectURL(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); +/// +var mediaStreamConstraints: MediaStreamConstraints = { audio: true, video: true }; + +var mediaTrackConstraintSet: MediaTrackConstraintSet = {}; +var mediaTrackConstraintArray: MediaTrackConstraintSet[] = []; +var mediaTrackConstraints: MediaTrackConstraints = mediaTrackConstraintSet; +var mediaTrackConstraints2: MediaTrackConstraints = { advanced: mediaTrackConstraintArray }; + +navigator.getUserMedia(mediaStreamConstraints, + stream => { + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); + var objectUrl = URL.createObjectURL(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); + +navigator.webkitGetUserMedia(mediaStreamConstraints, + stream => { + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); + var objectUrl = URL.createObjectURL(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); + + +navigator.mozGetUserMedia(mediaStreamConstraints, + stream => { + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); + var objectUrl = URL.createObjectURL(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); diff --git a/windows-service/windows-service-tests.ts b/windows-service/windows-service-tests.ts index 667a343d9..52ed0d91e 100644 --- a/windows-service/windows-service-tests.ts +++ b/windows-service/windows-service-tests.ts @@ -1,21 +1,21 @@ -/// - -import stream = require("stream"); -import service = require("windows-service"); - -service.add("MyService"); -service.add("MyService", {programPath: "./service.js"}); - -var s: stream.Writable; -var t: stream.Writable; - -service.run(s, (): void => { - service.stop(0); -}); - -service.run(s, t, (): void => { - service.stop(0); -}); - -service.remove("MyService"); - +/// + +import stream = require("stream"); +import service = require("windows-service"); + +service.add("MyService"); +service.add("MyService", {programPath: "./service.js"}); + +var s: stream.Writable; +var t: stream.Writable; + +service.run(s, (): void => { + service.stop(0); +}); + +service.run(s, t, (): void => { + service.stop(0); +}); + +service.remove("MyService"); + diff --git a/windows-service/windows-service.d.ts b/windows-service/windows-service.d.ts index a11666319..d5229d993 100644 --- a/windows-service/windows-service.d.ts +++ b/windows-service/windows-service.d.ts @@ -1,74 +1,74 @@ -// Type definitions for windows-service 1.0.4 -// Project: https://bitbucket.org/stephenwvickers/node-windows-service -// Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -declare module "windows-service" { - import stream = require("stream"); - - /** - * Options for the add() function. - */ - export interface AddOptions { - /** - * The services display name, defaults to the name parameter - */ - displayName?: string; - /** - * The fully qualified path to the node binary used to run the service (i.e. c:\Program Files\nodejs\node.exe, defaults to the value of process.execPath - */ - nodePath?: string; - /** - * An array of strings specifying parameters to pass to nodePath, defaults to [] - */ - nodeArgs?: string[]; - /** - * The program to run using nodePath, defaults to the value of process.argv[1] - */ - programPath?: string; - /** - * An array of strings specifying parameters to pass to programPath, defaults to [] - */ - programArgs?: string[]; - } - - /** - * The add() function adds a Windows service. The service will be set to automatically start at boot time, but not started. - * The service can be started using the net start "My Service" command. An exception will be thrown if the service could - * not be added. The error will be an instance of the Error class. - * - * @param name The name parameter specifies the name of the created service. - * @param opts Options - */ - export function add(name: string, opts?: AddOptions): void; - - - /** - * The remove() function removes a Windows service. - * The name parameter specifies the name of the service to remove. This will be the same name parameter specified when adding the service. - * The service must be in a stopped state for it to be removed. The net stop "My Service" command can be used to stop the service before - * it is to be removed. - * An exception will be thrown if the service could not be removed. The error will be an instance of the Error class. - */ - export function remove(name: string): void; - - /** - * The run() function will connect the calling program to the Windows Service Control Manager, allowing the program to run as a Windows service. - * The programs process.stdout stream will be replaced with the stdoutLogStream parameter, and the programs process.stderr stream replaced with - * the stdoutLogStream parameter (this allows the redirection of all console.log() type calls to a service specific log file). If the stderrLogStream - * parameter is not specified the programs process.stderr stream will be replaced with the stdoutLogStream parameter. The callback function will be - * called when the service receives a stop request, e.g. because the Windows Service Controller was used to send a stop request to the service. - * The program should perform cleanup tasks and then call the service.stop() function. - */ - export function run(stdoutLogStream: stream.Writable, callback: () => void): void; - export function run(stdoutLogStream: stream.Writable, stderrLogStream: stream.Writable, callback: () => void): void; - - /** - * The stop() function will cause the service to stop, and the calling program to exit. - * Once the service has been stopped this function will terminate the program by calling the process.exit() function, passing to it the rcode - * parameter which defaults to 0. Before calling this function ensure the program has finished performing cleanup tasks. - * BE AWARE, THIS FUNCTION WILL NOT RETURN. - */ - export function stop(rcode?: number): void; -} +// Type definitions for windows-service 1.0.4 +// Project: https://bitbucket.org/stephenwvickers/node-windows-service +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module "windows-service" { + import stream = require("stream"); + + /** + * Options for the add() function. + */ + export interface AddOptions { + /** + * The services display name, defaults to the name parameter + */ + displayName?: string; + /** + * The fully qualified path to the node binary used to run the service (i.e. c:\Program Files\nodejs\node.exe, defaults to the value of process.execPath + */ + nodePath?: string; + /** + * An array of strings specifying parameters to pass to nodePath, defaults to [] + */ + nodeArgs?: string[]; + /** + * The program to run using nodePath, defaults to the value of process.argv[1] + */ + programPath?: string; + /** + * An array of strings specifying parameters to pass to programPath, defaults to [] + */ + programArgs?: string[]; + } + + /** + * The add() function adds a Windows service. The service will be set to automatically start at boot time, but not started. + * The service can be started using the net start "My Service" command. An exception will be thrown if the service could + * not be added. The error will be an instance of the Error class. + * + * @param name The name parameter specifies the name of the created service. + * @param opts Options + */ + export function add(name: string, opts?: AddOptions): void; + + + /** + * The remove() function removes a Windows service. + * The name parameter specifies the name of the service to remove. This will be the same name parameter specified when adding the service. + * The service must be in a stopped state for it to be removed. The net stop "My Service" command can be used to stop the service before + * it is to be removed. + * An exception will be thrown if the service could not be removed. The error will be an instance of the Error class. + */ + export function remove(name: string): void; + + /** + * The run() function will connect the calling program to the Windows Service Control Manager, allowing the program to run as a Windows service. + * The programs process.stdout stream will be replaced with the stdoutLogStream parameter, and the programs process.stderr stream replaced with + * the stdoutLogStream parameter (this allows the redirection of all console.log() type calls to a service specific log file). If the stderrLogStream + * parameter is not specified the programs process.stderr stream will be replaced with the stdoutLogStream parameter. The callback function will be + * called when the service receives a stop request, e.g. because the Windows Service Controller was used to send a stop request to the service. + * The program should perform cleanup tasks and then call the service.stop() function. + */ + export function run(stdoutLogStream: stream.Writable, callback: () => void): void; + export function run(stdoutLogStream: stream.Writable, stderrLogStream: stream.Writable, callback: () => void): void; + + /** + * The stop() function will cause the service to stop, and the calling program to exit. + * Once the service has been stopped this function will terminate the program by calling the process.exit() function, passing to it the rcode + * parameter which defaults to 0. Before calling this function ensure the program has finished performing cleanup tasks. + * BE AWARE, THIS FUNCTION WILL NOT RETURN. + */ + export function stop(rcode?: number): void; +} diff --git a/winrt/winrt-uwp.d.ts b/winrt/winrt-uwp.d.ts index 4de542180..41dc1b0e1 100644 --- a/winrt/winrt-uwp.d.ts +++ b/winrt/winrt-uwp.d.ts @@ -630,6 +630,7 @@ declare namespace Windows { addEventListener(type: string, listener: Windows.Foundation.EventHandler): void; removeEventListener(type: string, listener: Windows.Foundation.EventHandler): void; } + /** Provides information about an event that occurs when the app is activated because a user tapped on the body of a toast notification or performed an action inside a toast notification. */ abstract class ToastNotificationActivatedEventArgs { /** Gets the arguments that the app can retrieve after it is activated through an interactive toast notification. */ argument: string; @@ -1015,7 +1016,7 @@ declare namespace Windows { */ getAppointmentAsync(localId: string): Windows.Foundation.IPromiseWithIAsyncOperation; /** - * + * (Applies to Windows Phone only) Asynchronously retrieves the Appointment with the specified ID and includes data for the specified properties. * @param localId The LocalId of the appointment to be retrieved. * @param prefetchProperties A list of names of the properties for which data should be included when the appointment is retrieved. * @return An asynchronous operation that returns Appointment on successful completion. @@ -1867,6 +1868,7 @@ declare namespace Windows { */ requestAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; } + /** (Applies to Windows Phone only) The details of an ApplicationTrigger . */ abstract class ApplicationTriggerDetails { /** The arguments that were passed to the background task using the ApplicationTrigger.RequestAsync(ValueSet) method. */ arguments: Windows.Foundation.Collections.ValueSet; @@ -2794,19 +2796,16 @@ declare namespace Windows { /** * Deletes entries in the store. * @param callHistoryEntries The entries to delete. - * @return */ deleteEntriesAsync(callHistoryEntries: Windows.Foundation.Collections.IIterable): any; /* unmapped return type */ /** * Delete an entry from the store. * @param callHistoryEntry The entry to delete. - * @return */ deleteEntryAsync(callHistoryEntry: Windows.ApplicationModel.Calls.PhoneCallHistoryEntry): any; /* unmapped return type */ /** * Gets an entry from the store based on the entry id. * @param callHistoryEntryId The PhoneCallHistoryEntryt.Id of the relevant entry. - * @return */ getEntryAsync(callHistoryEntryId: string): any; /* unmapped return type */ /** @@ -2833,31 +2832,26 @@ declare namespace Windows { getUnseenCountAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Update all the entries to indicate they have all been seen by the user. - * @return */ markAllAsSeenAsync(): any; /* unmapped return type */ /** * Updates entries to indicate they have been seen by the user. * @param callHistoryEntries The entries to mark as seen. This updates the PhoneCallHistoryEntry.IsSeen property. - * @return */ markEntriesAsSeenAsync(callHistoryEntries: Windows.Foundation.Collections.IIterable): any; /* unmapped return type */ /** * Updates an entry to indicate it has been seen. * @param callHistoryEntry The entry to update. - * @return */ markEntryAsSeenAsync(callHistoryEntry: Windows.ApplicationModel.Calls.PhoneCallHistoryEntry): any; /* unmapped return type */ /** * Marks all entries from the specified sources as seen. * @param sourceIds The list of source identifiers to mark as seen. Only entries that match PhoneCallHistoryEntry.SourceId will be updated. - * @return */ markSourcesAsSeenAsync(sourceIds: Windows.Foundation.Collections.IIterable): any; /* unmapped return type */ /** * Saves an entry to the store. * @param callHistoryEntry The entry to save. - * @return */ saveEntryAsync(callHistoryEntry: Windows.ApplicationModel.Calls.PhoneCallHistoryEntry): any; /* unmapped return type */ } @@ -5373,7 +5367,6 @@ declare namespace Windows { size: number; /** * Divides the object into two views - * @return */ split(): { /** The first half of the object. */ first: Windows.Foundation.Collections.IMapView; /** The second half of the object. */ second: Windows.Foundation.Collections.IMapView; }; /** Gets the source app's logo. */ @@ -6285,6 +6278,7 @@ declare namespace Windows { /** Enable sync for this folder. */ markFolderForSyncEnabled, } + /** Defines the type of negotiation on encryption algorithms permitted by the server. */ enum EmailMailboxAllowedSmimeEncryptionAlgorithmNegotiation { /** No negotiation is allowed. */ none, @@ -6349,6 +6343,7 @@ declare namespace Windows { /** Gets a Boolean value that indicates whether the email mailbox is capable of validating certificates. */ canValidateCertificates: boolean; } + /** The functionality described in this topic is not available to all Windows and Windows Phone apps. For your code to call these APIs, Microsoft must approve your use of them and provision your developer account. Otherwise the calls will fail at runtime. */ abstract class EmailMailboxChange { /** Gets the type of change that was made to the mailbox. This includes whether it was a folder or message that was changed and whether the item was created, deleted, or modified, or if change tracking was lost for this change. */ changeType: Windows.ApplicationModel.Email.EmailMailboxChangeType; @@ -6359,6 +6354,7 @@ declare namespace Windows { /** Gets the message to which the change applies. */ message: Windows.ApplicationModel.Email.EmailMessage; } + /** The functionality described in this topic is not available to all Windows and Windows Phone apps. For your code to call these APIs, Microsoft must approve your use of them and provision your developer account. Otherwise the calls will fail at runtime. */ abstract class EmailMailboxChangeReader { /** Accepts all changes. */ acceptChanges(): void; @@ -6373,6 +6369,7 @@ declare namespace Windows { */ readBatchAsync(): Windows.Foundation.IPromiseWithIAsyncOperation>; } + /** The functionality described in this topic is not available to all Windows and Windows Phone apps. For your code to call these APIs, Microsoft must approve your use of them and provision your developer account. Otherwise the calls will fail at runtime. */ abstract class EmailMailboxChangeTracker { /** Enables change tracking on a mailbox. */ enable(): void; @@ -6403,10 +6400,12 @@ declare namespace Windows { /** Change unknown because change tracking was lost. */ changeTrackingLost, } + /** Represents a deferred process that will halt a thread until the deferral is complete. */ abstract class EmailMailboxChangedDeferral { /** Indicates to waiting processes that the deferral is complete. */ complete(): void; } + /** Represents the deferral process. */ abstract class EmailMailboxChangedEventArgs { /** * Gets the deferral object. @@ -6521,6 +6520,7 @@ declare namespace Windows { /** Use Message Digest algorithm 5 (128-bit). */ md5, } + /** The functionality described in this topic is not available to all Windows and Windows Phone apps. For your code to call these APIs, Microsoft must approve your use of them and provision your developer account. Otherwise the calls will fail at runtime. */ abstract class EmailMailboxSyncManager { /** Gets the last time the mailbox attempted to sync. */ lastAttemptedSyncTime: Date; @@ -6903,6 +6903,7 @@ declare namespace Windows { /** This is the sent items folder. */ sent, } + /** The functionality described in this topic is not available to all Windows and Windows Phone apps. For your code to call these APIs, Microsoft must approve your use of them and provision your developer account. Otherwise the calls will fail at runtime. */ abstract class EmailStore { /** * Allows an app to create an email account from an account name and an email address. @@ -6978,6 +6979,7 @@ declare namespace Windows { /** Scope limited to read all data but only call write APIs that are on the mailbox and do not save. */ allMailboxesLimitedReadWrite, } + /** The functionality described in this topic is not available to all Windows and Windows Phone apps. For your code to call these APIs, Microsoft must approve your use of them and provision your developer account. Otherwise the calls will fail at runtime. */ abstract class EmailStoreNotificationTriggerDetails { } } @@ -7341,13 +7343,11 @@ declare namespace Windows { /** * Returns the ResourceCandidate objects that start at the specified index in the set. * @param startIndex The zero-based index of the start of the ResourceCandidate objects in the set to return. - * @return */ getMany(startIndex: number): { /** The ResourceCandidate objects in the set that start at startIndex. */ items: Windows.ApplicationModel.Resources.Core.ResourceCandidate; /** The number of ResourceCandidate objects returned. */ returnValue: number; }; /** * Returns the index of a specified ResourceCandidate in the set. * @param value The ResourceCandidate to find in the set. - * @return */ indexOf(value: Windows.ApplicationModel.Resources.Core.ResourceCandidate): { /** The zero-based index of the ResourceCandidate , if the item is found. The method returns zero if the item is not found. */ index: number; /** A Boolean that is TRUE if the ResourceCandidate is found, otherwise FALSE if the item is not found. */ returnValue: boolean; }; /** Gets the number of ResourceCandidate objects in the set. */ @@ -7433,13 +7433,11 @@ declare namespace Windows { /** * Returns the ResourceContext language qualifiers that start at the specified index in the set. * @param startIndex The zero-based index of the start of the ResourceContext language qualifiers in the set to return. - * @return */ getMany(startIndex: number): { /** The ResourceContext language qualifiers in the set that start at startIndex. */ items: string[]; /** The number of ResourceContext language qualifiers returned. */ returnValue: number; }; /** * Returns the index of a specified ResourceContext language qualifier in the set. * @param value The ResourceContext language qualifier to find in the set. - * @return */ indexOf(value: string): { /** The zero-based index of the ResourceContext language qualifier, if the item is found. The method returns zero if the item is not found. */ index: number; /** A Boolean that is TRUE if the ResourceContext language qualifier is found; otherwise, FALSE. */ returnValue: boolean; }; /** Gets the number of ResourceContext language qualifiers in the set. */ @@ -7530,7 +7528,6 @@ declare namespace Windows { size: number; /** * Splits the map view into two views. - * @return */ split(): { /** One half of the original map. */ first: Windows.Foundation.Collections.IMapView; /** The second half of the original map. */ second: Windows.Foundation.Collections.IMapView; }; /** Gets a URI that can be used to refer to this ResourceMap . */ @@ -7542,7 +7539,6 @@ declare namespace Windows { current: Windows.Foundation.Collections.IKeyValuePair; /** * Returns all the items in the ResourceMap . - * @return */ getMany(): { /** The items in the map. */ items: Windows.Foundation.Collections.IKeyValuePair; /** The number of items in the map. */ returnValue: number; }; /** Gets a value that indicates whether there is a current item, or whether the iterator is at the end of the ResourceMap . */ @@ -7576,7 +7572,6 @@ declare namespace Windows { size: number; /** * Splits the map view into two views. - * @return */ split(): { /** One half of the original map. */ first: Windows.Foundation.Collections.IMapView; /** The second half of the original map. */ second: Windows.Foundation.Collections.IMapView; }; } @@ -7586,7 +7581,6 @@ declare namespace Windows { current: Windows.Foundation.Collections.IKeyValuePair; /** * Returns all the items in the ResourceMapMapView . - * @return */ getMany(): { /** The items in the map view. */ items: Windows.Foundation.Collections.IKeyValuePair; /** The number of items in the map view. */ returnValue: number; }; /** Gets a value that indicates whether there is a current item, or whether the iterator is at the end of the ResourceMapMapView . */ @@ -7633,7 +7627,6 @@ declare namespace Windows { size: number; /** * Splits the map view into two views. - * @return */ split(): { /** One half of the original map. */ first: Windows.Foundation.Collections.IMapView; /** The second half of the original map. */ second: Windows.Foundation.Collections.IMapView; }; } @@ -7707,13 +7700,11 @@ declare namespace Windows { /** * Returns the ResourceQualifier objects that start at the specified index in the view. * @param startIndex The zero-based index of the start of the objects in the view to return. - * @return */ getMany(startIndex: number): { /** The objects in the view that start at startIndex. */ items: Windows.ApplicationModel.Resources.Core.ResourceQualifier; /** The number of objects returned. */ returnValue: number; }; /** * Returns the index of a specified ResourceQualifier in the view. * @param value The ResourceQualifier to find in the set. - * @return */ indexOf(value: Windows.ApplicationModel.Resources.Core.ResourceQualifier): { /** The zero-based index of the object, if found. The method returns zero if the object is not found. */ index: number; /** A Boolean that is TRUE if the object is found, otherwise FALSE if the object is not found. */ returnValue: boolean; }; /** Gets the number of ResourceQualifier objects in the view. */ @@ -9963,7 +9954,6 @@ declare namespace Windows { /** * Returns the high and low surrogate pair values for the specified supplementary Unicode character. * @param codepoint A Unicode character. This must be in the proper range: 0 <= codepoint <= 0x10FFFF. - * @return */ static getSurrogatePairFromCodepoint(codepoint: number): { /** The high surrogate value returned. */ highSurrogate: string; /** The low surrogate value returned. */ lowSurrogate: string; }; /** @@ -11592,7 +11582,6 @@ declare namespace Windows { /** * Returns the items that start at the specified index of the vector view. * @param startIndex The zero-based index of the start of the items in the vector to return. - * @return */ getMany(startIndex: number): { /** The items in the vector view that start at startIndex. */ items: Windows.Data.Xml.Dom.IXmlNode; /** The number of items returned. */ returnValue: number; }; /** @@ -11611,7 +11600,6 @@ declare namespace Windows { /** * Returns the index of a specified item in the vector view. * @param value The item to find in the vector view. - * @return */ indexOf(value: Windows.Data.Xml.Dom.IXmlNode): { /** The zero-based index of the item if found. Zero is returned if the item is not found. */ index: number; /** TRUE if the item is found; otherwise, FALSE if it is not found. */ returnValue: boolean; }; /** @@ -11668,13 +11656,11 @@ declare namespace Windows { /** * Returns the items that start at the specified index of the vector view. * @param startIndex The zero-based index of the start of the items in the vector to return. - * @return */ getMany(startIndex: number): { /** The items in the vector view that start at startIndex. */ items: Windows.Data.Xml.Dom.IXmlNode; /** The number of items returned. */ returnValue: number; }; /** * Returns the index of a specified item in the vector. * @param value The item to find in the vector. - * @return */ indexOf(value: Windows.Data.Xml.Dom.IXmlNode): { /** The zero-based index of the item if found. Zero is returned if the item is not found. */ index: number; /** TRUE if the item is found; otherwise, FALSE if the item is not found. */ returnValue: boolean; }; /** @@ -13155,7 +13141,7 @@ declare namespace Windows { /** Provides functionality to determine the Bluetooth Low Energy (LE) Appearance information for a device. */ abstract class BluetoothLEAppearance { /** - * + * Creates a BluetoothLEAppearance object by supplying values for Category (see BluetoothLEAppearanceCategories ) and Subcategory (see BluetoothLEAppearanceSubcategories ) of the Bluetooth LE device. * @param appearanceCategory The Bluetooth LE appearance category. See BluetoothLEAppearanceSubcategories . * @param appearanceSubCategory The Bluetooth LE appearance subcategory. See BluetoothLEAppearanceSubcategories . * @return The Bluetooth LE appearance object that was created from the appearance category and subcategory. @@ -13171,6 +13157,7 @@ declare namespace Windows { category: number; /** Gets the appearance raw value of the Bluetooth LE device. */ rawValue: number; + /** Gets the appearance subcategory value of the Bluetooth LE device. */ subCategory: number; } /** Indicates the appearance category code of the Bluetooth LE device. */ @@ -14586,13 +14573,11 @@ declare namespace Windows { /** * Gets a range of DeviceInformation objects. * @param startIndex The index at which to start retrieving DeviceInformation objects. - * @return */ getMany(startIndex: number): { /** The array of DeviceInformation objects starting at the index specified by startIndex. */ items: Windows.Devices.Enumeration.DeviceInformation; /** The number of DeviceInformation objects returned. */ returnValue: number; }; /** * Returns the index of the specified DeviceInformation object in the collection. * @param value The DeviceInformation object in the collection. - * @return */ indexOf(value: Windows.Devices.Enumeration.DeviceInformation): { /** The index. */ index: number; /** true if the method succeeded; otherwise, false. */ returnValue: boolean; }; /** The number of DeviceInformation objects in the collection. */ @@ -15136,13 +15121,11 @@ declare namespace Windows { /** * Retrieves multiple elements in a single pass through the iterator. * @param startIndex The index from which to start retrieval. - * @return */ getMany(startIndex: number): { /** Provides the destination for the result. Size the initial array size as a "capacity" in order to specify how many results should be retrieved. */ items: Windows.Devices.Enumeration.Pnp.PnpObject; /** The number of items retrieved. */ returnValue: number; }; /** * Retrieves the index of the specified item. * @param value The value to find in the collection. - * @return */ indexOf(value: Windows.Devices.Enumeration.Pnp.PnpObject): { /** The index of the item to find, if found. */ index: number; /** True if an item with the specified value was found; otherwise, False. */ returnValue: boolean; }; /** Returns the number of items in the collection. */ @@ -15759,7 +15742,6 @@ declare namespace Windows { * Opens the specified general-purpose I/O (GPIO) pin in the specified mode, and gets a status value that you can use to handle a failure to open the pin programmatically. * @param pinNumber The pin number of the GPIO pin that you want to open. Some pins may not be available in user mode. For information about how the pin numbers correspond to physical pins, see the documentation for your circuit board. * @param sharingMode The mode in which you want to open the GPIO pin, which determines whether other connections to the pin can be opened while you have the pin open. - * @return */ tryOpenPin(pinNumber: number, sharingMode: Windows.Devices.Gpio.GpioSharingMode): { /** The opened GPIO pin if the return value is true; otherwise null. */ pin: Windows.Devices.Gpio.GpioPin; /** An enumeration value that indicates either that the attempt to open the GPIO pin succeeded, or the reason that the attempt to open the GPIO pin failed. */ openStatus: Windows.Devices.Gpio.GpioOpenStatus; /** True if the method successfully opened the pin; otherwise false. */ returnValue: boolean; }; } @@ -17214,7 +17196,6 @@ declare namespace Windows { /** * This method returns the transform from the color frame source to the target entity and sets hasResult to true, if a correlation exists. If a correlation does not exist, hasResult is set to false and result is not modified. * @param targetId The unique ID of the target entity. - * @return */ tryGetTransformTo(targetId: string): { /** If a correlation exists, this will be set to a 4x4 transform matrix that changes basis from the color frame source coordinate system to the target entity coordinate system. */ result: Windows.Foundation.Numerics.Matrix4x4; /** Returns true if a correlation exists, otherwise false. */ returnValue: boolean; }; /** @@ -17289,7 +17270,6 @@ declare namespace Windows { /** * Unprojects all pixels in an image from camera image space out into the coordinate frame of the camera device, using the corresponding depth values from a correlated depth camera. * @param depthFrame The depth frame containing the depth value to use when projecting the points into camera space. The coordinates of each pixel in the image will be mapped from camera image space to depth image space, and then used to look up the depth in this depth frame. - * @return */ unprojectAllPixelsAtCorrelatedDepthAsync(depthFrame: Windows.Devices.Perception.PerceptionDepthFrame): { /** Returns a set of coordinates, relative to the coordinate system of the camera device and with correlated depth values. */ results: Windows.Foundation.Numerics.Vector3; /** This method returns asynchronously. */ returnValue: Windows.Foundation.IPromiseWithIAsyncAction; }; /** @@ -17310,7 +17290,6 @@ declare namespace Windows { * Unprojects a region of pixels in an image from camera image space out into the coordinate frame of the camera device, using the corresponding depth values from a correlated depth camera. * @param region The region of pixels to project from camera image space out into the coordinate frame of the camera device. * @param depthFrame The depth frame containing the depth value to use when projecting the points into camera space. The pixelCoordinates will be mapped from camera image space to depth image space, and then used to look up the depth in depthFrame. - * @return */ unprojectRegionPixelsAtCorrelatedDepthAsync(region: Windows.Foundation.Rect, depthFrame: Windows.Devices.Perception.PerceptionDepthFrame): { /** A set of coordinates, relative to the coordinate system of the camera device and with correlated depth values. */ results: Windows.Foundation.Numerics.Vector3; /** This method returns asynchronously. */ returnValue: Windows.Foundation.IPromiseWithIAsyncAction; }; } @@ -17319,7 +17298,6 @@ declare namespace Windows { /** * Maps all pixels in an image from camera image space to depth image space. * @param depthFrame The depth frame to map the pixels to. - * @return */ mapAllPixelsToTargetAsync(depthFrame: Windows.Devices.Perception.PerceptionDepthFrame): { /** Returns the pixel coordinates, mapped to depth image space. */ targetCoordinates: Windows.Foundation.Point; /** This function returns asynchronously. */ returnValue: Windows.Foundation.IPromiseWithIAsyncAction; }; /** @@ -17340,7 +17318,6 @@ declare namespace Windows { * Maps a region of pixels from camera image space to depth image space. * @param region The region of pixels to map from camera image space to depth image space. * @param depthFrame The depth frame to map the region of pixels to. - * @return */ mapRegionOfPixelsToTargetAsync(region: Windows.Foundation.Rect, depthFrame: Windows.Devices.Perception.PerceptionDepthFrame): { /** The pixel coordinates, mapped to depth image space. */ targetCoordinates: Windows.Foundation.Point; /** This function returns asynchronously. */ returnValue: Windows.Foundation.IPromiseWithIAsyncAction; }; } @@ -17483,7 +17460,6 @@ declare namespace Windows { /** * Gets the transform from the depth frame source to the target entity and sets hasResult to true, if a correlation exists. If a correlation does not exist, hasResult is set to false and result is not modified. * @param targetId The unique ID of the target entity. - * @return */ tryGetTransformTo(targetId: string): { /** If a correlation exists, this will be set to a 4x4 transform matrix that changes basis from the depth frame source coordinate system to the target entity coordinate system. */ result: Windows.Foundation.Numerics.Matrix4x4; /** True if a correlation exists, otherwise false. */ returnValue: boolean; }; /** @@ -17714,7 +17690,6 @@ declare namespace Windows { /** * Gets the transform from the infrared frame source to the target entity and sets hasResult to true, if a correlation exists. If a correlation does not exist, hasResult is set to false and result is not modified. * @param targetId The unique ID of the target entity. - * @return */ tryGetTransformTo(targetId: string): { /** If a correlation exists, this will be set to a 4x4 transform matrix that changes basis from the infrared frame source coordinate system to the target entity coordinate system. */ result: Windows.Foundation.Numerics.Matrix4x4; /** True if a correlation exists, otherwise false. */ returnValue: boolean; }; /** @@ -18646,7 +18621,6 @@ declare namespace Windows { /** * Puts the device into an authenticated state. * @param responseToken A buffer containing the response token generated from the challenge token retrieved from a previous call to the RetrieveDeviceAuthenticationDataAsync method. - * @return */ authenticateDeviceAsync(responseToken: number[]): any; /* unmapped return type */ /** Releases the exclusive claim to the magnetic strip reader. */ @@ -18656,7 +18630,6 @@ declare namespace Windows { /** * Puts the device into an unauthenticated state. * @param responseToken A buffer containing the response token generated from the challenge token retrieved from a previous call to the RetrieveDeviceAuthenticationDataAsync method. - * @return */ deAuthenticateDeviceAsync(responseToken: number[]): any; /* unmapped return type */ /** Gets the DeviceInformation.Id of the claimed magnetic stripe reader. */ @@ -18725,7 +18698,6 @@ declare namespace Windows { * Provides a new encryption key to the device. * @param key The HEX-ASCII or base64-encoded value for the new key. * @param keyName The name used to identify the key. - * @return */ updateKeyAsync(key: string, keyName: string): any; /* unmapped return type */ /** @@ -22978,7 +22950,6 @@ declare namespace Windows { /** * Retrieves the first 9 bytes of a USB configuration descriptor in a UsbConfigurationDescriptor object that is contained in a UsbDescriptor object. * @param descriptor The UsbDescriptor object to parse. - * @return */ static tryParse(descriptor: Windows.Devices.Usb.UsbDescriptor): { /** Receives a UsbConfigurationDescriptor object. */ parsed: Windows.Devices.Usb.UsbConfigurationDescriptor; /** True, if a UsbConfigurationDescriptor object was found in the specified UsbDescriptor object. Otherwise, false. */ returnValue: boolean; }; /** Gets the bConfigurationValue field of a USB configuration descriptor. The value is the number that identifies the configuration. */ @@ -23165,7 +23136,6 @@ declare namespace Windows { /** * Retrieves the USB endpoint descriptor in a UsbEndpointDescriptor object that is contained in a UsbDescriptor object. * @param descriptor The UsbDescriptor object to parse. - * @return */ static tryParse(descriptor: Windows.Devices.Usb.UsbDescriptor): { /** Receives a UsbEndpointDescriptor object. */ parsed: Windows.Devices.Usb.UsbEndpointDescriptor; /** True, if the specified UsbDescriptor object is a USB endpoint descriptor. Otherwise, false. */ returnValue: boolean; }; /** Gets an object that represents the endpoint descriptor for the USB bulk IN endpoint. */ @@ -23222,7 +23192,6 @@ declare namespace Windows { /** * Retrieves information about the alternate setting in a UsbInterfaceDescriptor object that is contained in a UsbDescriptor object. * @param descriptor The UsbDescriptor object to parse. - * @return */ static tryParse(descriptor: Windows.Devices.Usb.UsbDescriptor): { /** Receives a UsbInterfaceDescriptor object. */ parsed: Windows.Devices.Usb.UsbInterfaceDescriptor; /** True, if the specified UsbDescriptor object is USB interface descriptor. Otherwise, false. */ returnValue: boolean; }; /** Gets the bAlternateSetting field of the USB interface descriptor. The value is a number that identifies the alternate setting defined by the interface. */ @@ -24238,13 +24207,11 @@ declare namespace Windows { /** * Retrieves the items that start at the specified index in the vector view. * @param startIndex The zero-based index of the start of the items in the vector view. - * @return */ getMany(startIndex: number): { /** The items that start at startIndex in the vector view. */ items: T; /** The number of items retrieved. */ returnValue: number; }; /** * Retrieves the index of a specified item in the vector view. * @param value The item to find in the vector view. - * @return */ indexOf(value: T): { /** If the item is found, this is the zero-based index of the item; otherwise, this parameter is 0. */ index: number; /** true if the item is found; otherwise, false. */ returnValue: boolean; }; /** Gets the number of items in the vector view. */ @@ -24268,7 +24235,6 @@ declare namespace Windows { /** * Retrieves the items that start at the specified index in the vector. * @param startIndex The zero-based index of the start of the items in the vector. - * @return */ getMany(startIndex: number): { /** The items that start at startIndex in the vector. */ items: T; /** The number of items retrieved. */ returnValue: number; }; /** @@ -24279,7 +24245,6 @@ declare namespace Windows { /** * Retrieves the index of a specified item in the vector. * @param value The item to find in the vector. - * @return */ indexOf(value: T): { /** If the item is found, this is the zero-based index of the item; otherwise, this parameter is 0. */ index: number; /** true if the item is found; otherwise, false. */ returnValue: boolean; }; /** @@ -24333,7 +24298,6 @@ declare namespace Windows { lookup(key: K): V; /** * Splits the map view into two views. - * @return */ split(): { /** One half of the original map. */ first: Windows.Foundation.Collections.IMapView; /** The second half of the original map. */ second: Windows.Foundation.Collections.IMapView; }; /** Gets the number of elements in the map. */ @@ -24381,7 +24345,6 @@ declare namespace Windows { interface IIterator { /** * Retrieves all items in the collection. - * @return */ getMany(): { /** The items in the collection. */ items: T; /** The number of items in the collection. */ returnValue: number; }; /** @@ -25858,7 +25821,7 @@ declare namespace Windows { * Ends the current logging session and saves it to a file. * @return When this method completes, it returns the new file as a StorageFile . */ - closeAndSaveToFileAsync(): Windows.Foundation.IAsyncOperation; + closeAndSaveToFileAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Removes the specified logging channel from the current logging session. * @param loggingChannel The logging channel to remove. @@ -26400,13 +26363,11 @@ declare namespace Windows { /** * Gets name-value pairs starting at the specified index in the current URL query string. * @param startIndex The index to start getting name-value pairs at. - * @return */ getMany(startIndex: number): { /** The name-value pairs. */ items: Windows.Foundation.IWwwFormUrlDecoderEntry; /** The number of name-value pairs in items. */ returnValue: number; }; /** * Gets a value indicating whether the specified IWwwFormUrlDecoderEntry is at the specified index in the current URL query string. * @param value The name-value pair to get the index of. - * @return */ indexOf(value: Windows.Foundation.IWwwFormUrlDecoderEntry): { /** The position in value. */ index: number; /** true if value is at the position specified by index; otherwise, false. */ returnValue: boolean; }; /** Gets the number of the name-value pairs in the current URL query string. */ @@ -27377,13 +27338,11 @@ declare namespace Windows { /** * Returns the CharacterGrouping objects that start at the specified index in the set of character groups. * @param startIndex The zero-based index of the start of the CharacterGrouping objects in the set to return. - * @return */ getMany(startIndex: number): { /** The CharacterGrouping objects in the set that start at startIndex. */ items: Windows.Globalization.Collation.CharacterGrouping; /** The number of objects returned. */ returnValue: number; }; /** * Returns the index of a specified CharacterGrouping object in the set of character groups. * @param value The CharacterGrouping object to find in the set. - * @return */ indexOf(value: Windows.Globalization.Collation.CharacterGrouping): { /** The zero-based index of the CharacterGrouping object, if found. The method returns zero if the object is not found. */ index: number; /** True if the object is found, otherwise false. */ returnValue: boolean; }; /** @@ -28977,32 +28936,44 @@ declare namespace Windows { /** Specifies that the monitor rotated another 90 degrees in the clockwise direction (to equal 270 degrees) to orient the display in portrait mode where the height of the display viewing area is greater than the width. This portrait mode is flipped 180 degrees from the Portrait mode. */ portraitFlipped, } + /** Provides various properties that are related to the physical display. */ abstract class DisplayProperties { + /** Gets and sets the preferred orientation of the app. */ static autoRotationPreferences: Windows.Graphics.Display.DisplayOrientations; + /** Gets the current orientation of a rectangular monitor. */ static currentOrientation: Windows.Graphics.Display.DisplayOrientations; /** - * + * Asynchronously gets the default International Color Consortium (ICC) color profile that is associated with the physical display. * @return Object that manages the asynchronous retrieval of the color profile. */ static getColorProfileAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; + /** Gets the pixels per logical inch of the current environment. */ static logicalDpi: number; + /** Gets the native orientation of the display monitor, which is typically the orientation where the buttons on the device match the orientation of the monitor. */ static nativeOrientation: Windows.Graphics.Display.DisplayOrientations; + /** Occurs when the physical display's color profile changes. */ static oncolorprofilechanged: Windows.Graphics.Display.DisplayPropertiesEventHandler; static addEventListener(type: "colorprofilechanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; static removeEventListener(type: "colorprofilechanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; + /** Occurs when the display requires redrawing. */ static ondisplaycontentsinvalidated: Windows.Graphics.Display.DisplayPropertiesEventHandler; static addEventListener(type: "displaycontentsinvalidated", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; static removeEventListener(type: "displaycontentsinvalidated", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; + /** Occurs when the LogicalDpi property changes because the pixels per inch (PPI) of the display changes. */ static onlogicaldpichanged: Windows.Graphics.Display.DisplayPropertiesEventHandler; static addEventListener(type: "logicaldpichanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; static removeEventListener(type: "logicaldpichanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; + /** Occurs when either the CurrentOrientation or NativeOrientation property changes because of a mode change or a monitor change. */ static onorientationchanged: Windows.Graphics.Display.DisplayPropertiesEventHandler; static addEventListener(type: "orientationchanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; static removeEventListener(type: "orientationchanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; + /** Occurs when the StereoEnabled property changes because support for stereoscopic 3D changes. */ static onstereoenabledchanged: Windows.Graphics.Display.DisplayPropertiesEventHandler; static addEventListener(type: "stereoenabledchanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; static removeEventListener(type: "stereoenabledchanged", listener: Windows.Graphics.Display.DisplayPropertiesEventHandler): void; + /** Gets the scale factor of the immersive environment. */ static resolutionScale: Windows.Graphics.Display.ResolutionScale; + /** Gets a value that indicates whether the device supports stereoscopic 3D. */ static stereoEnabled: boolean; static addEventListener(type: string, listener: Windows.Foundation.EventHandler): void; static removeEventListener(type: string, listener: Windows.Foundation.EventHandler): void; @@ -29044,7 +29015,7 @@ declare namespace Windows { /** Specifies the scale of a display as 500 percent. */ scale500Percent, } - /** */ + /** Represents a method that handles display property events. */ type DisplayPropertiesEventHandler = (ev: WinRTEvent) => void; } namespace Effects { @@ -32775,6 +32746,7 @@ declare namespace Windows { /** Provides settings for capturing videos. The settings include format, maximum resolution, maximum duration, and whether or not to allow trimming. */ videoSettings: Windows.Media.Capture.CameraCaptureUIVideoCaptureSettings; } + /** Determines the highest resolution the user can select for capturing photos. */ enum CameraCaptureUIMaxPhotoResolution { /** The user can select any resolution. */ highestAvailable, @@ -35911,12 +35883,10 @@ declare namespace Windows { capabilities: Windows.Media.Devices.MediaDeviceControlCapabilities; /** * Indicates whether automatic adjustment of the camera setting is enabled. - * @return */ tryGetAuto(): { /** True if automatic adjustment is enabled; false otherwise. */ value: boolean; /** Returns true if the method succeeds, or false otherwise. */ returnValue: boolean; }; /** * Gets the value of the camera setting. - * @return */ tryGetValue(): { /** The current value of the setting. The units depend on the setting. */ value: number; /** Returns true if the method succeeds, or false otherwise. */ returnValue: boolean; }; /** @@ -36180,7 +36150,6 @@ declare namespace Windows { torchControl: Windows.Media.Devices.TorchControl; /** * Gets the local power line frequency. - * @return */ tryGetPowerlineFrequency(): { /** The power line frequency. */ value: Windows.Media.Capture.PowerlineFrequency; /** Returns true if the method succeeded, or false otherwise. */ returnValue: boolean; }; /** @@ -38634,13 +38603,11 @@ declare namespace Windows { /** * Retrieves the audio tracks that start at the specified index in the list. * @param startIndex The zero-based index of the start of the audio tracks in the list. - * @return */ getMany(startIndex: number): { /** The audio tracks that start at startIndex in the list. */ items: Windows.Media.Core.AudioTrack; /** The number of audio tracks retrieved. */ returnValue: number; }; /** * Retrieves the index of a specified audio track in the list. * @param value The audio track to find in the vector view. - * @return */ indexOf(value: Windows.Media.Core.AudioTrack): { /** If the audio track is found, this is the zero-based index of the audio track; otherwise, this parameter is 0. */ index: number; /** True if the audio track is found; otherwise, false. */ returnValue: boolean; }; /** Occurs when the index of the currently selected audio track changes. */ @@ -38793,7 +38760,6 @@ declare namespace Windows { /** * Retrieves the timed metadata tracks that start at the specified index in the list. * @param startIndex The zero-based index of the start of the timed metadata tracks in the list. - * @return */ getMany(startIndex: number): { /** The timed metadata tracks that start at startIndex in the list. */ items: Windows.Media.Core.TimedMetadataTrack; /** The number of timed metadata tracks retrieved. */ returnValue: number; }; /** @@ -38805,7 +38771,6 @@ declare namespace Windows { /** * Retrieves the index of a specified timed metadata track in the list. * @param value The timed metadata track to find in the vector view. - * @return */ indexOf(value: Windows.Media.Core.TimedMetadataTrack): { /** If the timed metadata track is found, this is the zero-based index of the audio track; otherwise, this parameter is 0. */ index: number; /** True if the timed metadata track is found; otherwise, false. */ returnValue: boolean; }; /** Occurs when the presentation mode of the MediaPlaybackTimedMetadataTrackList changes. */ @@ -38841,13 +38806,11 @@ declare namespace Windows { /** * Retrieves the video tracks that start at the specified index in the list. * @param startIndex The zero-based index of the start of the video tracks in the list. - * @return */ getMany(startIndex: number): { /** The video tracks that start at startIndex in the list. */ items: Windows.Media.Core.VideoTrack; /** The number of video tracks retrieved. */ returnValue: number; }; /** * Retrieves the index of a specified video track in the list. * @param value The video track to find in the vector view. - * @return */ indexOf(value: Windows.Media.Core.VideoTrack): { /** If the video track is found, this is the zero-based index of the audio track; otherwise, this parameter is 0. */ index: number; /** True if the video track is found; otherwise, false. */ returnValue: boolean; }; /** Occurs when the index of the currently selected video track changes. */ @@ -39667,7 +39630,6 @@ declare namespace Windows { current: Windows.Media.Protection.PlayReady.IPlayReadyDomain; /** * Retrieves all items in the PlayReady domain collection. - * @return */ getMany(): { /** The items in the collection. */ items: Windows.Media.Protection.PlayReady.IPlayReadyDomain; /** The number of items in the collection. */ returnValue: number; }; /** Gets a value that indicates whether there is a current item or the iterator is at the end of the PlayReady domain collection. */ @@ -39918,7 +39880,6 @@ declare namespace Windows { current: Windows.Media.Protection.PlayReady.IPlayReadyLicense; /** * Retrieves all items in the PlayReady license collection. - * @return */ getMany(): { /** The items in the collection. */ items: Windows.Media.Protection.PlayReady.IPlayReadyLicense; /** The number of items in the collection. */ returnValue: number; }; /** Gets a value that indicates whether there is a current item or the iterator is at the end of the PlayReady license collection. */ @@ -40049,7 +40010,6 @@ declare namespace Windows { current: Windows.Media.Protection.PlayReady.IPlayReadySecureStopServiceRequest; /** * Retrieves all items in the PlayReady secure stop collection. - * @return */ getMany(): { /** The items in the collection. */ items: Windows.Media.Protection.PlayReady.IPlayReadySecureStopServiceRequest; /** The number of items in the collection. */ returnValue: number; }; /** Gets a value that indicates whether there is a current item or the iterator is at the end of the PlayReady secure stop collection. */ @@ -40247,7 +40207,6 @@ declare namespace Windows { /** * Retrieves the stream type (audio or video) and stream identifier of the media stream descriptor. * @param descriptor The media stream from which this method gets information. - * @return */ getStreamInformation(descriptor: Windows.Media.Core.IMediaStreamDescriptor): { /** The type of the media stream. This type can be either Audio or Video. */ streamType: Windows.Media.Protection.PlayReady.NDMediaStreamType; /** The stream identifier for the media stream. */ returnValue: number; }; /** @@ -40266,7 +40225,7 @@ declare namespace Windows { * @param challengeDataBytes The data for the challenge message. * @return The result of the license fetch request. */ - sendLicenseFetchRequestAsync(sessionIDBytes: Array, challengeDataBytes: Array): Windows.Foundation.IAsyncOperation; + sendLicenseFetchRequestAsync(sessionIDBytes: Array, challengeDataBytes: Array): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Sends the specified data in an asynchronous proximity detection response message. * @param pdType The type of proximity detection operation. This value can be UDP, TCP, or Transport-Agnostic. @@ -40275,7 +40234,7 @@ declare namespace Windows { * @param responseDataBytes The data for the response message. * @return The result of the proximity detection response operation. */ - sendProximityDetectionResponseAsync(pdType: Windows.Media.Protection.PlayReady.NDProximityDetectionType, transmitterChannelBytes: Array, sessionIDBytes: Array, responseDataBytes: Array): Windows.Foundation.IAsyncOperation; + sendProximityDetectionResponseAsync(pdType: Windows.Media.Protection.PlayReady.NDProximityDetectionType, transmitterChannelBytes: Array, sessionIDBytes: Array, responseDataBytes: Array): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Sends the specified data in an asynchronous proximity detection start message. * @param pdType The type of proximity detection operation. This value can be UDP, TCP, or Transport-Agnostic. @@ -40284,14 +40243,14 @@ declare namespace Windows { * @param challengeDataBytes The data for the challenge message. * @return The result of the proximity detection start operation. */ - sendProximityDetectionStartAsync(pdType: Windows.Media.Protection.PlayReady.NDProximityDetectionType, transmitterChannelBytes: Array, sessionIDBytes: Array, challengeDataBytes: Array): Windows.Foundation.IAsyncOperation; + sendProximityDetectionStartAsync(pdType: Windows.Media.Protection.PlayReady.NDProximityDetectionType, transmitterChannelBytes: Array, sessionIDBytes: Array, challengeDataBytes: Array): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Sends the specified data in an asynchronous registration request message. * @param sessionIDBytes The session identifier. The session identifier must be 16 bytes. * @param challengeDataBytes The data for the challenge message. * @return The result of the license fetch request. */ - sendRegistrationRequestAsync(sessionIDBytes: Array, challengeDataBytes: Array): Windows.Foundation.IAsyncOperation; + sendRegistrationRequestAsync(sessionIDBytes: Array, challengeDataBytes: Array): Windows.Foundation.IPromiseWithIAsyncOperation; } /** Provides the result, in the form of a response message, from the PlayReady-ND messenger. */ interface INDSendResult { @@ -41615,7 +41574,7 @@ declare namespace Windows { */ static getCurrentDownloadsForTransferGroupAsync(group: Windows.Networking.BackgroundTransfer.BackgroundTransferGroup): Windows.Foundation.IPromiseWithIAsyncOperation>; /** - * + * Used to request an unconstrained download operation. When this method is called the user is provided with a UI prompt that they can use to indicate their consent for an unconstrained operation. * @param operations The download operation to run unconstrained. * @return Indicates if the operations will run unconstrained. */ @@ -41815,7 +41774,7 @@ declare namespace Windows { */ static getCurrentUploadsForTransferGroupAsync(group: Windows.Networking.BackgroundTransfer.BackgroundTransferGroup): Windows.Foundation.IPromiseWithIAsyncOperation>; /** - * + * Used to request an unconstrained upload operation. When this method is called the user is provided with a UI prompt that they can use to indicate their consent for an unconstrained operation. * @param operations The upload operation to run unconstrained. * @return Indicates if the operations will run unconstrained. */ @@ -42740,7 +42699,6 @@ declare namespace Windows { /** * Gets the context of an authentication attempt. * @param evenToken The event token retrieved from the network operator hotspot authentication event . The token is a GUID in string format. - * @return */ static tryGetAuthenticationContext(evenToken: string): { /** The network operator hotspot authentication context. */ context: Windows.Networking.NetworkOperators.HotspotAuthenticationContext; /** If true, the authentication context was retrieved. The authentication context can only be retrieved if the calling application matches the application ID specified in the hotspot profile of the underlying WLAN connection and if the authentication hasn’t be completed by the corresponding context already or timed out. */ returnValue: boolean; }; /** @@ -44213,13 +44171,11 @@ declare namespace Windows { /** * Gets multiple DnssdServiceInstance objects from a DNS-SD service instance collection. * @param startIndex Index of the first collection item to be retrieved. - * @return */ getMany(startIndex: number): { /** The retrieved DnssdServiceInstance objects. */ items: Windows.Networking.ServiceDiscovery.Dnssd.DnssdServiceInstance; /** The number of items in items. */ returnValue: number; }; /** * Gets a value indicating whether a given DnssdServiceInstance is at the specified index in this service instance collection. * @param value The DnssdServiceInstance to get the index of. - * @return */ indexOf(value: Windows.Networking.ServiceDiscovery.Dnssd.DnssdServiceInstance): { /** The index, if the DnssdServiceInstance is found. */ index: number; /** true if value is found at index, false otherwise. */ returnValue: boolean; }; /** Gets the number of items in the collection */ @@ -45024,7 +44980,7 @@ declare namespace Windows { * @param uri An absolute Uri for the server to connect to. * @return An asynchronous connect operation on a IWebSocket object. */ - connectAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IAsyncAction; + connectAsync(uri: Windows.Foundation.Uri): Windows.Foundation.IPromiseWithIAsyncAction; /** * Adds an HTTP request header to the HTTP request message used in the WebSocket protocol handshake by the IWebSocket object. * @param headerName The name of the request header. @@ -45215,7 +45171,6 @@ declare namespace Windows { getSnapshotAsBuffer(): Windows.Storage.Streams.IBuffer; /** * This API is not available to all apps. Unless your developer account is specially provisioned by Microsoft, calls to these APIs will fail at runtime. - * @return */ getSnapshotAsBytes(): { /** This API is not available to all apps. Unless your developer account is specially provisioned by Microsoft, calls to these APIs will fail at runtime. */ buffer: number[]; /** This API is not available to all apps. Unless your developer account is specially provisioned by Microsoft, calls to these APIs will fail at runtime. */ bytesWritten: number; }; /** This API is not available to all apps. Unless your developer account is specially provisioned by Microsoft, calls to these APIs will fail at runtime. */ @@ -46574,31 +46529,26 @@ declare namespace Windows { clear(): void; /** * This method is reserved for internal use and is not intended to be used in your code. - * @return */ first(): any; /* unmapped return type */ /** * This method is reserved for internal use and is not intended to be used in your code. - * @return */ getView(): any; /* unmapped return type */ /** * This method is reserved for internal use and is not intended to be used in your code. * @param key Reserved. - * @return */ hasKey(key: string): any; /* unmapped return type */ /** * This method is reserved for internal use and is not intended to be used in your code. * @param key Reserved. * @param value Reserved. - * @return */ insert(key: string, value: any): any; /* unmapped return type */ /** * This method is reserved for internal use and is not intended to be used in your code. * @param key Reserved. - * @return */ lookup(key: string): any; /* unmapped return type */ /** This method is reserved for internal use and is not intended to be used in your code. */ @@ -48977,13 +48927,11 @@ declare namespace Windows { /** * Retrieves the storage items that start at the specified index in the access list or most recently used (MRU) list. * @param startIndex The zero-based index of the start of the items in the collection to retrieve. - * @return */ getMany(startIndex: number): { /** The items in the collection that start at startIndex. */ items: Windows.Storage.AccessCache.AccessListEntry; /** The number of items retrieved. */ returnValue: number; }; /** * Retrieves the index of the specified storage item in the access list or most recently used (MRU) list. * @param value The storage item. - * @return */ indexOf(value: Windows.Storage.AccessCache.AccessListEntry): { /** The zero-based index of the storage item. */ index: number; /** True if the specified storage item exists in the list; otherwise false. */ returnValue: boolean; }; /** Gets the number of storage items in the access list or most recently used (MRU) list. */ @@ -50697,6 +50645,7 @@ declare namespace Windows { producers: Windows.Foundation.Collections.IVector; /** Gets or sets the publisher of the video. */ publisher: string; + /** Gets or sets the rating associated with a video file. */ rating: number; /** * Retrieves the specified properties associated with the item. @@ -50948,7 +50897,6 @@ declare namespace Windows { /** * Retrieves the file name extensions that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the file name extensions in the collection to retrieve. - * @return */ getMany(startIndex: number): { /** The file name extensions in the collection that start at startIndex. */ items: string[]; /** The number of items retrieved. */ returnValue: number; }; /** @@ -50959,7 +50907,6 @@ declare namespace Windows { /** * Retrieves the index of a specified file name extension in the collection. * @param value The file name extension to find in the collection. - * @return */ indexOf(value: string): { /** The zero-based index of the file name extension if found. This parameter is set to zero if the file name extension is not found. */ index: number; /** True if the file name extension is found; otherwise FALSE. */ returnValue: boolean; }; /** @@ -51086,13 +51033,11 @@ declare namespace Windows { /** * Retrieves the StorageFile objects that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the objects in the collection to return. - * @return */ getMany(startIndex: number): { /** The items in the collection that start at startIndex. */ items: Windows.Storage.StorageFile; /** The number of items returned. */ returnValue: number; }; /** * Retrieves the index of a specified StorageFile object in the collection. * @param value The object to find in the collection. - * @return */ indexOf(value: Windows.Storage.StorageFile): { /** The zero-based index of the object if found. Zero is returned if the object is not found. */ index: number; /** True if the object is found; otherwise false. */ returnValue: boolean; }; /** Gets the number of StorageFile objects in the collection. */ @@ -51528,7 +51473,6 @@ declare namespace Windows { /** * Adds app-defined items with properties and content to the system index. * @param indexableContent The content properties to index. - * @return */ addAsync(indexableContent: Windows.Storage.Search.IIndexableContent): any; /* unmapped return type */ /** @@ -51557,19 +51501,16 @@ declare namespace Windows { createQuery(searchFilter: string, propertiesToRetrieve: Windows.Foundation.Collections.IIterable): Windows.Storage.Search.ContentIndexerQuery; /** * Removes all app-defined items from the ContentIndexer . - * @return */ deleteAllAsync(): any; /* unmapped return type */ /** * Removes the specified app-defined item from the ContentIndexer . * @param contentId The identifier of the item to remove. - * @return */ deleteAsync(contentId: string): any; /* unmapped return type */ /** * Removes the specified app-defined items from the ContentIndexer . * @param contentIds The identifier of the item to remove. - * @return */ deleteMultipleAsync(contentIds: Windows.Foundation.Collections.IIterable): any; /* unmapped return type */ /** @@ -51584,7 +51525,6 @@ declare namespace Windows { /** * Updates app content and properties in the ContentIndexer . * @param indexableContent The content properties to update. - * @return */ updateAsync(indexableContent: Windows.Storage.Search.IIndexableContent): any; /* unmapped return type */ } @@ -51753,7 +51693,6 @@ declare namespace Windows { /** * Retrieves the sort entries that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the sort entries in the collection to retrieve. - * @return */ getMany(startIndex: number): { /** The sort entries in the collection that start at startIndex. */ items: Windows.Storage.Search.SortEntry; /** The number of items retrieved. */ returnValue: number; }; /** @@ -51764,7 +51703,6 @@ declare namespace Windows { /** * Retrieves the index of a specified sort entry in the collection. * @param value The sort entry to find in the collection. - * @return */ indexOf(value: Windows.Storage.Search.SortEntry): { /** The zero-based index of the sort entry, if found. This parameter is set to zero if the sort entry is not found. */ index: number; /** True if the sort entry is found; otherwise false. */ returnValue: boolean; }; /** @@ -51978,7 +51916,7 @@ declare namespace Windows { * @param value The property value to match when searching the query results. * @return When this method completes successfully it returns the index of the matched item in the query results. */ - findStartIndexAsync(value: any): Windows.Foundation.IAsyncOperation; + findStartIndexAsync(value: any): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Retrieves the query options used to create a StorageFileQueryResult , StorageFolderQueryResult , or StorageItemQueryResult object. * @return The query options. @@ -51988,7 +51926,7 @@ declare namespace Windows { * Retrieves the number of items that match the query that created a StorageFileQueryResult , StorageFolderQueryResult , or StorageItemQueryResult object. * @return When this method completes successfully, it returns the number of items that match the query. */ - getItemCountAsync(): Windows.Foundation.IAsyncOperation; + getItemCountAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; /** Gets the folder originally used to create a StorageFileQueryResult , StorageFolderQueryResult , or StorageItemQueryResult object. This folder represents the scope of the query. */ folder: Windows.Storage.StorageFolder; } @@ -53292,7 +53230,7 @@ declare namespace Windows { * Opens a stream for random access. * @return The asynchronous operation. */ - openReadAsync(): Windows.Foundation.IAsyncOperation; + openReadAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; } /** Supports random access of data in input and output streams for a specified data format. */ interface IRandomAccessStreamWithContentType extends Windows.Storage.Streams.IRandomAccessStream, Windows.Foundation.IClosable, Windows.Storage.Streams.IInputStream, Windows.Storage.Streams.IOutputStream, Windows.Storage.Streams.IContentTypeProvider {} @@ -53345,7 +53283,7 @@ declare namespace Windows { * @param options Specifies the type of the asynchronous read operation. * @return The asynchronous operation. */ - readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IAsyncOperationWithProgress; + readAsync(buffer: Windows.Storage.Streams.IBuffer, count: number, options: Windows.Storage.Streams.InputStreamOptions): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; } /** Represents a sequential stream of bytes to be written. */ interface IOutputStream extends Windows.Foundation.IClosable { @@ -53353,13 +53291,13 @@ declare namespace Windows { * Flushes data asynchronously in a sequential stream. * @return The stream flush operation. */ - flushAsync(): Windows.Foundation.IAsyncOperation; + flushAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Writes data asynchronously in a sequential stream. * @param buffer A buffer that contains the data to be written. * @return The byte writer operation. */ - writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IAsyncOperationWithProgress; + writeAsync(buffer: Windows.Storage.Streams.IBuffer): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; } /** Characterizes the format of the data. */ interface IContentTypeProvider { @@ -53372,7 +53310,7 @@ declare namespace Windows { * Opens a stream for sequential read access. * @return The asynchronous operation. */ - openSequentialReadAsync(): Windows.Foundation.IAsyncOperation; + openSequentialReadAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; } } /** A helper object that provides indexing names for Windows audio file properties. */ @@ -53490,17 +53428,17 @@ declare namespace Windows { * @param option A value that indicates whether to delete the item permanently. * @return No object or value is returned by this method when it completes. */ - deleteAsync(option: Windows.Storage.StorageDeleteOption): Windows.Foundation.IAsyncAction; + deleteAsync(option: Windows.Storage.StorageDeleteOption): Windows.Foundation.IPromiseWithIAsyncAction; /** * Deletes the current item. * @return No object or value is returned by this method when it completes. */ - deleteAsync(): Windows.Foundation.IAsyncAction; + deleteAsync(): Windows.Foundation.IPromiseWithIAsyncAction; /** * Gets the basic properties of the current item (like a file or folder). * @return When this method completes successfully, it returns the basic properties of the current item as a BasicProperties object. */ - getBasicPropertiesAsync(): Windows.Foundation.IAsyncOperation; + getBasicPropertiesAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Determines whether the current IStorageItem matches the specified StorageItemTypes value. * @param type The value to match against. @@ -53513,13 +53451,13 @@ declare namespace Windows { * @param option The enum value that determines how Windows responds if the desiredName is the same as the name of an existing item in the current item's location. * @return No object or value is returned by this method when it completes. */ - renameAsync(desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; + renameAsync(desiredName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IPromiseWithIAsyncAction; /** * Renames the current item. * @param desiredName The desired, new name of the item. * @return No object or value is returned by this method when it completes. */ - renameAsync(desiredName: string): Windows.Foundation.IAsyncAction; + renameAsync(desiredName: string): Windows.Foundation.IPromiseWithIAsyncAction; /** Gets the attributes of a storage item. */ attributes: Windows.Storage.FileAttributes; /** Gets the date and time when the current item was created. */ @@ -53536,7 +53474,7 @@ declare namespace Windows { * @param fileToReplace The file to replace. * @return No object or value is returned when this method completes. */ - copyAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; + copyAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IPromiseWithIAsyncAction; /** * Creates a copy of the file in the specified folder, using the desired name. This method also specifies what to do if an existing file in the specified folder has the same name. * @param destinationFolder The destination folder where the copy is created. @@ -53544,32 +53482,32 @@ declare namespace Windows { * @param option An enum value that determines how Windows responds if the desiredNewName is the same as the name of an existing file in the destination folder. * @return When this method completes, it returns a StorageFile that represents the copy. */ - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncOperation; + copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Creates a copy of the file in the specified folder, using the desired name. * @param destinationFolder The destination folder where the copy is created. * @param desiredNewName The desired name of the copy. * @return When this method completes, it returns a StorageFile that represents the copy. */ - copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncOperation; + copyAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Creates a copy of the file in the specified folder. * @param destinationFolder The destination folder where the copy is created. * @return When this method completes, it returns a StorageFile that represents the copy. */ - copyAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncOperation; + copyAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Moves the current file to the location of the specified file and replaces the specified file in that location. * @param fileToReplace The file to replace. * @return No object or value is returned by this method. */ - moveAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IAsyncAction; + moveAndReplaceAsync(fileToReplace: Windows.Storage.IStorageFile): Windows.Foundation.IPromiseWithIAsyncAction; /** * Moves the current file to the specified folder. * @param destinationFolder The destination folder where the file is moved. * @return No object or value is returned by this method. */ - moveAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IAsyncAction; + moveAsync(destinationFolder: Windows.Storage.IStorageFolder): Windows.Foundation.IPromiseWithIAsyncAction; /** * Moves the current file to the specified folder and renames the file according to the desired name. This method also specifies what to do if a file with the same name already exists in the specified folder. * @param destinationFolder The destination folder where the file is moved. @@ -53577,25 +53515,25 @@ declare namespace Windows { * @param option An enum value that determines how Windows responds if the desiredNewName is the same as the name of an existing file in the destination folder. * @return No object or value is returned by this method. */ - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IAsyncAction; + moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string, option: Windows.Storage.NameCollisionOption): Windows.Foundation.IPromiseWithIAsyncAction; /** * Moves the current file to the specified folder and renames the file according to the desired name. * @param destinationFolder The destination folder where the file is moved. * @param desiredNewName The desired name of the file after it is moved. * @return No object or value is returned by this method. */ - moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IAsyncAction; + moveAsync(destinationFolder: Windows.Storage.IStorageFolder, desiredNewName: string): Windows.Foundation.IPromiseWithIAsyncAction; /** * Opens a random-access stream over the file. * @param accessMode The type of access to allow. * @return When this method completes, it returns the random-access stream (type IRandomAccessStream ). */ - openAsync(accessMode: Windows.Storage.FileAccessMode): Windows.Foundation.IAsyncOperation; + openAsync(accessMode: Windows.Storage.FileAccessMode): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Opens a transacted, random-access stream for writing to the file. * @return When this method completes, it returns a StorageStreamTransaction that contains the random-access stream and methods that can be used to complete transactions. */ - openTransactedWriteAsync(): Windows.Foundation.IAsyncOperation; + openTransactedWriteAsync(): Windows.Foundation.IPromiseWithIAsyncOperation; /** Gets the MIME type of the contents of the file. */ contentType: string; /** Gets the type (file name extension) of the file. */ @@ -53609,59 +53547,59 @@ declare namespace Windows { * @param options The enum value that determines how Windows responds if the desiredName is the same as the name of an existing file in the current folder. * @return When this method completes, it returns the new file as a StorageFile . */ - createFileAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; + createFileAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Creates a new file in the current folder. * @param desiredName The desired name of the file to create. * @return When this method completes, it returns the new file as a StorageFile . */ - createFileAsync(desiredName: string): Windows.Foundation.IAsyncOperation; + createFileAsync(desiredName: string): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Creates a new folder in the current folder. * @param desiredName The desired name of the folder to create. * @return When this method completes, it returns the new folder as a StorageFolder . */ - createFolderAsync(desiredName: string): Windows.Foundation.IAsyncOperation; + createFolderAsync(desiredName: string): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Creates a new folder in the current folder, and specifies what to do if a folder with the same name already exists in the current folder. * @param desiredName The desired name of the folder to create. * @param options The enum value that determines how Windows responds if the desiredName is the same as the name of an existing folder in the current folder. * @return When this method completes, it returns the new folder as a StorageFolder . */ - createFolderAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IAsyncOperation; + createFolderAsync(desiredName: string, options: Windows.Storage.CreationCollisionOption): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Gets the specified file from the current folder. * @param name The name (or path relative to the current folder) of the file to retrieve. * @return When this method completes successfully, it returns a StorageFile that represents the file. */ - getFileAsync(name: string): Windows.Foundation.IAsyncOperation; + getFileAsync(name: string): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Gets the files from the current folder. * @return When this method completes successfully, it returns a list of the files (type IVectorView ) in the folder. Each file in the list is represented by a StorageFile object. */ - getFilesAsync(): Windows.Foundation.IAsyncOperation>; + getFilesAsync(): Windows.Foundation.IPromiseWithIAsyncOperation>; /** * Gets the specified folder from the current folder. * @param name The name of the child folder to retrieve. * @return When this method completes successfully, it returns a StorageFolder that represents the child folder. */ - getFolderAsync(name: string): Windows.Foundation.IAsyncOperation; + getFolderAsync(name: string): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Gets the folders in the current folder. * @return When this method completes successfully, it returns a list of the files (type IVectorView ). Each folder in the list is represented by a StorageFolder . */ - getFoldersAsync(): Windows.Foundation.IAsyncOperation>; + getFoldersAsync(): Windows.Foundation.IPromiseWithIAsyncOperation>; /** * Gets the specified item from the IStorageFolder . * @param name The name of the item to retrieve. * @return When this method completes successfully, it returns the file or folder (type IStorageItem ). */ - getItemAsync(name: string): Windows.Foundation.IAsyncOperation; + getItemAsync(name: string): Windows.Foundation.IPromiseWithIAsyncOperation; /** * Gets the items from the current folder. * @return When this method completes successfully, it returns a list of the files and folders (type IVectorView ). The files and folders in the list are represented by objects of type IStorageItem . */ - getItemsAsync(): Windows.Foundation.IAsyncOperation>; + getItemsAsync(): Windows.Foundation.IPromiseWithIAsyncOperation>; } /** Represents a method that handles the request to set the version of the application data in the application data store. */ type ApplicationDataSetVersionHandler = (setVersionRequest: Windows.Storage.SetVersionRequest) => void; @@ -54528,7 +54466,6 @@ declare namespace Windows { size: number; /** * Splits the map view into two views. - * @return */ split(): { /** The first part of the original map. */ first: Windows.Foundation.Collections.IMapView; /** The second part of the original map. */ second: Windows.Foundation.Collections.IMapView; }; } @@ -56944,7 +56881,6 @@ declare namespace Windows { /** * Attempts to perform the transformation on the specified input point. * @param inPoint The original input point. - * @return */ tryTransform(inPoint: Windows.Foundation.Point): { /** The transformed input point. */ outPoint: Windows.Foundation.Point; /** True if inPoint was transformed successfully; otherwise, false. */ returnValue: boolean; }; /** Gets the inverse of the specified transformation. */ @@ -60174,6 +60110,7 @@ declare namespace Windows { currentlyShownApplicationViewId: number; /** Gets the activation type. */ kind: Windows.ApplicationModel.Activation.ActivationKind; + /** (Applies to Windows only) Gets an indication about whether a pre-launch has been activated. */ prelaunchActivated: boolean; /** Gets the execution state of the app before this activation. */ previousExecutionState: Windows.ApplicationModel.Activation.ApplicationExecutionState; @@ -60886,7 +60823,7 @@ declare namespace Windows { * @param request The HTTP request message to send. * @return The object representing the asynchronous operation. */ - sendRequestAsync(request: Windows.Web.Http.HttpRequestMessage): Windows.Foundation.IAsyncOperationWithProgress; + sendRequestAsync(request: Windows.Web.Http.HttpRequestMessage): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; } } /** Provides support for HTTP headers used by the Windows.Web.Http namespace for Windows Store apps that target HTTP services. */ @@ -60914,7 +60851,6 @@ declare namespace Windows { /** * Retrieves the HttpNameValueHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpNameValueHeaderValue items in the HttpCacheDirectiveHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpNameValueHeaderValue items that start at startIndex in the HttpCacheDirectiveHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpNameValueHeaderValue; /** The number of HttpNameValueHeaderValue items retrieved. */ returnValue: number; }; /** @@ -60925,7 +60861,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpNameValueHeaderValue in the collection. * @param value The HttpNameValueHeaderValue to find in the HttpCacheDirectiveHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpNameValueHeaderValue): { /** The index of the HttpNameValueHeaderValue in the HttpCacheDirectiveHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -60998,7 +60933,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpChallengeHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpChallengeHeaderValue version of the string. */ challengeHeaderValue: Windows.Web.Http.Headers.HttpChallengeHeaderValue; /** true if input is valid HttpChallengeHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61042,7 +60976,6 @@ declare namespace Windows { /** * Retrieves the HttpChallengeHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpChallengeHeaderValue items in the HttpChallengeHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpChallengeHeaderValue items that start at startIndex in the HttpChallengeHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpChallengeHeaderValue; /** The number of HttpChallengeHeaderValue items retrieved. */ returnValue: number; }; /** @@ -61053,7 +60986,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpChallengeHeaderValue in the collection. * @param value The HttpChallengeHeaderValue to find in the HttpChallengeHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpChallengeHeaderValue): { /** The index of the HttpChallengeHeaderValue in the HttpChallengeHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -61118,7 +61050,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpConnectionOptionHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpConnectionOptionHeaderValue version of the string. */ connectionOptionHeaderValue: Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue; /** true if input is valid HttpConnectionOptionHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61152,7 +61083,6 @@ declare namespace Windows { /** * Retrieves the HttpConnectionOptionHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpConnectionOptionHeaderValue items in the HttpConnectionOptionHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpConnectionOptionHeaderValue items that start at startIndex in the HttpConnectionOptionHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue; /** The number of HttpConnectionOptionHeaderValue items retrieved. */ returnValue: number; }; /** @@ -61163,7 +61093,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpConnectionOptionHeaderValue in the collection. * @param value The HttpConnectionOptionHeaderValue to find in the HttpConnectionOptionHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue): { /** The index of the HttpConnectionOptionHeaderValue in the HttpConnectionOptionHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -61228,7 +61157,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpContentCodingHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpContentCodingHeaderValue version of the string. */ contentCodingHeaderValue: Windows.Web.Http.Headers.HttpContentCodingHeaderValue; /** true if input is valid HttpContentCodingHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61262,7 +61190,6 @@ declare namespace Windows { /** * Retrieves the HttpContentCodingHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpContentCodingHeaderValue items in the HttpContentCodingHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpContentCodingHeaderValue items that start at startIndex in the HttpContentCodingHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpContentCodingHeaderValue; /** The number of HttpContentCodingHeaderValue items retrieved. */ returnValue: number; }; /** @@ -61273,7 +61200,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpContentCodingHeaderValue in the collection. * @param value The HttpContentCodingHeaderValue to find in the HttpContentCodingHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpContentCodingHeaderValue): { /** The index of the HttpContentCodingHeaderValue in the HttpContentCodingHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -61338,7 +61264,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpContentCodingWithQualityHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpContentCodingWithQualityHeaderValue version of the string. */ contentCodingWithQualityHeaderValue: Windows.Web.Http.Headers.HttpContentCodingWithQualityHeaderValue; /** true if input is valid HttpContentCodingWithQualityHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61380,7 +61305,6 @@ declare namespace Windows { /** * Retrieves the HttpContentCodingWithQualityHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpContentCodingWithQualityHeaderValue items in the HttpContentCodingWithQualityHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpContentCodingWithQualityHeaderValue items that start at startIndex in the HttpContentCodingWithQualityHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpContentCodingWithQualityHeaderValue; /** The number of HttpContentCodingWithQualityHeaderValue items retrieved. */ returnValue: number; }; /** @@ -61391,7 +61315,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpContentCodingWithQualityHeaderValue in the collection. * @param value The HttpContentCodingWithQualityHeaderValue to find in the HttpContentCodingWithQualityHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpContentCodingWithQualityHeaderValue): { /** The index of the HttpContentCodingWithQualityHeaderValue in the HttpContentCodingWithQualityHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -61456,7 +61379,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpContentDispositionHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpContentDispositionHeaderValue version of the string. */ contentDispositionHeaderValue: Windows.Web.Http.Headers.HttpContentDispositionHeaderValue; /** true if input is valid HttpContentDispositionHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61570,7 +61492,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpContentRangeHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpContentRangeHeaderValue version of the string. */ contentRangeHeaderValue: Windows.Web.Http.Headers.HttpContentRangeHeaderValue; /** true if input is valid HttpContentRangeHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61611,7 +61532,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpCookiePairHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpCookiePairHeaderValue version of the string. */ cookiePairHeaderValue: Windows.Web.Http.Headers.HttpCookiePairHeaderValue; /** true if input is valid HttpCookiePairHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61653,7 +61573,6 @@ declare namespace Windows { /** * Retrieves the HttpCookiePairHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpCookiePairHeaderValue items in the HttpCookiePairHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpCookiePairHeaderValue items that start at startIndex in the HttpCookiePairHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpCookiePairHeaderValue; /** The number of HttpCookiePairHeaderValue items retrieved. */ returnValue: number; }; /** @@ -61664,7 +61583,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpCookiePairHeaderValue in the collection. * @param value The HttpCookiePairHeaderValue to find in the HttpCookiePairHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpCookiePairHeaderValue): { /** The index of the HttpCookiePairHeaderValue in the HttpCookiePairHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -61729,7 +61647,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpCredentialsHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpCredentialsHeaderValue version of the string. */ credentialsHeaderValue: Windows.Web.Http.Headers.HttpCredentialsHeaderValue; /** true if input is valid HttpCredentialsHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61761,7 +61678,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpDateOrDeltaHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpDateOrDeltaHeaderValue version of the string. */ dateOrDeltaHeaderValue: Windows.Web.Http.Headers.HttpDateOrDeltaHeaderValue; /** true if input is valid HttpDateOrDeltaHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** Gets the value of the HTTP-date information used in the Retry-After HTTP header. */ @@ -61780,7 +61696,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpCredentialsHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpExpectationHeaderValue version of the string. */ expectationHeaderValue: Windows.Web.Http.Headers.HttpExpectationHeaderValue; /** true if input is valid HttpExpectationHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -61824,7 +61739,6 @@ declare namespace Windows { /** * Retrieves the HttpExpectationHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpExpectationHeaderValue items in the HttpExpectationHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpExpectationHeaderValue items that start at startIndex in the HttpExpectationHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpExpectationHeaderValue; /** The number of items retrieved. */ returnValue: number; }; /** @@ -61835,7 +61749,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpExpectationHeaderValue in the collection. * @param value The HttpExpectationHeaderValue to find in the HttpExpectationHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpExpectationHeaderValue): { /** The index of the HttpExpectationHeaderValue in the HttpExpectationHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -61912,7 +61825,6 @@ declare namespace Windows { /** * Retrieves the Language items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the Language items in the HttpLanguageHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of Language items that start at startIndex in the HttpLanguageHeaderValueCollection . */ items: Windows.Globalization.Language; /** The number of items retrieved. */ returnValue: number; }; /** @@ -61923,7 +61835,6 @@ declare namespace Windows { /** * Retrieves the index of a Language in the collection. * @param value The item to find in the HttpLanguageHeaderValueCollection . - * @return */ indexOf(value: Windows.Globalization.Language): { /** The index of the Language item in the HttpLanguageHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -61988,7 +61899,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpLanguageRangeWithQualityHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpLanguageRangeWithQualityHeaderValue version of the string. */ languageRangeWithQualityHeaderValue: Windows.Web.Http.Headers.HttpLanguageRangeWithQualityHeaderValue; /** true if input is valid HttpLanguageRangeWithQualityHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -62030,7 +61940,6 @@ declare namespace Windows { /** * Retrieves the HttpLanguageRangeWithQualityHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpLanguageRangeWithQualityHeaderValue items in the HttpLanguageRangeWithQualityHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpLanguageRangeWithQualityHeaderValue items that start at startIndex in the HttpLanguageRangeWithQualityHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpLanguageRangeWithQualityHeaderValue; /** The number of items retrieved. */ returnValue: number; }; /** @@ -62041,7 +61950,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpLanguageRangeWithQualityHeaderValue in the collection. * @param value The HttpLanguageRangeWithQualityHeaderValue to find in the HttpLanguageRangeWithQualityHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpLanguageRangeWithQualityHeaderValue): { /** The index of the HttpLanguageRangeWithQualityHeaderValue in the HttpLanguageRangeWithQualityHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -62106,7 +62014,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpMediaTypeHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpMediaTypeHeaderValue version of the string. */ mediaTypeHeaderValue: Windows.Web.Http.Headers.HttpMediaTypeHeaderValue; /** true if input is valid HttpMediaTypeHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -62132,7 +62039,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpMediaTypeWithQualityHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpMediaTypeWithQualityHeaderValue version of the string. */ mediaTypeWithQualityHeaderValue: Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue; /** true if input is valid HttpMediaTypeWithQualityHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -62178,7 +62084,6 @@ declare namespace Windows { /** * Retrieves the HttpMediaTypeWithQualityHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpMediaTypeWithQualityHeaderValue items in the HttpMediaTypeWithQualityHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpMediaTypeWithQualityHeaderValue items that start at startIndex in the HttpMediaTypeWithQualityHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue; /** The number of items retrieved. */ returnValue: number; }; /** @@ -62189,7 +62094,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpMediaTypeWithQualityHeaderValue in the collection. * @param value The HttpMediaTypeWithQualityHeaderValue to find in the HttpMediaTypeWithQualityHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue): { /** The index of the HttpMediaTypeWithQualityHeaderValue in the HttpMediaTypeWithQualityHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -62266,7 +62170,6 @@ declare namespace Windows { /** * Retrieves the HttpMethod items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpMethod items in the HttpMethodHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpMethod items that start at startIndex in the HttpMethodHeaderValueCollection . */ items: Windows.Web.Http.HttpMethod; /** The number of items retrieved. */ returnValue: number; }; /** @@ -62277,7 +62180,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpMethod in the collection. * @param value The HttpMethod to find in the HttpMethodHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.HttpMethod): { /** The index of the HttpMethod in the HttpMethodHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -62342,7 +62244,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpNameValueHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpNameValueHeaderValue version of the string. */ nameValueHeaderValue: Windows.Web.Http.Headers.HttpNameValueHeaderValue; /** true if input is valid HttpNameValueHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -62372,7 +62273,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpProductHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpProductHeaderValue version of the string. */ productHeaderValue: Windows.Web.Http.Headers.HttpProductHeaderValue; /** true if input is valid HttpProductHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -62402,7 +62302,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpProductInfoHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpProductInfoHeaderValue version of the string. */ productInfoHeaderValue: Windows.Web.Http.Headers.HttpProductInfoHeaderValue; /** true if input is valid HttpProductInfoHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -62444,7 +62343,6 @@ declare namespace Windows { /** * Retrieves the HttpProductInfoHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpProductInfoHeaderValue items in the HttpProductInfoHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpProductInfoHeaderValue items that start at startIndex in the HttpProductInfoHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpProductInfoHeaderValue; /** The number of items retrieved. */ returnValue: number; }; /** @@ -62461,7 +62359,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpProductInfoHeaderValue in the collection. * @param value The HttpProductInfoHeaderValue to find in the HttpProductInfoHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpProductInfoHeaderValue): { /** The index of the HttpProductInfoHeaderValue in the HttpProductInfoHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -62696,7 +62593,6 @@ declare namespace Windows { /** * Determines whether a string is valid HttpTransferCodingHeaderValue information. * @param input The string to validate. - * @return */ static tryParse(input: string): { /** The HttpTransferCodingHeaderValue version of the string. */ transferCodingHeaderValue: Windows.Web.Http.Headers.HttpTransferCodingHeaderValue; /** true if input is valid HttpTransferCodingHeaderValue information; otherwise, false. */ returnValue: boolean; }; /** @@ -62732,7 +62628,6 @@ declare namespace Windows { /** * Retrieves the HttpTransferCodingHeaderValue items that start at the specified index in the collection. * @param startIndex The zero-based index of the start of the HttpTransferCodingHeaderValue items in the HttpTransferCodingHeaderValueCollection . - * @return */ getMany(startIndex: number): { /** An array of HttpTransferCodingHeaderValue items that start at startIndex in the HttpTransferCodingHeaderValueCollection . */ items: Windows.Web.Http.Headers.HttpTransferCodingHeaderValue; /** The number of items retrieved. */ returnValue: number; }; /** @@ -62755,7 +62650,6 @@ declare namespace Windows { /** * Retrieves the index of an HttpTransferCodingHeaderValue in the collection. * @param value The HttpTransferCodingHeaderValue to find in the HttpTransferCodingHeaderValueCollection . - * @return */ indexOf(value: Windows.Web.Http.Headers.HttpTransferCodingHeaderValue): { /** The index of the HttpTransferCodingHeaderValue in the HttpTransferCodingHeaderValueCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** @@ -62844,7 +62738,6 @@ declare namespace Windows { readAsStringAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Computes the HttpBufferContent length in bytes. - * @return */ tryComputeLength(): { /** The length in bytes of the HttpBufferContent . */ length: number; /** true if length is a valid length; otherwise, false. */ returnValue: boolean; }; /** @@ -62979,13 +62872,11 @@ declare namespace Windows { /** * Retrieves the HttpCookie items that start at the specified index in the HttpCookieCollection . * @param startIndex The zero-based index of the start of the HttpCookie items in the HttpCookieCollection . - * @return */ getMany(startIndex: number): { /** The HttpCookie items that start at startIndex in the HttpCookieCollection . */ items: Windows.Web.Http.HttpCookie; /** The number of HttpCookie items retrieved. */ returnValue: number; }; /** * Retrieves the index of an HttpCookie in the HttpCookieCollection . * @param value The HttpCookie to find in the HttpCookieCollection . - * @return */ indexOf(value: Windows.Web.Http.HttpCookie): { /** The index of the HttpCookie in the HttpCookieCollection . */ index: number; /** Indicates whether the item is found. */ returnValue: boolean; }; /** Gets the number of cookies in the HttpCookieCollection . */ @@ -63053,7 +62944,6 @@ declare namespace Windows { readAsStringAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Computes the HttpFormUrlEncodedContent length in bytes. - * @return */ tryComputeLength(): { /** The length in bytes of the HttpFormUrlEncodedContent . */ length: number; /** true if length is a valid length; otherwise, false. */ returnValue: boolean; }; /** @@ -63138,7 +63028,6 @@ declare namespace Windows { readAsStringAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Determines whether the HttpMultipartContent has a valid length in bytes. - * @return */ tryComputeLength(): { /** The length in bytes of the HttpMultipartContent . */ length: number; /** true if length is a valid length; otherwise, false. */ returnValue: boolean; }; /** @@ -63206,7 +63095,6 @@ declare namespace Windows { readAsStringAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Determines whether the HttpMultipartFormDataContent has a valid length in bytes. - * @return */ tryComputeLength(): { /** The length in bytes of the HttpMultipartFormDataContent . */ length: number; /** true if length is a valid length; otherwise, false. */ returnValue: boolean; }; /** @@ -63458,7 +63346,6 @@ declare namespace Windows { readAsStringAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Determines whether the HttpStreamContent has a valid length in bytes. - * @return */ tryComputeLength(): { /** The length in bytes of the HttpStreamContent . */ length: number; /** true if length is a valid length; otherwise, false. */ returnValue: boolean; }; /** @@ -63514,7 +63401,6 @@ declare namespace Windows { readAsStringAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Compute the HttpStringContent length in bytes. - * @return */ tryComputeLength(): { /** The length in bytes of the HttpStringContent . */ length: number; /** true if length is a valid length; otherwise, false. */ returnValue: boolean; }; /** @@ -63567,25 +63453,24 @@ declare namespace Windows { * Serialize the HTTP content into memory as an asynchronous operation. * @return The object that represents the asynchronous operation. */ - bufferAllAsync(): Windows.Foundation.IAsyncOperationWithProgress; + bufferAllAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Serialize the HTTP content to a buffer as an asynchronous operation. * @return The object representing the asynchronous operation. */ - readAsBufferAsync(): Windows.Foundation.IAsyncOperationWithProgress; + readAsBufferAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Serialize the HTTP content and return an input stream that represents the content as an asynchronous operation. * @return The object representing the asynchronous operation. */ - readAsInputStreamAsync(): Windows.Foundation.IAsyncOperationWithProgress; + readAsInputStreamAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Serialize the HTTP content to a String as an asynchronous operation. * @return The object representing the asynchronous operation. */ - readAsStringAsync(): Windows.Foundation.IAsyncOperationWithProgress; + readAsStringAsync(): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** * Determines whether the HTTP content has a valid length in bytes. - * @return */ tryComputeLength(): { /** The length in bytes of the HTTP content. */ length: number; /** true if length is a valid length; otherwise, false. */ returnValue: boolean; }; /** @@ -63593,7 +63478,7 @@ declare namespace Windows { * @param outputStream The output stream to write to. * @return The object representing the asynchronous operation. */ - writeToStreamAsync(outputStream: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IAsyncOperationWithProgress; + writeToStreamAsync(outputStream: Windows.Storage.Streams.IOutputStream): Windows.Foundation.IPromiseWithIAsyncOperationWithProgress; /** Get a collection of content headers set on the IHttpContent . */ headers: Windows.Web.Http.Headers.HttpContentHeaderCollection; } diff --git a/wiredep/wiredep-tests.ts b/wiredep/wiredep-tests.ts index 4a8313bd6..4fa5659b0 100644 --- a/wiredep/wiredep-tests.ts +++ b/wiredep/wiredep-tests.ts @@ -1,17 +1,17 @@ -/// -/// - -import gulp = require('gulp'); -import wiredep = require('wiredep'); - -gulp.task('bower', function () { - gulp.src('./src/footer.html') - .pipe(wiredep.stream({ - cwd:'.', - overrides:{ - optional: 'configuration', - goes: 'here' - } - })) - .pipe(gulp.dest('./dest')); +/// +/// + +import gulp = require('gulp'); +import wiredep = require('wiredep'); + +gulp.task('bower', function () { + gulp.src('./src/footer.html') + .pipe(wiredep.stream({ + cwd:'.', + overrides:{ + optional: 'configuration', + goes: 'here' + } + })) + .pipe(gulp.dest('./dest')); }); \ No newline at end of file diff --git a/xpath/xpath-tests.ts b/xpath/xpath-tests.ts index c20088b9e..24e0eac1b 100644 --- a/xpath/xpath-tests.ts +++ b/xpath/xpath-tests.ts @@ -1,76 +1,76 @@ -/// - -import xpath = require('xpath'); - -// A string of xml -var xml: string; -// an xpath query -var xpathText: string; -// a DOM -var doc: Document; -// xpath returns lists of Nodes that do not implement the NodeList interface; -// they are merely arrays. -var nodes: Array; -var node: Node; -var stringResult: string; -var booleanResult: boolean; -var numberResult: number; -var expression: xpath.XPathExpression; -var namespaceResolver: xpath.XPathNSResolver; -var xpathResult: xpath.XPathResult; -var length: number; - -xml = 'xml'; -xpathText = '//this/is/an/xpath/query'; -doc = new DOMParser().parseFromString(xml, 'text/xml'); -nodes = xpath.select(xpathText, doc); -node = xpath.select(xpathText, doc, true); -nodes = xpath.select(xpathText, doc, false); - -node = xpath.select1(xpathText, doc); - -stringResult = xpath.select(xpathText, doc).toString(); - -node = xpath.select(xpathText, doc)[0]; - -var selectFn = xpath.useNamespaces({ - 'prefix': 'http://namespaceuri.com/nsfile' -}); -nodes = selectFn(xpathText, doc); -node = selectFn(xpathText, doc, true); -nodes = selectFn(xpathText, doc, false); - -namespaceResolver = { - lookupNamespaceURI: function(prefix) { - return 'http://namespace.domain' - } -}; -expression = xpath.createExpression(xpathText, namespaceResolver); -xpathResult = expression.evaluate(doc, xpath.XPathResult.ANY_TYPE, null); -xpathResult = expression.evaluate(doc, xpath.XPathResult.ANY_TYPE, xpathResult); -xpathResult = expression.evaluate(doc, xpath.XPathResult.ANY_TYPE); -booleanResult = xpathResult.booleanValue; -numberResult = xpathResult.numberValue; -stringResult = xpathResult.stringValue; -node = xpathResult.singleNodeValue; -node = xpathResult.iterateNext(); -node = xpathResult.snapshotItem(10); -length = xpathResult.snapshotLength; - -var arrayOfNumbers: Array = [ - xpath.XPathResult.ANY_TYPE, - xpath.XPathResult.NUMBER_TYPE, - xpath.XPathResult.STRING_TYPE, - xpath.XPathResult.BOOLEAN_TYPE, - xpath.XPathResult.UNORDERED_NODE_ITERATOR_TYPE, - xpath.XPathResult.ORDERED_NODE_ITERATOR_TYPE, - xpath.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, - xpath.XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, - xpath.XPathResult.ANY_UNORDERED_NODE_TYPE, - xpath.XPathResult.FIRST_ORDERED_NODE_TYPE -]; - -namespaceResolver = xpath.createNSResolver(node); -namespaceResolver = xpath.createNSResolver(doc); - - +/// + +import xpath = require('xpath'); + +// A string of xml +var xml: string; +// an xpath query +var xpathText: string; +// a DOM +var doc: Document; +// xpath returns lists of Nodes that do not implement the NodeList interface; +// they are merely arrays. +var nodes: Array; +var node: Node; +var stringResult: string; +var booleanResult: boolean; +var numberResult: number; +var expression: xpath.XPathExpression; +var namespaceResolver: xpath.XPathNSResolver; +var xpathResult: xpath.XPathResult; +var length: number; + +xml = 'xml'; +xpathText = '//this/is/an/xpath/query'; +doc = new DOMParser().parseFromString(xml, 'text/xml'); +nodes = xpath.select(xpathText, doc); +node = xpath.select(xpathText, doc, true); +nodes = xpath.select(xpathText, doc, false); + +node = xpath.select1(xpathText, doc); + +stringResult = xpath.select(xpathText, doc).toString(); + +node = xpath.select(xpathText, doc)[0]; + +var selectFn = xpath.useNamespaces({ + 'prefix': 'http://namespaceuri.com/nsfile' +}); +nodes = selectFn(xpathText, doc); +node = selectFn(xpathText, doc, true); +nodes = selectFn(xpathText, doc, false); + +namespaceResolver = { + lookupNamespaceURI: function(prefix) { + return 'http://namespace.domain' + } +}; +expression = xpath.createExpression(xpathText, namespaceResolver); +xpathResult = expression.evaluate(doc, xpath.XPathResult.ANY_TYPE, null); +xpathResult = expression.evaluate(doc, xpath.XPathResult.ANY_TYPE, xpathResult); +xpathResult = expression.evaluate(doc, xpath.XPathResult.ANY_TYPE); +booleanResult = xpathResult.booleanValue; +numberResult = xpathResult.numberValue; +stringResult = xpathResult.stringValue; +node = xpathResult.singleNodeValue; +node = xpathResult.iterateNext(); +node = xpathResult.snapshotItem(10); +length = xpathResult.snapshotLength; + +var arrayOfNumbers: Array = [ + xpath.XPathResult.ANY_TYPE, + xpath.XPathResult.NUMBER_TYPE, + xpath.XPathResult.STRING_TYPE, + xpath.XPathResult.BOOLEAN_TYPE, + xpath.XPathResult.UNORDERED_NODE_ITERATOR_TYPE, + xpath.XPathResult.ORDERED_NODE_ITERATOR_TYPE, + xpath.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, + xpath.XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, + xpath.XPathResult.ANY_UNORDERED_NODE_TYPE, + xpath.XPathResult.FIRST_ORDERED_NODE_TYPE +]; + +namespaceResolver = xpath.createNSResolver(node); +namespaceResolver = xpath.createNSResolver(doc); + + diff --git a/xsockets/XSockets-tests.ts.tscparams b/xsockets/XSockets-tests.ts.tscparams index d3f5a12fa..8b1378917 100644 --- a/xsockets/XSockets-tests.ts.tscparams +++ b/xsockets/XSockets-tests.ts.tscparams @@ -1 +1 @@ - + diff --git a/yargs/yargs-tests.ts b/yargs/yargs-tests.ts index d504cd181..5af27636c 100644 --- a/yargs/yargs-tests.ts +++ b/yargs/yargs-tests.ts @@ -1,275 +1,275 @@ -// Type definition tests for yargs -// Project: https://github.com/chevex/yargs -// Definitions by: Martin Poelstra -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -import yargs = require('yargs'); - -// Examples taken from yargs website -// https://github.com/chevex/yargs - -// With yargs, the options be just a hash! -function xup() { - var argv = yargs.argv; - - if (argv.rif - 5 * argv.xup > 7.138) { - console.log('Plunder more riffiwobbles!'); - } - else { - console.log('Drop the xupptumblers!'); - } -} - -// And non-hyphenated options too! Just use argv._! -function nonopt() { - var argv = yargs.argv; - console.log('(%d,%d)', argv.x, argv.y); - console.log(argv._); -} - -// Yargs even counts your booleans! -function count() { - var argv = yargs - .count('verbose') - .alias('v', 'verbose') - .argv; - - var VERBOSE_LEVEL: number = argv.verbose; - - function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); } - function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); } - function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); } -} - -// Tell users how to use yer options and make demands. -function divide() { - var argv = yargs - .usage('Usage: $0 -x [num] -y [num]') - .demand(['x', 'y']) - .argv; - - console.log(argv.x / argv.y); -} - -// After yer demands have been met, demand more! Ask for non-hypenated arguments! -function demand_count() { - var argv = yargs - .demand(2) - .argv; - console.dir(argv); -} - -// EVEN MORE SHIVER ME TIMBERS! -function default_singles() { - var argv = yargs - .default('x', 10) - .default('y', 10) - .argv - ; - console.log(argv.x + argv.y); -} -function default_hash() { - var argv = yargs - .default({ x: 10, y: 10 }) - .argv - ; - console.log(argv.x + argv.y); -} - -// And if you really want to get all descriptive about it... -function boolean_single() { - var argv = yargs - .boolean('v') - .argv - ; - console.dir(argv.v); - console.dir(argv._); -} -function boolean_double() { - var argv = yargs - .boolean(['x', 'y', 'z']) - .argv - ; - console.dir([argv.x, argv.y, argv.z]); - console.dir(argv._); -} - -// Yargs is here to help you... -function line_count() { - var argv = yargs - .usage('Count the lines in a file.\nUsage: $0') - .example('$0 -f', 'count the lines in the given file') - .demand('f') - .alias('f', 'file') - .describe('f', 'Load a file') - .argv - ; -} - -// Below are tests for individual methods. -// Not all methods are covered yet, and neither are all possible invocations of methods. - -function Argv_parsing() { - var argv1 = yargs.argv; - var argv2 = yargs(['-x', '1', '-y', '2']).argv; - var argv3 = yargs.parse(['-x', '1', '-y', '2']); - console.log(argv1.x, argv2.x, argv3.x); -} - -function Argv$options() { - var argv1 = yargs - .options('f', { - alias: 'file', - default: '/etc/passwd', - }) - .argv - ; - - var argv2 = yargs - .alias('f', 'file') - .default('f', '/etc/passwd') - .argv - ; -} - -function Argv$choices() { - // example from documentation - var argv = yargs - .alias('i', 'ingredient') - .describe('i', 'choose your sandwich ingredients') - .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles']) - .help('help') - .argv -} - -function command() { - var argv = yargs - .usage('npm ') - .command('install', 'tis a mighty fine package to install') - .command('publish', 'shiver me timbers, should you be sharing all that', yargs => { - argv = yargs.option('f', { - alias: 'force', - description: 'yar, it usually be a bad idea' - }) - .help('help') - .argv; - }) - .help('help') - .argv; -} - -function completion_sync() { - var argv = yargs - .completion('completion', (current, argv) => { - // 'current' is the current command being completed. - // 'argv' is the parsed arguments so far. - // simply return an array of completions. - return [ - 'foo', - 'bar' - ]; - }) - .argv; -} - -function completion_async() { - var argv = yargs - .completion('completion', (current, argv, done) => { - setTimeout(function() { - done([ - 'apple', - 'banana' - ]); - }, 500); - }) - .argv; -} - -function Argv$help() { - var yargs1 = yargs - .usage("$0 -operand1 number -operand2 number -operation [add|subtract]"); - var s: string = yargs1.help(); -} - -function Argv$showHelpOnFail() { - var argv = yargs - .usage('Count the lines in a file.\nUsage: $0') - .demand('f') - .alias('f', 'file') - .describe('f', 'Load a file') - .showHelpOnFail(false, "Specify --help for available options") - .argv; -} - -function Argv$showHelp() { - var yargs1 = yargs - .usage("$0 -operand1 number -operand2 number -operation [add|subtract]"); - yargs1.showHelp(); -} - -function Argv$version() { - var argv1 = yargs - .version('1.0.0'); - - var argv2 = yargs - .version('1.0.0', '--version'); - - var argv3 = yargs - .version('1.0.0', '--version', 'description'); - - var argv4 = yargs - .version( function() { return '1.0.0'; }, '--version', 'description'); -} - -function Argv$locale() { - var argv = yargs - .usage('./$0 - follow ye instructions true') - .option('option', { - alias: 'o', - describe: "'tis a mighty fine option", - demand: true - }) - .command('run', "Arrr, ya best be knowin' what yer doin'") - .example('$0 run foo', "shiver me timbers, here's an example for ye") - .help('help') - .wrap(70) - .locale('pirate') - .argv -} - -function Argv$epilogue() { - var argv = yargs - .epilogue('for more information, find our manual at http://example.com'); -} - -function Argv$reset() { - var ya = yargs - .usage('$0 command') - .command('hello', 'hello command') - .command('world', 'world command') - .demand(1, 'must provide a valid command'), - argv = yargs.argv, - command = argv._[0]; - - if (command === 'hello') { - ya.reset() - .usage('$0 hello') - .help('h') - .example('$0 hello', 'print the hello message!') - .argv - - console.log('hello!'); - } else if (command === 'world'){ - ya.reset() - .usage('$0 world') - .help('h') - .example('$0 world', 'print the world message!') - .argv - - console.log('world!'); - } else { - ya.showHelp(); - } -} +// Type definition tests for yargs +// Project: https://github.com/chevex/yargs +// Definitions by: Martin Poelstra +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +import yargs = require('yargs'); + +// Examples taken from yargs website +// https://github.com/chevex/yargs + +// With yargs, the options be just a hash! +function xup() { + var argv = yargs.argv; + + if (argv.rif - 5 * argv.xup > 7.138) { + console.log('Plunder more riffiwobbles!'); + } + else { + console.log('Drop the xupptumblers!'); + } +} + +// And non-hyphenated options too! Just use argv._! +function nonopt() { + var argv = yargs.argv; + console.log('(%d,%d)', argv.x, argv.y); + console.log(argv._); +} + +// Yargs even counts your booleans! +function count() { + var argv = yargs + .count('verbose') + .alias('v', 'verbose') + .argv; + + var VERBOSE_LEVEL: number = argv.verbose; + + function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); } + function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); } + function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); } +} + +// Tell users how to use yer options and make demands. +function divide() { + var argv = yargs + .usage('Usage: $0 -x [num] -y [num]') + .demand(['x', 'y']) + .argv; + + console.log(argv.x / argv.y); +} + +// After yer demands have been met, demand more! Ask for non-hypenated arguments! +function demand_count() { + var argv = yargs + .demand(2) + .argv; + console.dir(argv); +} + +// EVEN MORE SHIVER ME TIMBERS! +function default_singles() { + var argv = yargs + .default('x', 10) + .default('y', 10) + .argv + ; + console.log(argv.x + argv.y); +} +function default_hash() { + var argv = yargs + .default({ x: 10, y: 10 }) + .argv + ; + console.log(argv.x + argv.y); +} + +// And if you really want to get all descriptive about it... +function boolean_single() { + var argv = yargs + .boolean('v') + .argv + ; + console.dir(argv.v); + console.dir(argv._); +} +function boolean_double() { + var argv = yargs + .boolean(['x', 'y', 'z']) + .argv + ; + console.dir([argv.x, argv.y, argv.z]); + console.dir(argv._); +} + +// Yargs is here to help you... +function line_count() { + var argv = yargs + .usage('Count the lines in a file.\nUsage: $0') + .example('$0 -f', 'count the lines in the given file') + .demand('f') + .alias('f', 'file') + .describe('f', 'Load a file') + .argv + ; +} + +// Below are tests for individual methods. +// Not all methods are covered yet, and neither are all possible invocations of methods. + +function Argv_parsing() { + var argv1 = yargs.argv; + var argv2 = yargs(['-x', '1', '-y', '2']).argv; + var argv3 = yargs.parse(['-x', '1', '-y', '2']); + console.log(argv1.x, argv2.x, argv3.x); +} + +function Argv$options() { + var argv1 = yargs + .options('f', { + alias: 'file', + default: '/etc/passwd', + }) + .argv + ; + + var argv2 = yargs + .alias('f', 'file') + .default('f', '/etc/passwd') + .argv + ; +} + +function Argv$choices() { + // example from documentation + var argv = yargs + .alias('i', 'ingredient') + .describe('i', 'choose your sandwich ingredients') + .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles']) + .help('help') + .argv +} + +function command() { + var argv = yargs + .usage('npm ') + .command('install', 'tis a mighty fine package to install') + .command('publish', 'shiver me timbers, should you be sharing all that', yargs => { + argv = yargs.option('f', { + alias: 'force', + description: 'yar, it usually be a bad idea' + }) + .help('help') + .argv; + }) + .help('help') + .argv; +} + +function completion_sync() { + var argv = yargs + .completion('completion', (current, argv) => { + // 'current' is the current command being completed. + // 'argv' is the parsed arguments so far. + // simply return an array of completions. + return [ + 'foo', + 'bar' + ]; + }) + .argv; +} + +function completion_async() { + var argv = yargs + .completion('completion', (current, argv, done) => { + setTimeout(function() { + done([ + 'apple', + 'banana' + ]); + }, 500); + }) + .argv; +} + +function Argv$help() { + var yargs1 = yargs + .usage("$0 -operand1 number -operand2 number -operation [add|subtract]"); + var s: string = yargs1.help(); +} + +function Argv$showHelpOnFail() { + var argv = yargs + .usage('Count the lines in a file.\nUsage: $0') + .demand('f') + .alias('f', 'file') + .describe('f', 'Load a file') + .showHelpOnFail(false, "Specify --help for available options") + .argv; +} + +function Argv$showHelp() { + var yargs1 = yargs + .usage("$0 -operand1 number -operand2 number -operation [add|subtract]"); + yargs1.showHelp(); +} + +function Argv$version() { + var argv1 = yargs + .version('1.0.0'); + + var argv2 = yargs + .version('1.0.0', '--version'); + + var argv3 = yargs + .version('1.0.0', '--version', 'description'); + + var argv4 = yargs + .version( function() { return '1.0.0'; }, '--version', 'description'); +} + +function Argv$locale() { + var argv = yargs + .usage('./$0 - follow ye instructions true') + .option('option', { + alias: 'o', + describe: "'tis a mighty fine option", + demand: true + }) + .command('run', "Arrr, ya best be knowin' what yer doin'") + .example('$0 run foo', "shiver me timbers, here's an example for ye") + .help('help') + .wrap(70) + .locale('pirate') + .argv +} + +function Argv$epilogue() { + var argv = yargs + .epilogue('for more information, find our manual at http://example.com'); +} + +function Argv$reset() { + var ya = yargs + .usage('$0 command') + .command('hello', 'hello command') + .command('world', 'world command') + .demand(1, 'must provide a valid command'), + argv = yargs.argv, + command = argv._[0]; + + if (command === 'hello') { + ya.reset() + .usage('$0 hello') + .help('h') + .example('$0 hello', 'print the hello message!') + .argv + + console.log('hello!'); + } else if (command === 'world'){ + ya.reset() + .usage('$0 world') + .help('h') + .example('$0 world', 'print the world message!') + .argv + + console.log('world!'); + } else { + ya.showHelp(); + } +} diff --git a/yargs/yargs.d.ts b/yargs/yargs.d.ts index 637137fbf..ff0132cf4 100644 --- a/yargs/yargs.d.ts +++ b/yargs/yargs.d.ts @@ -1,143 +1,143 @@ -// Type definitions for yargs -// Project: https://github.com/chevex/yargs -// Definitions by: Martin Poelstra -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module "yargs" { - - module yargs { - interface Argv { - argv: any; - (...args: any[]): any; - parse(...args: any[]): any; - - reset(): Argv; - - locale(): string; - locale(loc:string): Argv; - - detectLocale(detect:boolean): Argv; - - alias(shortName: string, longName: string): Argv; - alias(aliases: { [shortName: string]: string }): Argv; - alias(aliases: { [shortName: string]: string[] }): Argv; - - default(key: string, value: any): Argv; - default(defaults: { [key: string]: any}): Argv; - - demand(key: string, msg: string): Argv; - demand(key: string, required?: boolean): Argv; - demand(keys: string[], msg: string): Argv; - demand(keys: string[], required?: boolean): Argv; - demand(positionals: number, required?: boolean): Argv; - demand(positionals: number, msg: string): Argv; - - require(key: string, msg: string): Argv; - require(key: string, required: boolean): Argv; - require(keys: number[], msg: string): Argv; - require(keys: number[], required: boolean): Argv; - require(positionals: number, required: boolean): Argv; - require(positionals: number, msg: string): Argv; - - required(key: string, msg: string): Argv; - required(key: string, required: boolean): Argv; - required(keys: number[], msg: string): Argv; - required(keys: number[], required: boolean): Argv; - required(positionals: number, required: boolean): Argv; - required(positionals: number, msg: string): Argv; - - requiresArg(key: string): Argv; - requiresArg(keys: string[]): Argv; - - describe(key: string, description: string): Argv; - describe(descriptions: { [key: string]: string }): Argv; - - option(key: string, options: Options): Argv; - option(options: { [key: string]: Options }): Argv; - options(key: string, options: Options): Argv; - options(options: { [key: string]: Options }): Argv; - - usage(message: string, options?: { [key: string]: Options }): Argv; - usage(options?: { [key: string]: Options }): Argv; - - command(command: string, description: string): Argv; - command(command: string, description: string, fn: (args: Argv) => void): Argv; - - completion(cmd: string, fn?: SyncCompletionFunction): Argv; - completion(cmd: string, description?: string, fn?: SyncCompletionFunction): Argv; - completion(cmd: string, fn?: AsyncCompletionFunction): Argv; - completion(cmd: string, description?: string, fn?: AsyncCompletionFunction): Argv; - - example(command: string, description: string): Argv; - - check(func: (argv: any, aliases: { [alias: string]: string }) => any): Argv; - - boolean(key: string): Argv; - boolean(keys: string[]): Argv; - - string(key: string): Argv; - string(keys: string[]): Argv; - - choices(choices: Object): Argv; - choices(key: string, values:any[]): Argv; - - config(key: string): Argv; - config(keys: string[]): Argv; - - wrap(columns: number): Argv; - - strict(): Argv; - - help(): string; - help(option: string, description?: string): Argv; - - epilog(msg: string): Argv; - epilogue(msg: string): Argv; - - version(version: string, option?: string, description?: string): Argv; - version(version: () => string, option?: string, description?: string): Argv; - - showHelpOnFail(enable: boolean, message?: string): Argv; - - showHelp(func?: (message: string) => any): Argv; - - exitProcess(enabled:boolean): Argv; - - /* Undocumented */ - - normalize(key: string): Argv; - normalize(keys: string[]): Argv; - - implies(key: string, value: string): Argv; - implies(implies: { [key: string]: string }): Argv; - - count(key: string): Argv; - count(keys: string[]): Argv; - - fail(func: (msg: string) => any): void; - } - - interface Options { - type?: string; - alias?: any; - demand?: any; - required?: any; - require?: any; - default?: any; - boolean?: any; - string?: any; - count?: any; - describe?: any; - description?: any; - desc?: any; - requiresArg?: any; - choices?:string[]; - } - - type SyncCompletionFunction = (current: string, argv: any) => string[]; - type AsyncCompletionFunction = (current: string, argv: any, done: (completion: string[]) => void) => void; - } - - var yargs: yargs.Argv; - export = yargs; -} +// Type definitions for yargs +// Project: https://github.com/chevex/yargs +// Definitions by: Martin Poelstra +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "yargs" { + + module yargs { + interface Argv { + argv: any; + (...args: any[]): any; + parse(...args: any[]): any; + + reset(): Argv; + + locale(): string; + locale(loc:string): Argv; + + detectLocale(detect:boolean): Argv; + + alias(shortName: string, longName: string): Argv; + alias(aliases: { [shortName: string]: string }): Argv; + alias(aliases: { [shortName: string]: string[] }): Argv; + + default(key: string, value: any): Argv; + default(defaults: { [key: string]: any}): Argv; + + demand(key: string, msg: string): Argv; + demand(key: string, required?: boolean): Argv; + demand(keys: string[], msg: string): Argv; + demand(keys: string[], required?: boolean): Argv; + demand(positionals: number, required?: boolean): Argv; + demand(positionals: number, msg: string): Argv; + + require(key: string, msg: string): Argv; + require(key: string, required: boolean): Argv; + require(keys: number[], msg: string): Argv; + require(keys: number[], required: boolean): Argv; + require(positionals: number, required: boolean): Argv; + require(positionals: number, msg: string): Argv; + + required(key: string, msg: string): Argv; + required(key: string, required: boolean): Argv; + required(keys: number[], msg: string): Argv; + required(keys: number[], required: boolean): Argv; + required(positionals: number, required: boolean): Argv; + required(positionals: number, msg: string): Argv; + + requiresArg(key: string): Argv; + requiresArg(keys: string[]): Argv; + + describe(key: string, description: string): Argv; + describe(descriptions: { [key: string]: string }): Argv; + + option(key: string, options: Options): Argv; + option(options: { [key: string]: Options }): Argv; + options(key: string, options: Options): Argv; + options(options: { [key: string]: Options }): Argv; + + usage(message: string, options?: { [key: string]: Options }): Argv; + usage(options?: { [key: string]: Options }): Argv; + + command(command: string, description: string): Argv; + command(command: string, description: string, fn: (args: Argv) => void): Argv; + + completion(cmd: string, fn?: SyncCompletionFunction): Argv; + completion(cmd: string, description?: string, fn?: SyncCompletionFunction): Argv; + completion(cmd: string, fn?: AsyncCompletionFunction): Argv; + completion(cmd: string, description?: string, fn?: AsyncCompletionFunction): Argv; + + example(command: string, description: string): Argv; + + check(func: (argv: any, aliases: { [alias: string]: string }) => any): Argv; + + boolean(key: string): Argv; + boolean(keys: string[]): Argv; + + string(key: string): Argv; + string(keys: string[]): Argv; + + choices(choices: Object): Argv; + choices(key: string, values:any[]): Argv; + + config(key: string): Argv; + config(keys: string[]): Argv; + + wrap(columns: number): Argv; + + strict(): Argv; + + help(): string; + help(option: string, description?: string): Argv; + + epilog(msg: string): Argv; + epilogue(msg: string): Argv; + + version(version: string, option?: string, description?: string): Argv; + version(version: () => string, option?: string, description?: string): Argv; + + showHelpOnFail(enable: boolean, message?: string): Argv; + + showHelp(func?: (message: string) => any): Argv; + + exitProcess(enabled:boolean): Argv; + + /* Undocumented */ + + normalize(key: string): Argv; + normalize(keys: string[]): Argv; + + implies(key: string, value: string): Argv; + implies(implies: { [key: string]: string }): Argv; + + count(key: string): Argv; + count(keys: string[]): Argv; + + fail(func: (msg: string) => any): void; + } + + interface Options { + type?: string; + alias?: any; + demand?: any; + required?: any; + require?: any; + default?: any; + boolean?: any; + string?: any; + count?: any; + describe?: any; + description?: any; + desc?: any; + requiresArg?: any; + choices?:string[]; + } + + type SyncCompletionFunction = (current: string, argv: any) => string[]; + type AsyncCompletionFunction = (current: string, argv: any, done: (completion: string[]) => void) => void; + } + + var yargs: yargs.Argv; + export = yargs; +} diff --git a/zip.js/zip.js-tests.ts b/zip.js/zip.js-tests.ts index b00654996..ec9aa524d 100644 --- a/zip.js/zip.js-tests.ts +++ b/zip.js/zip.js-tests.ts @@ -1,45 +1,45 @@ -/// - -// create the blob object storing the data to compress -var blob: Blob = new Blob([ "Lorem ipsum dolor sit amet, consectetuer adipiscing elit..." ], { - type : "text/plain" -}); -// creates a zip storing the file "lorem.txt" with blob as data -// the zip will be stored into a Blob object (zippedBlob) -zipBlob("lorem.txt", blob, function(zippedBlob: Blob) { - // unzip the first file from zipped data stored in zippedBlob - unzipBlob(zippedBlob, function(unzippedBlob: Blob) { - // logs the uncompressed Blob - console.log(unzippedBlob); - }); -}); - -function zipBlob(filename: string, blob: Blob, callback: (blob: Blob) => void) { - // use a zip.BlobWriter object to write zipped data into a Blob object - zip.createWriter(new zip.BlobWriter("application/zip"), function(zipWriter) { - // use a BlobReader object to read the data stored into blob variable - zipWriter.add(filename, new zip.BlobReader(blob), function() { - // close the writer and calls callback function - zipWriter.close(callback); - }); - }, theErrorHandler); -} - -function unzipBlob(blob: Blob, callback: (unzippedBlob: Blob) => void) { - // use a zip.BlobReader object to read zipped data stored into blob variable - zip.createReader(new zip.BlobReader(blob), function(zipReader) { - // get entries from the zip file - zipReader.getEntries(function(entries: zip.Entry[]) { - // get data from the first file - entries[0].getData(new zip.BlobWriter("text/plain"), function(data: Blob) { - // close the reader and calls callback function with uncompressed data as parameter - zipReader.close(); - callback(data); - }); - }); - }, theErrorHandler); -} - -function theErrorHandler(message: any) { - console.error(message); +/// + +// create the blob object storing the data to compress +var blob: Blob = new Blob([ "Lorem ipsum dolor sit amet, consectetuer adipiscing elit..." ], { + type : "text/plain" +}); +// creates a zip storing the file "lorem.txt" with blob as data +// the zip will be stored into a Blob object (zippedBlob) +zipBlob("lorem.txt", blob, function(zippedBlob: Blob) { + // unzip the first file from zipped data stored in zippedBlob + unzipBlob(zippedBlob, function(unzippedBlob: Blob) { + // logs the uncompressed Blob + console.log(unzippedBlob); + }); +}); + +function zipBlob(filename: string, blob: Blob, callback: (blob: Blob) => void) { + // use a zip.BlobWriter object to write zipped data into a Blob object + zip.createWriter(new zip.BlobWriter("application/zip"), function(zipWriter) { + // use a BlobReader object to read the data stored into blob variable + zipWriter.add(filename, new zip.BlobReader(blob), function() { + // close the writer and calls callback function + zipWriter.close(callback); + }); + }, theErrorHandler); +} + +function unzipBlob(blob: Blob, callback: (unzippedBlob: Blob) => void) { + // use a zip.BlobReader object to read zipped data stored into blob variable + zip.createReader(new zip.BlobReader(blob), function(zipReader) { + // get entries from the zip file + zipReader.getEntries(function(entries: zip.Entry[]) { + // get data from the first file + entries[0].getData(new zip.BlobWriter("text/plain"), function(data: Blob) { + // close the reader and calls callback function with uncompressed data as parameter + zipReader.close(); + callback(data); + }); + }); + }, theErrorHandler); +} + +function theErrorHandler(message: any) { + console.error(message); } \ No newline at end of file diff --git a/zip.js/zip.js.d.ts b/zip.js/zip.js.d.ts index fa976dca9..d7583d8e6 100644 --- a/zip.js/zip.js.d.ts +++ b/zip.js/zip.js.d.ts @@ -1,94 +1,94 @@ -// Type definitions for zip.js 2.x -// Project: https://github.com/gildas-lormeau/zip.js -// Definitions by: Louis Grignon -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface FileEntry {} - -declare module zip { - export var useWebWorkers: boolean; - export var workerScriptsPath: string; - export var workerScripts: { - deflater?: string[]; - inflater?: string[]; - }; - - export class Reader { - public size: number; - public init(callback: () => void, onerror: (error: any) => void): void; - public readUint8Array(index: number, length: number, callback: (result: Uint8Array) => void, onerror?: (error: any) => void): void; - } - - export class TextReader extends Reader { - constructor(text: string); - } - - export class BlobReader extends Reader { - constructor(blob: Blob); - } - - export class Data64URIReader extends Reader { - constructor(dataURI: string); - } - - export class HttpReader extends Reader { - constructor(url: string); - } - - export function createReader(reader: zip.Reader, callback: (zipReader: ZipReader) => void, onerror?: (error: any) => void): void; - - export class ZipReader { - getEntries(callback: (entries: zip.Entry[]) => void): void; - close(callback?: () => void): void; - } - - export interface Entry { - filename: string; - directory: boolean; - compressedSize: number; - uncompressedSize: number; - lastModDate: Date; - lastModDateRaw: number; - comment: string; - crc32: number; - - getData(writer: zip.Writer, onend: (result: any) => void, onprogress?: (progress: number, total: number) => void, checkCrc32?: boolean): void; - } - - export class Writer { - public init(callback: () => void, onerror?: (error: any) => void): void; - public writeUint8Array(array: Uint8Array, callback: () => void, onerror?: (error: any) => void): void; - public getData(callback: (data: any) => void, onerror?: (error: any) => void) : void; - } - - export class TextWriter extends Writer { - constructor(encoding: string); - } - - export class BlobWriter extends Writer { - constructor(contentType: string); - } - - export class FileWriter extends Writer { - constructor(fileEntry: FileEntry); - } - - export class Data64URIWriter extends Writer { - constructor(mimeString?: string); - } - - export function createWriter(writer: zip.Writer, callback: (zipWriter: zip.ZipWriter) => void, onerror?: (error: any) => void, dontDeflate?: boolean): void; - - export interface WriteOptions { - directory?: boolean; - level?: number; - comment?: string; - lastModDate?: Date; - version?: number; - } - - export class ZipWriter { - public add(name: string, reader: zip.Reader, onend: () => void, onprogress?: (progress: number, total: number) => void, options?: WriteOptions): void; - public close(callback: (result: any) => void): void; - } -} +// Type definitions for zip.js 2.x +// Project: https://github.com/gildas-lormeau/zip.js +// Definitions by: Louis Grignon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface FileEntry {} + +declare module zip { + export var useWebWorkers: boolean; + export var workerScriptsPath: string; + export var workerScripts: { + deflater?: string[]; + inflater?: string[]; + }; + + export class Reader { + public size: number; + public init(callback: () => void, onerror: (error: any) => void): void; + public readUint8Array(index: number, length: number, callback: (result: Uint8Array) => void, onerror?: (error: any) => void): void; + } + + export class TextReader extends Reader { + constructor(text: string); + } + + export class BlobReader extends Reader { + constructor(blob: Blob); + } + + export class Data64URIReader extends Reader { + constructor(dataURI: string); + } + + export class HttpReader extends Reader { + constructor(url: string); + } + + export function createReader(reader: zip.Reader, callback: (zipReader: ZipReader) => void, onerror?: (error: any) => void): void; + + export class ZipReader { + getEntries(callback: (entries: zip.Entry[]) => void): void; + close(callback?: () => void): void; + } + + export interface Entry { + filename: string; + directory: boolean; + compressedSize: number; + uncompressedSize: number; + lastModDate: Date; + lastModDateRaw: number; + comment: string; + crc32: number; + + getData(writer: zip.Writer, onend: (result: any) => void, onprogress?: (progress: number, total: number) => void, checkCrc32?: boolean): void; + } + + export class Writer { + public init(callback: () => void, onerror?: (error: any) => void): void; + public writeUint8Array(array: Uint8Array, callback: () => void, onerror?: (error: any) => void): void; + public getData(callback: (data: any) => void, onerror?: (error: any) => void) : void; + } + + export class TextWriter extends Writer { + constructor(encoding: string); + } + + export class BlobWriter extends Writer { + constructor(contentType: string); + } + + export class FileWriter extends Writer { + constructor(fileEntry: FileEntry); + } + + export class Data64URIWriter extends Writer { + constructor(mimeString?: string); + } + + export function createWriter(writer: zip.Writer, callback: (zipWriter: zip.ZipWriter) => void, onerror?: (error: any) => void, dontDeflate?: boolean): void; + + export interface WriteOptions { + directory?: boolean; + level?: number; + comment?: string; + lastModDate?: Date; + version?: number; + } + + export class ZipWriter { + public add(name: string, reader: zip.Reader, onend: () => void, onprogress?: (progress: number, total: number) => void, options?: WriteOptions): void; + public close(callback: (result: any) => void): void; + } +}