From 381bb8bc26b15878869a5edc037366b7c4bf24c9 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sat, 25 Feb 2017 22:57:26 +0000 Subject: [PATCH 0001/1618] add types for couchdb-nano --- couchdb-nano/couchdb-nano-tests.ts | 12 +++ couchdb-nano/index.d.ts | 133 +++++++++++++++++++++++++++++ couchdb-nano/tsconfig.json | 22 +++++ 3 files changed, 167 insertions(+) create mode 100644 couchdb-nano/couchdb-nano-tests.ts create mode 100644 couchdb-nano/index.d.ts create mode 100644 couchdb-nano/tsconfig.json diff --git a/couchdb-nano/couchdb-nano-tests.ts b/couchdb-nano/couchdb-nano-tests.ts new file mode 100644 index 0000000000..f61240b8e1 --- /dev/null +++ b/couchdb-nano/couchdb-nano-tests.ts @@ -0,0 +1,12 @@ +import * as nano from "couchdb-nano"; + +const instance: nano.Client = nano('http://localhost:5984/emails'); + +const config: nano.Config = { + url: "http://localhost:5984/foo", + requestDefaults: { "proxy": "http://someproxy" } +}; + +const cfgInstance: nano.Client = nano(config); + +const db: nano.Database = instance.use("mydb"); \ No newline at end of file diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts new file mode 100644 index 0000000000..6858812ad1 --- /dev/null +++ b/couchdb-nano/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for abs 1.3 +// Project: https://github.com/IonicaBizau/node-abs +// Definitions by: Aya Morisawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { EventEmitter } from 'events'; +import * as request from 'request'; + +declare function nano(config: nano.Config | string): nano.Client; + +declare namespace nano { + interface UpdatesParams { + feed: "longpoll" | "continuous" | "eventsource" + timeout: number + heartbeat: boolean + } + + interface ServerConfig { + url: string + db: string + } + + interface RequestFunction { + (options: RequestOptions, callback?: Callback): void + } + + interface Callback { + (error: any, result: any): void + } + + interface RequestOptions { + db: string + method: string + path: string + doc: string + att: string + qs: any + content_type: string + headers: any + body: any + encoding: string + multipart: any[] + } + + interface DatabaseAccessor { + create(name: string, callback?: Callback): void + get(name: string, callback?: Callback): void + destroy(name: string, callback?: Callback): void + list(callback?: Callback): void + compact(name: string, designname?: string, callback?: Callback): void + replicate(source: string, target: string, options?: object, callback?: Callback): void + changes(source: string, params?: object, callback?: Callback): void + follow(source: string, params?: FollowUpdatesParams, callback?: Callback): void + info(callback?: Callback): void + } + + interface MultipartAccessor { + insert(doc: object, attachments: object[], params: string | object, callback?: Callback): void + get(docname: string, params?: string | object, callback?: Callback): void + } + + interface AttachmentAccessor { + insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): void + get(docname: string, attname: string, params?: object, callback?: Callback): void + destroy(docname: string, attname: string, params?: object, callback?: Callback): void + } + + interface DocumentAccessor { + insert(document: object, params?: string | object, callback?: Callback): void + destroy(docname: string, rev: string, callback?: Callback): void + get(docname: string, params?: object, callback?: Callback): void + head(docname: string, callback: Callback): void + copy(src_document: object, dst_document: object, options: object, callback?: Callback): void + bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): void + fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): void + fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): void + view(designname: string, viewname: string, params?: object, callback?: Callback): void + viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): void + show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): void + atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): void + search(designname: string, searchname: string, params?: object, callback?: Callback): void + multipart: MultipartAccessor + attachment: AttachmentAccessor + } + + interface BulkModifyDocsWrapper { + docs: object[] + } + + interface BulkFetchDocsWrapper { + keys: string[] + } + + interface Config { + url: string + requestDefaults?: request.CoreOptions + log?(id: string, args: any): void + parseUrl?: boolean + } + + interface FollowUpdatesParamsFilterFunction { + (doc: any, req: any): boolean + } + + interface FollowUpdatesParams { + db: string + inlucde_docs?: boolean + since?: number | "now" + heartbeat?: number + feed?: "continuous" + filter?: string | FollowUpdatesParamsFilterFunction + query_params?: object + headers?: object + inactivity_ms?: number + max_retry_seconds?: number + initial_retry_delay?: number + response_grace_time?: number + } + + interface Client { + db: DatabaseAccessor + use(db: string): DocumentAccessor + request: RequestFunction + relax: RequestFunction + dinosaur: RequestFunction + readonly config: ServerConfig + updates(params?: UpdatesParams, callback?: Callback): void + followUpdates(params?: object, callback?: Callback): EventEmitter + } +} + +export = nano diff --git a/couchdb-nano/tsconfig.json b/couchdb-nano/tsconfig.json new file mode 100644 index 0000000000..7ae532da90 --- /dev/null +++ b/couchdb-nano/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "couchdb-nano-tests.ts" + ] +} \ No newline at end of file From d25d2490139a7c8b18e6c90a29cf2dc2e9e5b1b3 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sat, 25 Feb 2017 23:15:58 +0000 Subject: [PATCH 0002/1618] most methods return a request --- couchdb-nano/index.d.ts | 61 +++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts index 6858812ad1..2ffccc6b16 100644 --- a/couchdb-nano/index.d.ts +++ b/couchdb-nano/index.d.ts @@ -5,7 +5,7 @@ /// import { EventEmitter } from 'events'; -import * as request from 'request'; +import { Request, CoreOptions } from 'request'; declare function nano(config: nano.Config | string): nano.Client; @@ -44,42 +44,42 @@ declare namespace nano { } interface DatabaseAccessor { - create(name: string, callback?: Callback): void - get(name: string, callback?: Callback): void - destroy(name: string, callback?: Callback): void - list(callback?: Callback): void - compact(name: string, designname?: string, callback?: Callback): void - replicate(source: string, target: string, options?: object, callback?: Callback): void - changes(source: string, params?: object, callback?: Callback): void - follow(source: string, params?: FollowUpdatesParams, callback?: Callback): void - info(callback?: Callback): void + create(name: string, callback?: Callback): Request + get(name: string, callback?: Callback): Request + destroy(name: string, callback?: Callback): Request + list(callback?: Callback): Request + compact(name: string, designname?: string, callback?: Callback): Request + replicate(source: string, target: string, options?: object, callback?: Callback): Request + changes(source: string, params?: object, callback?: Callback): Request + follow(source: string, params?: FollowUpdatesParams, callback?: Callback): any + info(callback?: Callback): Request } interface MultipartAccessor { - insert(doc: object, attachments: object[], params: string | object, callback?: Callback): void - get(docname: string, params?: string | object, callback?: Callback): void + insert(doc: object, attachments: object[], params: string | object, callback?: Callback): Request + get(docname: string, params?: string | object, callback?: Callback): Request } interface AttachmentAccessor { - insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): void - get(docname: string, attname: string, params?: object, callback?: Callback): void - destroy(docname: string, attname: string, params?: object, callback?: Callback): void + insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): Request + get(docname: string, attname: string, params?: object, callback?: Callback): Request + destroy(docname: string, attname: string, params?: object, callback?: Callback): Request } interface DocumentAccessor { - insert(document: object, params?: string | object, callback?: Callback): void - destroy(docname: string, rev: string, callback?: Callback): void - get(docname: string, params?: object, callback?: Callback): void - head(docname: string, callback: Callback): void - copy(src_document: object, dst_document: object, options: object, callback?: Callback): void - bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): void - fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): void - fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): void - view(designname: string, viewname: string, params?: object, callback?: Callback): void - viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): void - show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): void - atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): void - search(designname: string, searchname: string, params?: object, callback?: Callback): void + insert(document: object, params?: string | object, callback?: Callback): Request + destroy(docname: string, rev: string, callback?: Callback): Request + get(docname: string, params?: object, callback?: Callback): Request + head(docname: string, callback: Callback): Request + copy(src_document: object, dst_document: object, options: object, callback?: Callback): Request + bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): Request + fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request + fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request + view(designname: string, viewname: string, params?: object, callback?: Callback): Request + viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): Request + show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): Request + atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request + search(designname: string, searchname: string, params?: object, callback?: Callback): Request multipart: MultipartAccessor attachment: AttachmentAccessor } @@ -121,11 +121,14 @@ declare namespace nano { interface Client { db: DatabaseAccessor use(db: string): DocumentAccessor + auth(username: string, userpass: string, callback?: Function): Request + session(callback?: Callback): Request + uuids(num: number, callback: Function): Request request: RequestFunction relax: RequestFunction dinosaur: RequestFunction readonly config: ServerConfig - updates(params?: UpdatesParams, callback?: Callback): void + updates(params?: UpdatesParams, callback?: Callback): Request followUpdates(params?: object, callback?: Callback): EventEmitter } } From f7a29d67e055077527fdf1800aefc191f1483ab3 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sat, 25 Feb 2017 23:18:58 +0000 Subject: [PATCH 0003/1618] remove unneeded reference --- couchdb-nano/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts index 2ffccc6b16..d29f6d8f69 100644 --- a/couchdb-nano/index.d.ts +++ b/couchdb-nano/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// import { EventEmitter } from 'events'; import { Request, CoreOptions } from 'request'; From f89b069eea2d70b34780c0f5d773b940acda3196 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sat, 25 Feb 2017 23:19:38 +0000 Subject: [PATCH 0004/1618] remove import scope --- couchdb-nano/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts index d29f6d8f69..0617b24742 100644 --- a/couchdb-nano/index.d.ts +++ b/couchdb-nano/index.d.ts @@ -93,7 +93,7 @@ declare namespace nano { interface Config { url: string - requestDefaults?: request.CoreOptions + requestDefaults?: CoreOptions log?(id: string, args: any): void parseUrl?: boolean } From a836ef38700b5a5c095f9deacfeb11fe1822ab37 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sat, 25 Feb 2017 23:22:56 +0000 Subject: [PATCH 0005/1618] update header --- couchdb-nano/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts index 0617b24742..f96c0436e9 100644 --- a/couchdb-nano/index.d.ts +++ b/couchdb-nano/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for abs 1.3 -// Project: https://github.com/IonicaBizau/node-abs -// Definitions by: Aya Morisawa +// Type definitions for nano 6.2.0 +// Project: https://github.com/apache/couchdb-nano +// Definitions by: Tim Jacobi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { EventEmitter } from 'events'; From b1976050bf400759f6c9e24a1f11c3c956b9e85e Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 00:22:47 +0000 Subject: [PATCH 0006/1618] update after revisiting source --- couchdb-nano/index.d.ts | 153 ++++++++++++++++++++++------------------ 1 file changed, 84 insertions(+), 69 deletions(-) diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts index f96c0436e9..fc895777f0 100644 --- a/couchdb-nano/index.d.ts +++ b/couchdb-nano/index.d.ts @@ -6,13 +6,84 @@ import { EventEmitter } from 'events'; import { Request, CoreOptions } from 'request'; -declare function nano(config: nano.Config | string): nano.Client; +declare function nano(config: nano.Configuration | string): nano.ServerScope | nano.DocumentScope; declare namespace nano { - interface UpdatesParams { - feed: "longpoll" | "continuous" | "eventsource" - timeout: number - heartbeat: boolean + interface Configuration { + url: string + requestDefaults?: CoreOptions + log?(id: string, args: any): void + parseUrl?: boolean + } + + interface ServerScope { + readonly config: ServerConfig + db: DatabaseScope + use(db: string): DocumentScope + scope(db: string): DocumentScope + request: RequestFunction + relax: RequestFunction + dinosaur: RequestFunction + auth(username: string, userpass: string, callback?: Function): Request + session(callback?: Callback): Request + updates(params?: UpdatesParams, callback?: Callback): Request + followUpdates(params?: object, callback?: Callback): EventEmitter + uuids(num: number, callback: Function): Request + } + + interface DatabaseScope { + create(name: string, callback?: Callback): Request + get(name: string, callback?: Callback): Request + destroy(name: string, callback?: Callback): Request + list(callback?: Callback): Request + use(db: string): DocumentScope + compact(name: string, designname?: string, callback?: Callback): Request + replicate(source: string, target: string, options?: object, callback?: Callback): Request + changes(name: string, params?: object, callback?: Callback): Request + follow(source: string, params?: FollowUpdatesParams, callback?: Callback): any + followUpdates(params?: object, callback?: Callback): EventEmitter + updates(params?: UpdatesParams, callback?: Callback): Request + } + + interface DocumentScope { + readonly config: ServerConfig + info(callback?: Callback): Request + replicate(target: string, options?: object, callback?: Callback): Request + compact(callback?: Callback): Request + changes(params?: object, callback?: Callback): Request + follow(params?: FollowUpdatesParams, callback?: Callback): any + auth(username: string, userpass: string, callback?: Function): Request + session(callback?: Callback): Request + insert(document: object, params?: string | object, callback?: Callback): Request + get(docname: string, params?: object, callback?: Callback): Request + head(docname: string, callback: Callback): Request + copy(src_document: object, dst_document: object, options: object, callback?: Callback): Request + destroy(docname: string, rev: string, callback?: Callback): Request + bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): Request + list(params?: object, callback?: Callback): Request + fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request + fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request + multipart: Multipart + attachment: Attachment + show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): Request + atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request + updateWithHandler(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request + search(designname: string, searchname: string, params?: object, callback?: Callback): Request + spatial(ddoc: string, viewname: string, params?: object, callback?: Callback): Request + view(designname: string, viewname: string, params?: object, callback?: Callback): Request + viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): Request + server: ServerScope + } + + interface Multipart { + insert(doc: object, attachments: object[], params: string | object, callback?: Callback): Request + get(docname: string, params?: string | object, callback?: Callback): Request + } + + interface Attachment { + insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): Request + get(docname: string, attname: string, params?: object, callback?: Callback): Request + destroy(docname: string, attname: string, params?: object, callback?: Callback): Request } interface ServerConfig { @@ -24,10 +95,6 @@ declare namespace nano { (options: RequestOptions, callback?: Callback): void } - interface Callback { - (error: any, result: any): void - } - interface RequestOptions { db: string method: string @@ -42,45 +109,14 @@ declare namespace nano { multipart: any[] } - interface DatabaseAccessor { - create(name: string, callback?: Callback): Request - get(name: string, callback?: Callback): Request - destroy(name: string, callback?: Callback): Request - list(callback?: Callback): Request - compact(name: string, designname?: string, callback?: Callback): Request - replicate(source: string, target: string, options?: object, callback?: Callback): Request - changes(source: string, params?: object, callback?: Callback): Request - follow(source: string, params?: FollowUpdatesParams, callback?: Callback): any - info(callback?: Callback): Request + interface UpdatesParams { + feed: "longpoll" | "continuous" | "eventsource" + timeout: number + heartbeat: boolean } - interface MultipartAccessor { - insert(doc: object, attachments: object[], params: string | object, callback?: Callback): Request - get(docname: string, params?: string | object, callback?: Callback): Request - } - - interface AttachmentAccessor { - insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): Request - get(docname: string, attname: string, params?: object, callback?: Callback): Request - destroy(docname: string, attname: string, params?: object, callback?: Callback): Request - } - - interface DocumentAccessor { - insert(document: object, params?: string | object, callback?: Callback): Request - destroy(docname: string, rev: string, callback?: Callback): Request - get(docname: string, params?: object, callback?: Callback): Request - head(docname: string, callback: Callback): Request - copy(src_document: object, dst_document: object, options: object, callback?: Callback): Request - bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): Request - fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request - fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request - view(designname: string, viewname: string, params?: object, callback?: Callback): Request - viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): Request - show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): Request - atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request - search(designname: string, searchname: string, params?: object, callback?: Callback): Request - multipart: MultipartAccessor - attachment: AttachmentAccessor + interface Callback { + (error: any, result: any): void } interface BulkModifyDocsWrapper { @@ -91,17 +127,6 @@ declare namespace nano { keys: string[] } - interface Config { - url: string - requestDefaults?: CoreOptions - log?(id: string, args: any): void - parseUrl?: boolean - } - - interface FollowUpdatesParamsFilterFunction { - (doc: any, req: any): boolean - } - interface FollowUpdatesParams { db: string inlucde_docs?: boolean @@ -117,18 +142,8 @@ declare namespace nano { response_grace_time?: number } - interface Client { - db: DatabaseAccessor - use(db: string): DocumentAccessor - auth(username: string, userpass: string, callback?: Function): Request - session(callback?: Callback): Request - uuids(num: number, callback: Function): Request - request: RequestFunction - relax: RequestFunction - dinosaur: RequestFunction - readonly config: ServerConfig - updates(params?: UpdatesParams, callback?: Callback): Request - followUpdates(params?: object, callback?: Callback): EventEmitter + interface FollowUpdatesParamsFilterFunction { + (doc: any, req: any): boolean } } From 7f2f2c32b8d660c0da1018240f1d24fbab555965 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 01:34:49 +0000 Subject: [PATCH 0007/1618] add more tests and update as needed --- couchdb-nano/couchdb-nano-tests.ts | 118 +++++++++++++++++++++++++++-- couchdb-nano/index.d.ts | 65 ++++++++-------- 2 files changed, 147 insertions(+), 36 deletions(-) diff --git a/couchdb-nano/couchdb-nano-tests.ts b/couchdb-nano/couchdb-nano-tests.ts index f61240b8e1..4780635d12 100644 --- a/couchdb-nano/couchdb-nano-tests.ts +++ b/couchdb-nano/couchdb-nano-tests.ts @@ -1,12 +1,120 @@ import * as nano from "couchdb-nano"; +import * as fs from 'fs'; +import * as path from 'path'; -const instance: nano.Client = nano('http://localhost:5984/emails'); - -const config: nano.Config = { +/* + * Instantiate with configuration object + */ +const config: nano.Configuration = { url: "http://localhost:5984/foo", requestDefaults: { "proxy": "http://someproxy" } }; -const cfgInstance: nano.Client = nano(config); +const cfgInstance = nano(config); -const db: nano.Database = instance.use("mydb"); \ No newline at end of file +/* + * Server Scope + */ +const instance: nano.ServerScope = nano('http://localhost:5984/emails'); + +instance.dinosaur('', function (err, response) { }); +const url = instance.config.url; + +instance.relax({ + method: 'POST', + path: '_users', + body: { + _id: 'org.couchdb.user:', + type: 'user', + name: 'ss', + roles: ['admin'], + password: 'rf' + } +}, function (err: any) { }); + +instance.session(function (error, session) { }); + +instance.request({ + db: 'shared_headers', + doc: 'new', + headers: {'If-None-Match': JSON.stringify({})} + }, function(error, helloWorld, rh) {}); + +instance.relax({ + db: 'document_list', + doc: '_all_docs', + method: 'GET', + qs: {limit: 1} + }, function(error, docs) {}); + +instance.auth("", "", function(err: any, _: any, headers: any) {}); + +instance.uuids(3, function (error, data) { }); + +/* + * Database Scope + */ +const db: nano.DatabaseScope = instance.db; + +db.create('az09_$()+-/', function (err) { }); +db.get('database_get', function(error, response) {}); +db.destroy('_users', function() {}); +db.list(function(error, list) {}); +db.replicate(instance.use("a"), instance.use("b"), function(error: any) {}); +db.replicate("a", "b", function(error: any) {}); + + +/* + * Document Scope + */ +const mydb: nano.DocumentScope = instance.use("mydb"); + +mydb.insert({ 'foo': 'baz' }, null, function (error, response) { }); +mydb.insert({ 'foo': 'baz' }, 'foobar', function (error, foo) { }); +mydb.get('foobaz', { 'revs_info': true }, function (error, foobaz) { }); +mydb.head('foobaz', function (error, body, headers) { }); +mydb.copy('foo_src', 'foo_dest', { overwrite: true }, function (error, response, headers) { }); +mydb.destroy(undefined, undefined, function (error, response) { }); +mydb.bulk( + { + 'docs': [ + { 'key': 'baz', 'name': 'bazzel' }, + { 'key': 'bar', 'name': 'barry' } + ] + }, + function (error: any, response: any) { } +); +mydb.list(function (error: any, docs: any) { }); +mydb.fetch({ keys: ['foobar'] }, function (error: any, docs: any) { }); +mydb.fetchRevs({ keys: ['foobar'] }, function (error: any, docs: any) { }); +mydb.changes({ since: 0 }, function (error, response) { }); +mydb.compact(function (error) { }); +const feed = mydb.follow({ since: '0' }); +feed.on('change', function (change: any) { }); +mydb.atomic('update', 'addbaz', 'baz', function (error: any, response: any) { }); +mydb.viewWithList('people', 'by_name_and_city', 'my_list', { + key: [ + 'Derek', + 'San Francisco' + ] +}, function (error, list) { } +); +mydb.view('alice', 'by_id', { + keys: ['foobar', 'barfoo'], + 'include_docs': true +}, function (err, view) { } +); +mydb.show('people', 'singleDoc', 'p_clemens', function(error: any, doc: any, rh: any) {}); +mydb.replicate('database_replica', function(error: any) {}); + +mydb.attachment.insert('new', 'att', 'Hello World!', 'text/plain', function (error: any, att: any) { }); +mydb.attachment.destroy('new', 'att', { rev: '123' }, function (error, response) { }); +mydb.attachment.get('new_string', 'att', function (error: any, helloWorld: any) { }); + +mydb.multipart.insert({'foo': 'baz'}, [{}], 'foobaz', function(error, foo) {}); +mydb.multipart.get('foobaz', function(error: any, foobaz: any, headers: any) {}); + +const rs = fs.createReadStream(""); +const is = mydb.attachment.insert('nodejs', 'logo.png', null, 'image/png'); +is.on('end', function () { }); +rs.pipe(is); \ No newline at end of file diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts index fc895777f0..7030db9a54 100644 --- a/couchdb-nano/index.d.ts +++ b/couchdb-nano/index.d.ts @@ -16,6 +16,10 @@ declare namespace nano { parseUrl?: boolean } + interface Callback { + (error: any, result: any, headers?: any): void + } + interface ServerScope { readonly config: ServerConfig db: DatabaseScope @@ -28,7 +32,7 @@ declare namespace nano { session(callback?: Callback): Request updates(params?: UpdatesParams, callback?: Callback): Request followUpdates(params?: object, callback?: Callback): EventEmitter - uuids(num: number, callback: Function): Request + uuids(num: number, callback: Callback): Request } interface DatabaseScope { @@ -38,7 +42,7 @@ declare namespace nano { list(callback?: Callback): Request use(db: string): DocumentScope compact(name: string, designname?: string, callback?: Callback): Request - replicate(source: string, target: string, options?: object, callback?: Callback): Request + replicate(source: string | DocumentScope, target: string | DocumentScope, options?: object, callback?: Callback): Request changes(name: string, params?: object, callback?: Callback): Request follow(source: string, params?: FollowUpdatesParams, callback?: Callback): any followUpdates(params?: object, callback?: Callback): EventEmitter @@ -51,13 +55,13 @@ declare namespace nano { replicate(target: string, options?: object, callback?: Callback): Request compact(callback?: Callback): Request changes(params?: object, callback?: Callback): Request - follow(params?: FollowUpdatesParams, callback?: Callback): any + follow(params?: ScopedFollowUpdatesParams, callback?: Callback): any auth(username: string, userpass: string, callback?: Function): Request session(callback?: Callback): Request insert(document: object, params?: string | object, callback?: Callback): Request get(docname: string, params?: object, callback?: Callback): Request head(docname: string, callback: Callback): Request - copy(src_document: object, dst_document: object, options: object, callback?: Callback): Request + copy(src_document: string, dst_document: string, options: object, callback?: Callback): Request destroy(docname: string, rev: string, callback?: Callback): Request bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): Request list(params?: object, callback?: Callback): Request @@ -92,21 +96,21 @@ declare namespace nano { } interface RequestFunction { - (options: RequestOptions, callback?: Callback): void + (options?: RequestOptions | string, callback?: Callback): void } interface RequestOptions { - db: string - method: string - path: string - doc: string - att: string - qs: any - content_type: string - headers: any - body: any - encoding: string - multipart: any[] + db?: string + method?: string + path?: string + doc?: string + att?: string + qs?: any + content_type?: string + headers?: any + body?: any + encoding?: string + multipart?: any[] } interface UpdatesParams { @@ -115,22 +119,9 @@ declare namespace nano { heartbeat: boolean } - interface Callback { - (error: any, result: any): void - } - - interface BulkModifyDocsWrapper { - docs: object[] - } - - interface BulkFetchDocsWrapper { - keys: string[] - } - - interface FollowUpdatesParams { - db: string + interface ScopedFollowUpdatesParams { inlucde_docs?: boolean - since?: number | "now" + since?: string heartbeat?: number feed?: "continuous" filter?: string | FollowUpdatesParamsFilterFunction @@ -142,9 +133,21 @@ declare namespace nano { response_grace_time?: number } + interface FollowUpdatesParams extends ScopedFollowUpdatesParams { + db: string + } + interface FollowUpdatesParamsFilterFunction { (doc: any, req: any): boolean } + + interface BulkModifyDocsWrapper { + docs: object[] + } + + interface BulkFetchDocsWrapper { + keys: string[] + } } export = nano From 68ceb53a5c259eec0ec5e55e91c739001c3593ab Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 02:27:29 +0000 Subject: [PATCH 0008/1618] ts 2.2 and relax type requirement --- couchdb-nano/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/couchdb-nano/index.d.ts b/couchdb-nano/index.d.ts index 7030db9a54..58831f66a3 100644 --- a/couchdb-nano/index.d.ts +++ b/couchdb-nano/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/apache/couchdb-nano // Definitions by: Tim Jacobi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import { EventEmitter } from 'events'; import { Request, CoreOptions } from 'request'; @@ -52,7 +53,7 @@ declare namespace nano { interface DocumentScope { readonly config: ServerConfig info(callback?: Callback): Request - replicate(target: string, options?: object, callback?: Callback): Request + replicate(target: string | DocumentScope, options?: object, callback?: Callback): Request compact(callback?: Callback): Request changes(params?: object, callback?: Callback): Request follow(params?: ScopedFollowUpdatesParams, callback?: Callback): any From c11cb69ec2d3ff6e8c5e9fd308867771b726ba3f Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 02:28:17 +0000 Subject: [PATCH 0009/1618] couchdb-nano -> nano --- {couchdb-nano => nano}/couchdb-nano-tests.ts | 0 {couchdb-nano => nano}/index.d.ts | 0 {couchdb-nano => nano}/tsconfig.json | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {couchdb-nano => nano}/couchdb-nano-tests.ts (100%) rename {couchdb-nano => nano}/index.d.ts (100%) rename {couchdb-nano => nano}/tsconfig.json (100%) diff --git a/couchdb-nano/couchdb-nano-tests.ts b/nano/couchdb-nano-tests.ts similarity index 100% rename from couchdb-nano/couchdb-nano-tests.ts rename to nano/couchdb-nano-tests.ts diff --git a/couchdb-nano/index.d.ts b/nano/index.d.ts similarity index 100% rename from couchdb-nano/index.d.ts rename to nano/index.d.ts diff --git a/couchdb-nano/tsconfig.json b/nano/tsconfig.json similarity index 100% rename from couchdb-nano/tsconfig.json rename to nano/tsconfig.json From e2fa753aac4ba5368589b627e505e13a1e41f0a8 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 12:08:47 +0000 Subject: [PATCH 0010/1618] couchdb-nano -> nano --- nano/couchdb-nano-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nano/couchdb-nano-tests.ts b/nano/couchdb-nano-tests.ts index 4780635d12..8d2d1ad11a 100644 --- a/nano/couchdb-nano-tests.ts +++ b/nano/couchdb-nano-tests.ts @@ -1,4 +1,4 @@ -import * as nano from "couchdb-nano"; +import * as nano from "nano"; import * as fs from 'fs'; import * as path from 'path'; From 281429c28353a375711e53bc78d2bfd836d00f7a Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 12:16:26 +0000 Subject: [PATCH 0011/1618] rename scopes and wrap in module --- nano/index.d.ts | 260 ++++++++++++++++++++++++------------------------ 1 file changed, 131 insertions(+), 129 deletions(-) diff --git a/nano/index.d.ts b/nano/index.d.ts index 58831f66a3..238a0d1d1e 100644 --- a/nano/index.d.ts +++ b/nano/index.d.ts @@ -4,151 +4,153 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -import { EventEmitter } from 'events'; -import { Request, CoreOptions } from 'request'; +declare module "nano" { + import { EventEmitter } from 'events'; + import { Request, CoreOptions } from 'request'; -declare function nano(config: nano.Configuration | string): nano.ServerScope | nano.DocumentScope; + function nano(config: nano.Configuration | string): nano.ServerScope | nano.DocumentScope; -declare namespace nano { - interface Configuration { - url: string - requestDefaults?: CoreOptions - log?(id: string, args: any): void - parseUrl?: boolean - } + namespace nano { + interface Configuration { + url: string + requestDefaults?: CoreOptions + log?(id: string, args: any): void + parseUrl?: boolean + } - interface Callback { - (error: any, result: any, headers?: any): void - } + interface Callback { + (error: any, result: any, headers?: any): void + } - interface ServerScope { - readonly config: ServerConfig - db: DatabaseScope - use(db: string): DocumentScope - scope(db: string): DocumentScope - request: RequestFunction - relax: RequestFunction - dinosaur: RequestFunction - auth(username: string, userpass: string, callback?: Function): Request - session(callback?: Callback): Request - updates(params?: UpdatesParams, callback?: Callback): Request - followUpdates(params?: object, callback?: Callback): EventEmitter - uuids(num: number, callback: Callback): Request - } + interface ServerScope { + readonly config: ServerConfig + db: DatabaseScope + use(db: string): DocumentScope + scope(db: string): DocumentScope + request: RequestFunction + relax: RequestFunction + dinosaur: RequestFunction + auth(username: string, userpass: string, callback?: Function): Request + session(callback?: Callback): Request + updates(params?: UpdatesParams, callback?: Callback): Request + followUpdates(params?: object, callback?: Callback): EventEmitter + uuids(num: number, callback: Callback): Request + } - interface DatabaseScope { - create(name: string, callback?: Callback): Request - get(name: string, callback?: Callback): Request - destroy(name: string, callback?: Callback): Request - list(callback?: Callback): Request - use(db: string): DocumentScope - compact(name: string, designname?: string, callback?: Callback): Request - replicate(source: string | DocumentScope, target: string | DocumentScope, options?: object, callback?: Callback): Request - changes(name: string, params?: object, callback?: Callback): Request - follow(source: string, params?: FollowUpdatesParams, callback?: Callback): any - followUpdates(params?: object, callback?: Callback): EventEmitter - updates(params?: UpdatesParams, callback?: Callback): Request - } + interface DatabaseScope { + create(name: string, callback?: Callback): Request + get(name: string, callback?: Callback): Request + destroy(name: string, callback?: Callback): Request + list(callback?: Callback): Request + use(db: string): DocumentScope + compact(name: string, designname?: string, callback?: Callback): Request + replicate(source: string | DocumentScope, target: string | DocumentScope, options?: object, callback?: Callback): Request + changes(name: string, params?: object, callback?: Callback): Request + follow(source: string, params?: DatabaseScopeFollowUpdatesParams, callback?: Callback): any + followUpdates(params?: object, callback?: Callback): EventEmitter + updates(params?: UpdatesParams, callback?: Callback): Request + } - interface DocumentScope { - readonly config: ServerConfig - info(callback?: Callback): Request - replicate(target: string | DocumentScope, options?: object, callback?: Callback): Request - compact(callback?: Callback): Request - changes(params?: object, callback?: Callback): Request - follow(params?: ScopedFollowUpdatesParams, callback?: Callback): any - auth(username: string, userpass: string, callback?: Function): Request - session(callback?: Callback): Request - insert(document: object, params?: string | object, callback?: Callback): Request - get(docname: string, params?: object, callback?: Callback): Request - head(docname: string, callback: Callback): Request - copy(src_document: string, dst_document: string, options: object, callback?: Callback): Request - destroy(docname: string, rev: string, callback?: Callback): Request - bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): Request - list(params?: object, callback?: Callback): Request - fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request - fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request - multipart: Multipart - attachment: Attachment - show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): Request - atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request - updateWithHandler(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request - search(designname: string, searchname: string, params?: object, callback?: Callback): Request - spatial(ddoc: string, viewname: string, params?: object, callback?: Callback): Request - view(designname: string, viewname: string, params?: object, callback?: Callback): Request - viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): Request - server: ServerScope - } + interface DocumentScope { + readonly config: ServerConfig + info(callback?: Callback): Request + replicate(target: string | DocumentScope, options?: object, callback?: Callback): Request + compact(callback?: Callback): Request + changes(params?: object, callback?: Callback): Request + follow(params?: DocumentScopeFollowUpdatesParams, callback?: Callback): any + auth(username: string, userpass: string, callback?: Function): Request + session(callback?: Callback): Request + insert(document: object, params?: string | object, callback?: Callback): Request + get(docname: string, params?: object, callback?: Callback): Request + head(docname: string, callback: Callback): Request + copy(src_document: string, dst_document: string, options: object, callback?: Callback): Request + destroy(docname: string, rev: string, callback?: Callback): Request + bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): Request + list(params?: object, callback?: Callback): Request + fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request + fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request + multipart: Multipart + attachment: Attachment + show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): Request + atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request + updateWithHandler(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request + search(designname: string, searchname: string, params?: object, callback?: Callback): Request + spatial(ddoc: string, viewname: string, params?: object, callback?: Callback): Request + view(designname: string, viewname: string, params?: object, callback?: Callback): Request + viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): Request + server: ServerScope + } - interface Multipart { - insert(doc: object, attachments: object[], params: string | object, callback?: Callback): Request - get(docname: string, params?: string | object, callback?: Callback): Request - } + interface Multipart { + insert(doc: object, attachments: object[], params: string | object, callback?: Callback): Request + get(docname: string, params?: string | object, callback?: Callback): Request + } - interface Attachment { - insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): Request - get(docname: string, attname: string, params?: object, callback?: Callback): Request - destroy(docname: string, attname: string, params?: object, callback?: Callback): Request - } + interface Attachment { + insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): Request + get(docname: string, attname: string, params?: object, callback?: Callback): Request + destroy(docname: string, attname: string, params?: object, callback?: Callback): Request + } - interface ServerConfig { - url: string - db: string - } + interface ServerConfig { + url: string + db: string + } - interface RequestFunction { - (options?: RequestOptions | string, callback?: Callback): void - } + interface RequestFunction { + (options?: RequestOptions | string, callback?: Callback): void + } - interface RequestOptions { - db?: string - method?: string - path?: string - doc?: string - att?: string - qs?: any - content_type?: string - headers?: any - body?: any - encoding?: string - multipart?: any[] - } + interface RequestOptions { + db?: string + method?: string + path?: string + doc?: string + att?: string + qs?: any + content_type?: string + headers?: any + body?: any + encoding?: string + multipart?: any[] + } - interface UpdatesParams { - feed: "longpoll" | "continuous" | "eventsource" - timeout: number - heartbeat: boolean - } + interface UpdatesParams { + feed: "longpoll" | "continuous" | "eventsource" + timeout: number + heartbeat: boolean + } - interface ScopedFollowUpdatesParams { - inlucde_docs?: boolean - since?: string - heartbeat?: number - feed?: "continuous" - filter?: string | FollowUpdatesParamsFilterFunction - query_params?: object - headers?: object - inactivity_ms?: number - max_retry_seconds?: number - initial_retry_delay?: number - response_grace_time?: number - } + interface DocumentScopeFollowUpdatesParams { + inlucde_docs?: boolean + since?: string + heartbeat?: number + feed?: "continuous" + filter?: string | FollowUpdatesParamsFilterFunction + query_params?: object + headers?: object + inactivity_ms?: number + max_retry_seconds?: number + initial_retry_delay?: number + response_grace_time?: number + } - interface FollowUpdatesParams extends ScopedFollowUpdatesParams { - db: string - } + interface DatabaseScopeFollowUpdatesParams extends DocumentScopeFollowUpdatesParams { + db: string + } - interface FollowUpdatesParamsFilterFunction { - (doc: any, req: any): boolean - } + interface FollowUpdatesParamsFilterFunction { + (doc: any, req: any): boolean + } - interface BulkModifyDocsWrapper { - docs: object[] - } + interface BulkModifyDocsWrapper { + docs: object[] + } - interface BulkFetchDocsWrapper { - keys: string[] + interface BulkFetchDocsWrapper { + keys: string[] + } } + + export = nano } - -export = nano From e2eee44a1cb287c8e3d51871c043cee63807ce33 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 12:17:26 +0000 Subject: [PATCH 0012/1618] callbacks everywhere --- nano/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nano/index.d.ts b/nano/index.d.ts index 238a0d1d1e..639d412209 100644 --- a/nano/index.d.ts +++ b/nano/index.d.ts @@ -30,7 +30,7 @@ declare module "nano" { request: RequestFunction relax: RequestFunction dinosaur: RequestFunction - auth(username: string, userpass: string, callback?: Function): Request + auth(username: string, userpass: string, callback?: Callback): Request session(callback?: Callback): Request updates(params?: UpdatesParams, callback?: Callback): Request followUpdates(params?: object, callback?: Callback): EventEmitter @@ -58,7 +58,7 @@ declare module "nano" { compact(callback?: Callback): Request changes(params?: object, callback?: Callback): Request follow(params?: DocumentScopeFollowUpdatesParams, callback?: Callback): any - auth(username: string, userpass: string, callback?: Function): Request + auth(username: string, userpass: string, callback?: Callback): Request session(callback?: Callback): Request insert(document: object, params?: string | object, callback?: Callback): Request get(docname: string, params?: object, callback?: Callback): Request @@ -151,6 +151,6 @@ declare module "nano" { keys: string[] } } - + export = nano } From 6c3a2b63ed11de81eca1fd6a530d770b284e5554 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 12:19:04 +0000 Subject: [PATCH 0013/1618] double quotes everywhere --- nano/couchdb-nano-tests.ts | 96 +++++++++++++++++++------------------- nano/index.d.ts | 4 +- 2 files changed, 50 insertions(+), 50 deletions(-) diff --git a/nano/couchdb-nano-tests.ts b/nano/couchdb-nano-tests.ts index 8d2d1ad11a..541580e484 100644 --- a/nano/couchdb-nano-tests.ts +++ b/nano/couchdb-nano-tests.ts @@ -1,6 +1,6 @@ import * as nano from "nano"; -import * as fs from 'fs'; -import * as path from 'path'; +import * as fs from "fs"; +import * as path from "path"; /* * Instantiate with configuration object @@ -15,35 +15,35 @@ const cfgInstance = nano(config); /* * Server Scope */ -const instance: nano.ServerScope = nano('http://localhost:5984/emails'); +const instance: nano.ServerScope = nano("http://localhost:5984/emails"); -instance.dinosaur('', function (err, response) { }); +instance.dinosaur("", function (err, response) { }); const url = instance.config.url; instance.relax({ - method: 'POST', - path: '_users', + method: "POST", + path: "_users", body: { - _id: 'org.couchdb.user:', - type: 'user', - name: 'ss', - roles: ['admin'], - password: 'rf' + _id: "org.couchdb.user:", + type: "user", + name: "ss", + roles: ["admin"], + password: "rf" } }, function (err: any) { }); instance.session(function (error, session) { }); instance.request({ - db: 'shared_headers', - doc: 'new', - headers: {'If-None-Match': JSON.stringify({})} + db: "shared_headers", + doc: "new", + headers: {"If-None-Match": JSON.stringify({})} }, function(error, helloWorld, rh) {}); instance.relax({ - db: 'document_list', - doc: '_all_docs', - method: 'GET', + db: "document_list", + doc: "_all_docs", + method: "GET", qs: {limit: 1} }, function(error, docs) {}); @@ -56,9 +56,9 @@ instance.uuids(3, function (error, data) { }); */ const db: nano.DatabaseScope = instance.db; -db.create('az09_$()+-/', function (err) { }); -db.get('database_get', function(error, response) {}); -db.destroy('_users', function() {}); +db.create("az09_$()+-/", function (err) { }); +db.get("database_get", function(error, response) {}); +db.destroy("_users", function() {}); db.list(function(error, list) {}); db.replicate(instance.use("a"), instance.use("b"), function(error: any) {}); db.replicate("a", "b", function(error: any) {}); @@ -69,52 +69,52 @@ db.replicate("a", "b", function(error: any) {}); */ const mydb: nano.DocumentScope = instance.use("mydb"); -mydb.insert({ 'foo': 'baz' }, null, function (error, response) { }); -mydb.insert({ 'foo': 'baz' }, 'foobar', function (error, foo) { }); -mydb.get('foobaz', { 'revs_info': true }, function (error, foobaz) { }); -mydb.head('foobaz', function (error, body, headers) { }); -mydb.copy('foo_src', 'foo_dest', { overwrite: true }, function (error, response, headers) { }); +mydb.insert({ "foo": "baz" }, null, function (error, response) { }); +mydb.insert({ "foo": "baz" }, "foobar", function (error, foo) { }); +mydb.get("foobaz", { "revs_info": true }, function (error, foobaz) { }); +mydb.head("foobaz", function (error, body, headers) { }); +mydb.copy("foo_src", "foo_dest", { overwrite: true }, function (error, response, headers) { }); mydb.destroy(undefined, undefined, function (error, response) { }); mydb.bulk( { - 'docs': [ - { 'key': 'baz', 'name': 'bazzel' }, - { 'key': 'bar', 'name': 'barry' } + "docs": [ + { "key": "baz", "name": "bazzel" }, + { "key": "bar", "name": "barry" } ] }, function (error: any, response: any) { } ); mydb.list(function (error: any, docs: any) { }); -mydb.fetch({ keys: ['foobar'] }, function (error: any, docs: any) { }); -mydb.fetchRevs({ keys: ['foobar'] }, function (error: any, docs: any) { }); +mydb.fetch({ keys: ["foobar"] }, function (error: any, docs: any) { }); +mydb.fetchRevs({ keys: ["foobar"] }, function (error: any, docs: any) { }); mydb.changes({ since: 0 }, function (error, response) { }); mydb.compact(function (error) { }); -const feed = mydb.follow({ since: '0' }); -feed.on('change', function (change: any) { }); -mydb.atomic('update', 'addbaz', 'baz', function (error: any, response: any) { }); -mydb.viewWithList('people', 'by_name_and_city', 'my_list', { +const feed = mydb.follow({ since: "0" }); +feed.on("change", function (change: any) { }); +mydb.atomic("update", "addbaz", "baz", function (error: any, response: any) { }); +mydb.viewWithList("people", "by_name_and_city", "my_list", { key: [ - 'Derek', - 'San Francisco' + "Derek", + "San Francisco" ] }, function (error, list) { } ); -mydb.view('alice', 'by_id', { - keys: ['foobar', 'barfoo'], - 'include_docs': true +mydb.view("alice", "by_id", { + keys: ["foobar", "barfoo"], + "include_docs": true }, function (err, view) { } ); -mydb.show('people', 'singleDoc', 'p_clemens', function(error: any, doc: any, rh: any) {}); -mydb.replicate('database_replica', function(error: any) {}); +mydb.show("people", "singleDoc", "p_clemens", function(error: any, doc: any, rh: any) {}); +mydb.replicate("database_replica", function(error: any) {}); -mydb.attachment.insert('new', 'att', 'Hello World!', 'text/plain', function (error: any, att: any) { }); -mydb.attachment.destroy('new', 'att', { rev: '123' }, function (error, response) { }); -mydb.attachment.get('new_string', 'att', function (error: any, helloWorld: any) { }); +mydb.attachment.insert("new", "att", "Hello World!", "text/plain", function (error: any, att: any) { }); +mydb.attachment.destroy("new", "att", { rev: "123" }, function (error, response) { }); +mydb.attachment.get("new_string", "att", function (error: any, helloWorld: any) { }); -mydb.multipart.insert({'foo': 'baz'}, [{}], 'foobaz', function(error, foo) {}); -mydb.multipart.get('foobaz', function(error: any, foobaz: any, headers: any) {}); +mydb.multipart.insert({"foo": "baz"}, [{}], "foobaz", function(error, foo) {}); +mydb.multipart.get("foobaz", function(error: any, foobaz: any, headers: any) {}); const rs = fs.createReadStream(""); -const is = mydb.attachment.insert('nodejs', 'logo.png', null, 'image/png'); -is.on('end', function () { }); +const is = mydb.attachment.insert("nodejs", "logo.png", null, "image/png"); +is.on("end", function () { }); rs.pipe(is); \ No newline at end of file diff --git a/nano/index.d.ts b/nano/index.d.ts index 639d412209..85446625a0 100644 --- a/nano/index.d.ts +++ b/nano/index.d.ts @@ -5,8 +5,8 @@ // TypeScript Version: 2.2 declare module "nano" { - import { EventEmitter } from 'events'; - import { Request, CoreOptions } from 'request'; + import { EventEmitter } from "events"; + import { Request, CoreOptions } from "request"; function nano(config: nano.Configuration | string): nano.ServerScope | nano.DocumentScope; From db037577e239892b94885da3aa0572c1acdef7eb Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 12:30:07 +0000 Subject: [PATCH 0014/1618] formatting --- nano/couchdb-nano-tests.ts | 74 +++++++++----------------------------- 1 file changed, 16 insertions(+), 58 deletions(-) diff --git a/nano/couchdb-nano-tests.ts b/nano/couchdb-nano-tests.ts index 541580e484..de7f050340 100644 --- a/nano/couchdb-nano-tests.ts +++ b/nano/couchdb-nano-tests.ts @@ -20,35 +20,11 @@ const instance: nano.ServerScope = nano("http://localhost:5984 instance.dinosaur("", function (err, response) { }); const url = instance.config.url; -instance.relax({ - method: "POST", - path: "_users", - body: { - _id: "org.couchdb.user:", - type: "user", - name: "ss", - roles: ["admin"], - password: "rf" - } -}, function (err: any) { }); - +instance.relax({ method: "POST", path: "_users", body: { _id: "org.couchdb.user:", type: "user", name: "ss", roles: ["admin"], password: "rf" } }, function (err: any) { }); instance.session(function (error, session) { }); - -instance.request({ - db: "shared_headers", - doc: "new", - headers: {"If-None-Match": JSON.stringify({})} - }, function(error, helloWorld, rh) {}); - -instance.relax({ - db: "document_list", - doc: "_all_docs", - method: "GET", - qs: {limit: 1} - }, function(error, docs) {}); - -instance.auth("", "", function(err: any, _: any, headers: any) {}); - +instance.request({ db: "shared_headers", doc: "new", headers: { "If-None-Match": JSON.stringify({}) } }, function (error, helloWorld, rh) { }); +instance.relax({ db: "document_list", doc: "_all_docs", method: "GET", qs: { limit: 1 } }, function (error, docs) { }); +instance.auth("", "", function (err: any, _: any, headers: any) { }); instance.uuids(3, function (error, data) { }); /* @@ -57,11 +33,11 @@ instance.uuids(3, function (error, data) { }); const db: nano.DatabaseScope = instance.db; db.create("az09_$()+-/", function (err) { }); -db.get("database_get", function(error, response) {}); -db.destroy("_users", function() {}); -db.list(function(error, list) {}); -db.replicate(instance.use("a"), instance.use("b"), function(error: any) {}); -db.replicate("a", "b", function(error: any) {}); +db.get("database_get", function (error, response) { }); +db.destroy("_users", function () { }); +db.list(function (error, list) { }); +db.replicate(instance.use("a"), instance.use("b"), function (error: any) { }); +db.replicate("a", "b", function (error: any) { }); /* @@ -75,15 +51,7 @@ mydb.get("foobaz", { "revs_info": true }, function (error, foobaz) { }); mydb.head("foobaz", function (error, body, headers) { }); mydb.copy("foo_src", "foo_dest", { overwrite: true }, function (error, response, headers) { }); mydb.destroy(undefined, undefined, function (error, response) { }); -mydb.bulk( - { - "docs": [ - { "key": "baz", "name": "bazzel" }, - { "key": "bar", "name": "barry" } - ] - }, - function (error: any, response: any) { } -); +mydb.bulk({ "docs": [{ "key": "baz", "name": "bazzel" }, { "key": "bar", "name": "barry" }] }, function (error: any, response: any) { }); mydb.list(function (error: any, docs: any) { }); mydb.fetch({ keys: ["foobar"] }, function (error: any, docs: any) { }); mydb.fetchRevs({ keys: ["foobar"] }, function (error: any, docs: any) { }); @@ -92,27 +60,17 @@ mydb.compact(function (error) { }); const feed = mydb.follow({ since: "0" }); feed.on("change", function (change: any) { }); mydb.atomic("update", "addbaz", "baz", function (error: any, response: any) { }); -mydb.viewWithList("people", "by_name_and_city", "my_list", { - key: [ - "Derek", - "San Francisco" - ] -}, function (error, list) { } -); -mydb.view("alice", "by_id", { - keys: ["foobar", "barfoo"], - "include_docs": true -}, function (err, view) { } -); -mydb.show("people", "singleDoc", "p_clemens", function(error: any, doc: any, rh: any) {}); -mydb.replicate("database_replica", function(error: any) {}); +mydb.viewWithList("people", "by_name_and_city", "my_list", { key: ["Derek", "San Francisco"] }, function (error, list) { }); +mydb.view("alice", "by_id", { keys: ["foobar", "barfoo"], "include_docs": true }, function (err, view) { }); +mydb.show("people", "singleDoc", "p_clemens", function (error: any, doc: any, rh: any) { }); +mydb.replicate("database_replica", function (error: any) { }); mydb.attachment.insert("new", "att", "Hello World!", "text/plain", function (error: any, att: any) { }); mydb.attachment.destroy("new", "att", { rev: "123" }, function (error, response) { }); mydb.attachment.get("new_string", "att", function (error: any, helloWorld: any) { }); -mydb.multipart.insert({"foo": "baz"}, [{}], "foobaz", function(error, foo) {}); -mydb.multipart.get("foobaz", function(error: any, foobaz: any, headers: any) {}); +mydb.multipart.insert({ "foo": "baz" }, [{}], "foobaz", function (error, foo) { }); +mydb.multipart.get("foobaz", function (error: any, foobaz: any, headers: any) { }); const rs = fs.createReadStream(""); const is = mydb.attachment.insert("nodejs", "logo.png", null, "image/png"); From 06de26c8f8ec7bd1745550596cd841f9a74e537a Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 12:32:05 +0000 Subject: [PATCH 0015/1618] callbacks don't return anything --- nano/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nano/index.d.ts b/nano/index.d.ts index 85446625a0..31fbc307b4 100644 --- a/nano/index.d.ts +++ b/nano/index.d.ts @@ -46,7 +46,7 @@ declare module "nano" { compact(name: string, designname?: string, callback?: Callback): Request replicate(source: string | DocumentScope, target: string | DocumentScope, options?: object, callback?: Callback): Request changes(name: string, params?: object, callback?: Callback): Request - follow(source: string, params?: DatabaseScopeFollowUpdatesParams, callback?: Callback): any + follow(source: string, params?: DatabaseScopeFollowUpdatesParams, callback?: Callback): void followUpdates(params?: object, callback?: Callback): EventEmitter updates(params?: UpdatesParams, callback?: Callback): Request } @@ -57,7 +57,7 @@ declare module "nano" { replicate(target: string | DocumentScope, options?: object, callback?: Callback): Request compact(callback?: Callback): Request changes(params?: object, callback?: Callback): Request - follow(params?: DocumentScopeFollowUpdatesParams, callback?: Callback): any + follow(params?: DocumentScopeFollowUpdatesParams, callback?: Callback): void auth(username: string, userpass: string, callback?: Callback): Request session(callback?: Callback): Request insert(document: object, params?: string | object, callback?: Callback): Request From 89982c5db8267f72391249d85502f54e07bd77bc Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 14:35:14 +0000 Subject: [PATCH 0016/1618] allow to pass custom request function One problem currently arises from this: Most methods return a Request object since nano uses the request module by default. Will leave it for now since using a custom request function isn't too common. --- nano/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/nano/index.d.ts b/nano/index.d.ts index 31fbc307b4..deb453bb98 100644 --- a/nano/index.d.ts +++ b/nano/index.d.ts @@ -16,6 +16,7 @@ declare module "nano" { requestDefaults?: CoreOptions log?(id: string, args: any): void parseUrl?: boolean + request?: Function } interface Callback { From 5250a9bf3db6004391fb9b2838a9c004c76b5ec1 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 14:45:45 +0000 Subject: [PATCH 0017/1618] correct test file name --- nano/{couchdb-nano-tests.ts => nano-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename nano/{couchdb-nano-tests.ts => nano-tests.ts} (100%) diff --git a/nano/couchdb-nano-tests.ts b/nano/nano-tests.ts similarity index 100% rename from nano/couchdb-nano-tests.ts rename to nano/nano-tests.ts From f9c62d370fb02e220939349f573f9ede0f95de52 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Sun, 26 Feb 2017 14:53:22 +0000 Subject: [PATCH 0018/1618] add comments --- nano/nano-tests.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/nano/nano-tests.ts b/nano/nano-tests.ts index de7f050340..79b2fded4c 100644 --- a/nano/nano-tests.ts +++ b/nano/nano-tests.ts @@ -65,13 +65,22 @@ mydb.view("alice", "by_id", { keys: ["foobar", "barfoo"], "include_docs": true } mydb.show("people", "singleDoc", "p_clemens", function (error: any, doc: any, rh: any) { }); mydb.replicate("database_replica", function (error: any) { }); +/* + * Attachments + */ mydb.attachment.insert("new", "att", "Hello World!", "text/plain", function (error: any, att: any) { }); mydb.attachment.destroy("new", "att", { rev: "123" }, function (error, response) { }); mydb.attachment.get("new_string", "att", function (error: any, helloWorld: any) { }); +/* + * Multipart + */ mydb.multipart.insert({ "foo": "baz" }, [{}], "foobaz", function (error, foo) { }); mydb.multipart.get("foobaz", function (error: any, foobaz: any, headers: any) { }); +/* + * Piping + */ const rs = fs.createReadStream(""); const is = mydb.attachment.insert("nodejs", "logo.png", null, "image/png"); is.on("end", function () { }); From 759b400afea18079474947443a22e40d9b82a6cc Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 17:44:01 +0200 Subject: [PATCH 0019/1618] Updated i18next extists function definition and allow for additional interpolation options to be passed as TranslationOptions --- types/i18next/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 958bff12a6..0eb8d64859 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -49,6 +49,8 @@ declare namespace i18n { joinArrays?: string; postProcess?: string | any[]; interpolation?: InterpolationOptions; + //add an indexer to assure that interpolation arguments can be passed + [x: string]: any; } interface Options { @@ -106,7 +108,7 @@ declare namespace i18n { t(key: string, options?: TranslationOptions): string | any | Array; - exists(): boolean; + exists(key, options?: TranslationOptions): boolean; setDefaultNamespace(ns: string): void; From 58b46e0cf1a73f23f47f57028f0779894867be84 Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 17:47:16 +0200 Subject: [PATCH 0020/1618] Updated 18next test --- types/i18next/i18next-tests.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index 23c67cc742..9230534618 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -10,12 +10,14 @@ i18n.init({ resources: { en: { translation: { - helloWorld: 'Hello, world!' + helloWorld: 'Hello, world!', + helloWorldInterpolated: 'Hello, {{name}}!' } }, ru: { translation: { - helloWorld: 'Привет, мир!' + helloWorld: 'Привет, мир!', + helloWorldInterpolated: 'Привет, {{name}}!' } } }, @@ -61,6 +63,14 @@ i18n.t('helloWorld', { count: 10 }); +i18n.t('helloWorldInterpolated', { + defaultValue: 'default', + count: 10, + name: "world" +}); + +I18n.exists("helloWorld"); + const options:i18n.Options = i18n.options; const currentLanguage:string = i18n.language; const userLanguageCodes:string[] = i18n.languages; From 0840c661ed3d0ebca9b3feaabcc569bfd6798f19 Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 18:04:04 +0200 Subject: [PATCH 0021/1618] i18next fixed typing of exists key parameter --- types/i18next/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 0eb8d64859..ee06d8d18c 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -108,7 +108,7 @@ declare namespace i18n { t(key: string, options?: TranslationOptions): string | any | Array; - exists(key, options?: TranslationOptions): boolean; + exists(key: string, options?: TranslationOptions): boolean; setDefaultNamespace(ns: string): void; From d91888b1a91c386335f99e6a19c02d00b3b72e2d Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 18:10:38 +0200 Subject: [PATCH 0022/1618] i18next Fixed test typo --- types/i18next/i18next-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index 9230534618..e51f2f495c 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -69,7 +69,7 @@ i18n.t('helloWorldInterpolated', { name: "world" }); -I18n.exists("helloWorld"); +i18n.exists("helloWorld"); const options:i18n.Options = i18n.options; const currentLanguage:string = i18n.language; From 46fb643a795b54f6d5101905a66a4833fa505961 Mon Sep 17 00:00:00 2001 From: Christopher Cortes Date: Fri, 28 Apr 2017 17:51:33 +0200 Subject: [PATCH 0023/1618] angular-material: fix wrong "ng" namespace in some types (it should be "angular") This caused a TSC error: "TS2503:Cannot find namespace 'ngr'". Replaced "ng" by "angular" in some places. --- types/angular-material/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 5afc9a9153..10648c0012 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -27,7 +27,7 @@ declare module 'angular' { escapeToClose?: boolean; resolve?: ResolveObject; controllerAs?: string; - parent?: ((scope: ng.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node + parent?: ((scope: angular.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node disableParentScroll?: boolean; // default: true } @@ -107,9 +107,9 @@ declare module 'angular' { resolve?: ResolveObject; controllerAs?: string; parent?: string | Element | JQuery; // default: root node - onShowing?(scope: ng.IScope, element: JQuery): void; - onComplete?(scope: ng.IScope, element: JQuery): void; - onRemoving?(element: JQuery, removePromise: ng.IPromise): void; + onShowing?(scope: angular.IScope, element: JQuery): void; + onComplete?(scope: angular.IScope, element: JQuery): void; + onRemoving?(element: JQuery, removePromise: angular.IPromise): void; skipHide?: boolean; multiple?: boolean; fullscreen?: boolean; // default: false From 60fc1660d63c41545115dc38d2b6985f1d58a9e5 Mon Sep 17 00:00:00 2001 From: Matthias Lochbrunner Date: Mon, 8 May 2017 10:01:54 +0200 Subject: [PATCH 0024/1618] Add openStdin() --- types/node/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 67f275c7b6..a410e0e77f 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -370,6 +370,7 @@ declare namespace NodeJS { stdout: Socket; stderr: Socket; stdin: Socket; + openStdin(): Socket; argv: string[]; argv0: string; execArgv: string[]; From a23357923b791eede4eb384bfb985ff09ba61bfc Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Mon, 15 May 2017 18:32:01 +0200 Subject: [PATCH 0025/1618] Added missing definition for sequelize unmanaged transaction with options --- types/sequelize/v3/index.d.ts | 2 +- types/sequelize/v3/sequelize-tests.ts | 1850 +++++++++++++------------ 2 files changed, 932 insertions(+), 920 deletions(-) diff --git a/types/sequelize/v3/index.d.ts b/types/sequelize/v3/index.d.ts index e823a926e2..cd5b43499d 100644 --- a/types/sequelize/v3/index.d.ts +++ b/types/sequelize/v3/index.d.ts @@ -5694,7 +5694,7 @@ declare namespace sequelize { transaction(options: TransactionOptions, autoCallback: (t: Transaction) => Promise): Promise; transaction(autoCallback: (t: Transaction) => Promise): Promise; - transaction(): Promise; + transaction(options?: TransactionOptions): Promise; /** * Close all connections used by this sequelize instance, and free all references so the instance can be diff --git a/types/sequelize/v3/sequelize-tests.ts b/types/sequelize/v3/sequelize-tests.ts index 83c4536a71..4fde0d82b3 100644 --- a/types/sequelize/v3/sequelize-tests.ts +++ b/types/sequelize/v3/sequelize-tests.ts @@ -8,17 +8,17 @@ import Sequelize = require("sequelize"); interface AnyAttributes { }; interface AnyInstance extends Sequelize.Instance { }; -var s = new Sequelize( '' ); +var s = new Sequelize(''); var sequelize = s; var DataTypes = Sequelize; -var User = s.define( 'user', {} ); -var user = User.build(); -var Task = s.define( 'task', {} ); -var Group = s.define( 'group', {} ); -var Comment = s.define( 'comment', {} ); -var Post = s.define( 'post', {} ); -var t : Sequelize.Transaction = null; -s.transaction().then( ( a ) => t = a ); +var User = s.define('user', {}); +var user = User.build(); +var Task = s.define('task', {}); +var Group = s.define('group', {}); +var Comment = s.define('comment', {}); +var Post = s.define('post', {}); +var t: Sequelize.Transaction = null; +s.transaction().then((a) => t = a); // // Generics @@ -26,33 +26,33 @@ s.transaction().then( ( a ) => t = a ); // interface GUserAttributes { - id? : number; - username? : string; + id?: number; + username?: string; } -interface GUserInstance extends Sequelize.Instance {} -var GUser = s.define( 'user', { id: Sequelize.INTEGER, username : Sequelize.STRING }); -GUser.create({ id : 1, username : 'one' }).then( ( guser ) => guser.save() ); +interface GUserInstance extends Sequelize.Instance { } +var GUser = s.define('user', { id: Sequelize.INTEGER, username: Sequelize.STRING }); +GUser.create({ id: 1, username: 'one' }).then((guser) => guser.save()); -var schema : Sequelize.DefineAttributes = { - key : { type : Sequelize.STRING, primaryKey : true }, - value : Sequelize.STRING +var schema: Sequelize.DefineAttributes = { + key: { type: Sequelize.STRING, primaryKey: true }, + value: Sequelize.STRING }; s.define('user', schema); interface GTaskAttributes { - revision? : number; - name? : string; + revision?: number; + name?: string; } interface GTaskInstance extends Sequelize.Instance { - upRevision(): void; + upRevision(): void; } -var GTask = s.define( 'task', { revision : Sequelize.INTEGER, name : Sequelize.STRING }); +var GTask = s.define('task', { revision: Sequelize.INTEGER, name: Sequelize.STRING }); GUser.hasMany(GTask); -GTask.create({ revision: 1, name: 'test' }).then( (gtask) => gtask.upRevision() ); +GTask.create({ revision: 1, name: 'test' }).then((gtask) => gtask.upRevision()); // @@ -62,92 +62,92 @@ GTask.create({ revision: 1, name: 'test' }).then( (gtask) => gtask.upRevision() // https://github.com/sequelize/sequelize/tree/v3.4.1/test/integration/associations // -User.hasOne( Task ); -User.hasOne( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); -User.hasOne( Task, { foreignKey : 'userCoolIdTag' } ); -User.hasOne( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); -Task.hasOne( User, { foreignKey : { name : 'taskId', field : 'task_id' } } ); -User.hasOne( Task, { foreignKey : { name : 'uid', allowNull : false } } ); -User.hasOne( Task, { onDelete : 'cascade' } ); -User.hasOne( Task, { onUpdate : 'cascade' } ); -User.hasOne( Task, { onDelete : 'cascade', hooks : true } ); -User.hasOne( Task, { foreignKey : { allowNull : false } } ); -User.hasOne( Task, { foreignKeyConstraint : true } ); +User.hasOne(Task); +User.hasOne(Task, { foreignKey: 'primaryGroupId', as: 'primaryUsers' }); +User.hasOne(Task, { foreignKey: 'userCoolIdTag' }); +User.hasOne(Task, { foreignKey: 'userId', keyType: Sequelize.STRING, constraints: false }); +Task.hasOne(User, { foreignKey: { name: 'taskId', field: 'task_id' } }); +User.hasOne(Task, { foreignKey: { name: 'uid', allowNull: false } }); +User.hasOne(Task, { onDelete: 'cascade' }); +User.hasOne(Task, { onUpdate: 'cascade' }); +User.hasOne(Task, { onDelete: 'cascade', hooks: true }); +User.hasOne(Task, { foreignKey: { allowNull: false } }); +User.hasOne(Task, { foreignKeyConstraint: true }); -User.belongsTo( Task ); -User.belongsTo( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); -Task.belongsTo( User, { foreignKey : 'user_id' } ); -Task.belongsTo( User, { foreignKey : 'user_name', targetKey : 'username' } ); -User.belongsTo( User, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); -User.belongsTo( Post, { foreignKey : { name : 'AccountId', field : 'account_id' } } ); -Task.belongsTo( User, { foreignKey : { allowNull : false, name : 'uid' } } ); -Task.belongsTo( User, { constraints : false } ); -Task.belongsTo( User, { onDelete : 'cascade' } ); -Task.belongsTo( User, { onUpdate : 'restrict' } ); -User.belongsTo( User, { - as : 'parentBlocks', - foreignKey : 'child', - foreignKeyConstraint : true -} ); +User.belongsTo(Task); +User.belongsTo(Task, { foreignKey: 'primaryGroupId', as: 'primaryUsers' }); +Task.belongsTo(User, { foreignKey: 'user_id' }); +Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' }); +User.belongsTo(User, { foreignKey: 'userId', keyType: Sequelize.STRING, constraints: false }); +User.belongsTo(Post, { foreignKey: { name: 'AccountId', field: 'account_id' } }); +Task.belongsTo(User, { foreignKey: { allowNull: false, name: 'uid' } }); +Task.belongsTo(User, { constraints: false }); +Task.belongsTo(User, { onDelete: 'cascade' }); +Task.belongsTo(User, { onUpdate: 'restrict' }); +User.belongsTo(User, { + as: 'parentBlocks', + foreignKey: 'child', + foreignKeyConstraint: true +}); -User.hasMany( User ); -User.hasMany( User, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); -User.hasMany( Task, { foreignKey : 'userId' } ); -User.hasMany( Task, { foreignKey : 'userId', as : 'activeTasks', scope : { active : true } } ); -User.hasMany( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); -User.hasMany( Task, { foreignKey : { name : 'uid', allowNull : false } } ); -User.hasMany( Task, { foreignKey : { allowNull : true } } ); -User.hasMany( Task, { as : 'Children' } ); -User.hasMany( Task, { as : { singular : 'task', plural : 'taskz' } } ); -User.hasMany( Task, { constraints : false } ); -User.hasMany( Task, { onDelete : 'cascade' } ); -User.hasMany( Task, { onUpdate : 'cascade' } ); -Post.hasMany( Task, { foreignKey : 'commentable_id', scope : { commentable : 'post' } } ); -User.hasMany( User, { - as : 'childBlocks', - foreignKey : 'parent', - foreignKeyConstraint : true -} ); +User.hasMany(User); +User.hasMany(User, { foreignKey: 'primaryGroupId', as: 'primaryUsers' }); +User.hasMany(Task, { foreignKey: 'userId' }); +User.hasMany(Task, { foreignKey: 'userId', as: 'activeTasks', scope: { active: true } }); +User.hasMany(Task, { foreignKey: 'userId', keyType: Sequelize.STRING, constraints: false }); +User.hasMany(Task, { foreignKey: { name: 'uid', allowNull: false } }); +User.hasMany(Task, { foreignKey: { allowNull: true } }); +User.hasMany(Task, { as: 'Children' }); +User.hasMany(Task, { as: { singular: 'task', plural: 'taskz' } }); +User.hasMany(Task, { constraints: false }); +User.hasMany(Task, { onDelete: 'cascade' }); +User.hasMany(Task, { onUpdate: 'cascade' }); +Post.hasMany(Task, { foreignKey: 'commentable_id', scope: { commentable: 'post' } }); +User.hasMany(User, { + as: 'childBlocks', + foreignKey: 'parent', + foreignKeyConstraint: true +}); -User.belongsToMany( Task, { through : 'UserTasks' } ); -User.belongsToMany( User, { through : Task } ); -User.belongsToMany( Group, { as : 'groups', through : Task, foreignKey : 'id_user' } ); -User.belongsToMany( Task, { as : 'activeTasks', through : Task, scope : { active : true } } ); -User.belongsToMany( Task, { as : 'startedTasks', through : { model : Task, scope : { started : true } } } ); -User.belongsToMany( Group, { through : 'group_members', foreignKey : 'group_id', otherKey : 'member_id' } ); -User.belongsToMany( User, { as : 'Participants', through : User } ); -User.belongsToMany( Group, { through : 'user_places', foreignKey : 'user_id' } ); -User.belongsToMany( Group, { - through : 'user_projects', - as : 'Projects', - foreignKey : { - field : 'user_id', - name : 'userId' +User.belongsToMany(Task, { through: 'UserTasks' }); +User.belongsToMany(User, { through: Task }); +User.belongsToMany(Group, { as: 'groups', through: Task, foreignKey: 'id_user' }); +User.belongsToMany(Task, { as: 'activeTasks', through: Task, scope: { active: true } }); +User.belongsToMany(Task, { as: 'startedTasks', through: { model: Task, scope: { started: true } } }); +User.belongsToMany(Group, { through: 'group_members', foreignKey: 'group_id', otherKey: 'member_id' }); +User.belongsToMany(User, { as: 'Participants', through: User }); +User.belongsToMany(Group, { through: 'user_places', foreignKey: 'user_id' }); +User.belongsToMany(Group, { + through: 'user_projects', + as: 'Projects', + foreignKey: { + field: 'user_id', + name: 'userId' }, - otherKey : { - field : 'project_id', - name : 'projectId' + otherKey: { + field: 'project_id', + name: 'projectId' } -} ); -User.belongsToMany( Task, { onDelete : 'RESTRICT', through : 'tasksusers' } ); -User.belongsToMany( Task, { constraints : false, through : 'tasksusers' } ); -User.belongsToMany( Task, { foreignKey : { name : 'user_id', defaultValue : 42 }, through : 'UserProjects' } ); -User.belongsToMany( Post, { through : User } ); -Post.belongsToMany( User, { as : 'categories', through : User, scope : { type : 'category' } } ); -Post.belongsToMany( User, { as : 'tags', through : User, scope : { type : 'tag' } } ); -Post.belongsToMany( User, { - through : { - model : User, - unique : false, - scope : { - taggable : 'post' +}); +User.belongsToMany(Task, { onDelete: 'RESTRICT', through: 'tasksusers' }); +User.belongsToMany(Task, { constraints: false, through: 'tasksusers' }); +User.belongsToMany(Task, { foreignKey: { name: 'user_id', defaultValue: 42 }, through: 'UserProjects' }); +User.belongsToMany(Post, { through: User }); +Post.belongsToMany(User, { as: 'categories', through: User, scope: { type: 'category' } }); +Post.belongsToMany(User, { as: 'tags', through: User, scope: { type: 'tag' } }); +Post.belongsToMany(User, { + through: { + model: User, + unique: false, + scope: { + taggable: 'post' } }, - foreignKey : 'taggable_id', - constraints : false -} ); -Post.belongsToMany( Post, { through : { model : Post, unique : false }, foreignKey : 'tag_id' } ); -Post.belongsToMany( Post, { as : 'Parents', through : 'Family', foreignKey : 'ChildId', otherKey : 'PersonId' } ); + foreignKey: 'taggable_id', + constraints: false +}); +Post.belongsToMany(Post, { through: { model: Post, unique: false }, foreignKey: 'tag_id' }); +Post.belongsToMany(Post, { as: 'Parents', through: 'Family', foreignKey: 'ChildId', otherKey: 'PersonId' }); // // Mixins @@ -468,19 +468,19 @@ interface CustomerInstance extends Sequelize.Instance, Custo // Sequelize.STRING; -Sequelize.STRING( 1234 ); -Sequelize.STRING( { length : 1234 } ); -Sequelize.STRING( 1234 ).BINARY; +Sequelize.STRING(1234); +Sequelize.STRING({ length: 1234 }); +Sequelize.STRING(1234).BINARY; Sequelize.STRING.BINARY; Sequelize.TEXT; -Sequelize.TEXT( 'tiny' ); -Sequelize.TEXT( { length : 'tiny' } ); -Sequelize.TEXT( 'medium' ); -Sequelize.TEXT( 'long' ); +Sequelize.TEXT('tiny'); +Sequelize.TEXT({ length: 'tiny' }); +Sequelize.TEXT('medium'); +Sequelize.TEXT('long'); Sequelize.CHAR; -Sequelize.CHAR( 12 ); -Sequelize.CHAR( { length : 12 } ); -Sequelize.CHAR( 12 ).BINARY; +Sequelize.CHAR(12); +Sequelize.CHAR({ length: 12 }); +Sequelize.CHAR(12).BINARY; Sequelize.CHAR.BINARY; Sequelize.BOOLEAN; Sequelize.DATE; @@ -492,97 +492,97 @@ Sequelize.NOW; Sequelize.INTEGER; Sequelize.INTEGER.UNSIGNED; Sequelize.INTEGER.UNSIGNED.ZEROFILL; -Sequelize.INTEGER( 11 ); -Sequelize.INTEGER( { length : 11 } ); -Sequelize.INTEGER( 11 ).UNSIGNED; -Sequelize.INTEGER( 11 ).UNSIGNED.ZEROFILL; -Sequelize.INTEGER( 11 ).ZEROFILL; -Sequelize.INTEGER( 11 ).ZEROFILL.UNSIGNED; +Sequelize.INTEGER(11); +Sequelize.INTEGER({ length: 11 }); +Sequelize.INTEGER(11).UNSIGNED; +Sequelize.INTEGER(11).UNSIGNED.ZEROFILL; +Sequelize.INTEGER(11).ZEROFILL; +Sequelize.INTEGER(11).ZEROFILL.UNSIGNED; Sequelize.BIGINT; Sequelize.BIGINT.UNSIGNED; Sequelize.BIGINT.UNSIGNED.ZEROFILL; -Sequelize.BIGINT( 11 ); -Sequelize.BIGINT( { length : 11 } ); -Sequelize.BIGINT( 11 ).UNSIGNED; -Sequelize.BIGINT( 11 ).UNSIGNED.ZEROFILL; -Sequelize.BIGINT( 11 ).ZEROFILL; -Sequelize.BIGINT( 11 ).ZEROFILL.UNSIGNED; +Sequelize.BIGINT(11); +Sequelize.BIGINT({ length: 11 }); +Sequelize.BIGINT(11).UNSIGNED; +Sequelize.BIGINT(11).UNSIGNED.ZEROFILL; +Sequelize.BIGINT(11).ZEROFILL; +Sequelize.BIGINT(11).ZEROFILL.UNSIGNED; Sequelize.REAL.UNSIGNED; -Sequelize.REAL( 11 ); -Sequelize.REAL( { length : 11 } ); -Sequelize.REAL( 11 ).UNSIGNED; -Sequelize.REAL( 11 ).UNSIGNED.ZEROFILL; -Sequelize.REAL( 11 ).ZEROFILL; -Sequelize.REAL( 11 ).ZEROFILL.UNSIGNED; -Sequelize.REAL( 11, 12 ); -Sequelize.REAL( 11, 12 ).UNSIGNED; -Sequelize.REAL( { length : 11, decimals : 12 } ).UNSIGNED; -Sequelize.REAL( 11, 12 ).UNSIGNED.ZEROFILL; -Sequelize.REAL( 11, 12 ).ZEROFILL; -Sequelize.REAL( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.REAL(11); +Sequelize.REAL({ length: 11 }); +Sequelize.REAL(11).UNSIGNED; +Sequelize.REAL(11).UNSIGNED.ZEROFILL; +Sequelize.REAL(11).ZEROFILL; +Sequelize.REAL(11).ZEROFILL.UNSIGNED; +Sequelize.REAL(11, 12); +Sequelize.REAL(11, 12).UNSIGNED; +Sequelize.REAL({ length: 11, decimals: 12 }).UNSIGNED; +Sequelize.REAL(11, 12).UNSIGNED.ZEROFILL; +Sequelize.REAL(11, 12).ZEROFILL; +Sequelize.REAL(11, 12).ZEROFILL.UNSIGNED; Sequelize.DOUBLE; Sequelize.DOUBLE.UNSIGNED; -Sequelize.DOUBLE( 11 ); -Sequelize.DOUBLE( 11 ).UNSIGNED; -Sequelize.DOUBLE( { length : 11 } ).UNSIGNED; -Sequelize.DOUBLE( 11 ).UNSIGNED.ZEROFILL; -Sequelize.DOUBLE( 11 ).ZEROFILL; -Sequelize.DOUBLE( 11 ).ZEROFILL.UNSIGNED; -Sequelize.DOUBLE( 11, 12 ); -Sequelize.DOUBLE( 11, 12 ).UNSIGNED; -Sequelize.DOUBLE( 11, 12 ).UNSIGNED.ZEROFILL; -Sequelize.DOUBLE( 11, 12 ).ZEROFILL; -Sequelize.DOUBLE( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE(11); +Sequelize.DOUBLE(11).UNSIGNED; +Sequelize.DOUBLE({ length: 11 }).UNSIGNED; +Sequelize.DOUBLE(11).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE(11).ZEROFILL; +Sequelize.DOUBLE(11).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE(11, 12); +Sequelize.DOUBLE(11, 12).UNSIGNED; +Sequelize.DOUBLE(11, 12).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE(11, 12).ZEROFILL; +Sequelize.DOUBLE(11, 12).ZEROFILL.UNSIGNED; Sequelize.FLOAT; Sequelize.FLOAT.UNSIGNED; -Sequelize.FLOAT( 11 ); -Sequelize.FLOAT( 11 ).UNSIGNED; -Sequelize.FLOAT( 11 ).UNSIGNED.ZEROFILL; -Sequelize.FLOAT( 11 ).ZEROFILL; -Sequelize.FLOAT( { length : 11 } ).ZEROFILL; -Sequelize.FLOAT( 11 ).ZEROFILL.UNSIGNED; -Sequelize.FLOAT( 11, 12 ); -Sequelize.FLOAT( 11, 12 ).UNSIGNED; -Sequelize.FLOAT( { length : 11, decimals : 12 } ).UNSIGNED; -Sequelize.FLOAT( 11, 12 ).UNSIGNED.ZEROFILL; -Sequelize.FLOAT( 11, 12 ).ZEROFILL; -Sequelize.FLOAT( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.FLOAT(11); +Sequelize.FLOAT(11).UNSIGNED; +Sequelize.FLOAT(11).UNSIGNED.ZEROFILL; +Sequelize.FLOAT(11).ZEROFILL; +Sequelize.FLOAT({ length: 11 }).ZEROFILL; +Sequelize.FLOAT(11).ZEROFILL.UNSIGNED; +Sequelize.FLOAT(11, 12); +Sequelize.FLOAT(11, 12).UNSIGNED; +Sequelize.FLOAT({ length: 11, decimals: 12 }).UNSIGNED; +Sequelize.FLOAT(11, 12).UNSIGNED.ZEROFILL; +Sequelize.FLOAT(11, 12).ZEROFILL; +Sequelize.FLOAT(11, 12).ZEROFILL.UNSIGNED; Sequelize.NUMERIC; -Sequelize.NUMERIC( 15, 5 ); +Sequelize.NUMERIC(15, 5); Sequelize.DECIMAL; -Sequelize.DECIMAL( 10, 2 ); -Sequelize.DECIMAL( { precision : 10, scale : 2 } ); -Sequelize.DECIMAL( 10 ); -Sequelize.DECIMAL( { precision : 10 } ); -Sequelize.ENUM( 'value 1', 'value 2' ); +Sequelize.DECIMAL(10, 2); +Sequelize.DECIMAL({ precision: 10, scale: 2 }); +Sequelize.DECIMAL(10); +Sequelize.DECIMAL({ precision: 10 }); +Sequelize.ENUM('value 1', 'value 2'); Sequelize.BLOB; -Sequelize.BLOB( 'tiny' ); -Sequelize.BLOB( 'medium' ); -Sequelize.BLOB( { length : 'medium' } ); -Sequelize.BLOB( 'long' ); -Sequelize.ARRAY( Sequelize.STRING ); -Sequelize.ARRAY( Sequelize.STRING( 100 ) ); -Sequelize.ARRAY( Sequelize.INTEGER ); -Sequelize.ARRAY( Sequelize.HSTORE ); -Sequelize.ARRAY( Sequelize.ARRAY( Sequelize.STRING ) ); -Sequelize.ARRAY( Sequelize.TEXT ); -Sequelize.ARRAY( Sequelize.DATE ); -Sequelize.ARRAY( Sequelize.BOOLEAN ); -Sequelize.ARRAY( Sequelize.DECIMAL ); -Sequelize.ARRAY( Sequelize.DECIMAL( 6 ) ); -Sequelize.ARRAY( Sequelize.DECIMAL( 6, 4 ) ); -Sequelize.ARRAY( Sequelize.DOUBLE ); -Sequelize.ARRAY( Sequelize.REAL ); -Sequelize.ARRAY( Sequelize.JSON ); -Sequelize.ARRAY( Sequelize.JSONB ); +Sequelize.BLOB('tiny'); +Sequelize.BLOB('medium'); +Sequelize.BLOB({ length: 'medium' }); +Sequelize.BLOB('long'); +Sequelize.ARRAY(Sequelize.STRING); +Sequelize.ARRAY(Sequelize.STRING(100)); +Sequelize.ARRAY(Sequelize.INTEGER); +Sequelize.ARRAY(Sequelize.HSTORE); +Sequelize.ARRAY(Sequelize.ARRAY(Sequelize.STRING)); +Sequelize.ARRAY(Sequelize.TEXT); +Sequelize.ARRAY(Sequelize.DATE); +Sequelize.ARRAY(Sequelize.BOOLEAN); +Sequelize.ARRAY(Sequelize.DECIMAL); +Sequelize.ARRAY(Sequelize.DECIMAL(6)); +Sequelize.ARRAY(Sequelize.DECIMAL(6, 4)); +Sequelize.ARRAY(Sequelize.DOUBLE); +Sequelize.ARRAY(Sequelize.REAL); +Sequelize.ARRAY(Sequelize.JSON); +Sequelize.ARRAY(Sequelize.JSONB); Sequelize.GEOMETRY; -Sequelize.GEOMETRY( 'POINT' ); -Sequelize.GEOMETRY( 'LINESTRING' ); -Sequelize.GEOMETRY( 'POLYGON' ); -Sequelize.GEOMETRY( 'POINT', 4326 ); +Sequelize.GEOMETRY('POINT'); +Sequelize.GEOMETRY('LINESTRING'); +Sequelize.GEOMETRY('POLYGON'); +Sequelize.GEOMETRY('POINT', 4326); Sequelize.VIRTUAL; -new Sequelize.VIRTUAL( Sequelize.STRING ); -new Sequelize.VIRTUAL( Sequelize.DATE , ['property1', 'property2']); +new Sequelize.VIRTUAL(Sequelize.STRING); +new Sequelize.VIRTUAL(Sequelize.DATE, ['property1', 'property2']); // // Deferrable @@ -595,9 +595,9 @@ Sequelize.Deferrable.NOT; Sequelize.Deferrable.INITIALLY_IMMEDIATE; Sequelize.Deferrable.INITIALLY_DEFERRED; Sequelize.Deferrable.SET_DEFERRED; -Sequelize.Deferrable.SET_DEFERRED( ['taskTableName_user_id_fkey'] ); +Sequelize.Deferrable.SET_DEFERRED(['taskTableName_user_id_fkey']); Sequelize.Deferrable.SET_IMMEDIATE; -Sequelize.Deferrable.SET_IMMEDIATE( ['taskTableName_user_id_fkey'] ); +Sequelize.Deferrable.SET_IMMEDIATE(['taskTableName_user_id_fkey']); // // Errors @@ -610,23 +610,23 @@ Sequelize.Error; Sequelize.ValidationError; s.Error; s.ValidationError; -new s.ValidationError( 'Validation Error', [ - new s.ValidationErrorItem( ' cannot be null', 'notNull Violation', '', null ) - , new s.ValidationErrorItem( ' cannot be an array or an object', 'string violation', - '', null ) -] ); +new s.ValidationError('Validation Error', [ + new s.ValidationErrorItem(' cannot be null', 'notNull Violation', '', null) + , new s.ValidationErrorItem(' cannot be an array or an object', 'string violation', + '', null) +]); new s.Error(); new s.ValidationError(); -new s.ValidationErrorItem( 'invalid', 'type', 'first_name', null ); -new s.ValidationErrorItem( 'invalid', 'type', 'last_name', null ); -new s.DatabaseError( new Error( 'original database error message' ) ); -new s.ConnectionError( new Error( 'original connection error message' ) ); -new s.ConnectionRefusedError( new Error( 'original connection error message' ) ); -new s.AccessDeniedError( new Error( 'original connection error message' ) ); -new s.HostNotFoundError( new Error( 'original connection error message' ) ); -new s.HostNotReachableError( new Error( 'original connection error message' ) ); -new s.InvalidConnectionError( new Error( 'original connection error message' ) ); -new s.ConnectionTimedOutError( new Error( 'original connection error message' ) ); +new s.ValidationErrorItem('invalid', 'type', 'first_name', null); +new s.ValidationErrorItem('invalid', 'type', 'last_name', null); +new s.DatabaseError(new Error('original database error message')); +new s.ConnectionError(new Error('original connection error message')); +new s.ConnectionRefusedError(new Error('original connection error message')); +new s.AccessDeniedError(new Error('original connection error message')); +new s.HostNotFoundError(new Error('original connection error message')); +new s.HostNotReachableError(new Error('original connection error message')); +new s.InvalidConnectionError(new Error('original connection error message')); +new s.ConnectionTimedOutError(new Error('original connection error message')); // // Hooks @@ -635,111 +635,111 @@ new s.ConnectionTimedOutError( new Error( 'original connection error message' ) // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/hooks.test.js // -User.addHook( 'afterCreate', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); -User.addHook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); -s.addHook( 'beforeInit', function( config : Object, options : Object ) { } ); -User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); -User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); +User.addHook('afterCreate', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); +User.addHook('afterCreate', 'myHook', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); +s.addHook('beforeInit', function (config: Object, options: Object) { }); +User.hook('afterCreate', 'myHook', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); +User.hook('afterCreate', 'myHook', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); -User.removeHook( 'afterCreate', 'myHook' ); +User.removeHook('afterCreate', 'myHook'); -User.hasHook( 'afterCreate' ); -User.hasHooks( 'afterCreate' ); +User.hasHook('afterCreate'); +User.hasHooks('afterCreate'); -User.beforeValidate( function( user, options ) { user.isNewRecord; } ); -User.beforeValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.beforeValidate(function (user, options) { user.isNewRecord; }); +User.beforeValidate('myHook', function (user, options) { user.isNewRecord; }); -User.afterValidate( function( user, options ) { user.isNewRecord; } ); -User.afterValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.afterValidate(function (user, options) { user.isNewRecord; }); +User.afterValidate('myHook', function (user, options) { user.isNewRecord; }); -User.beforeCreate( function( user, options ) { user.isNewRecord; } ); -User.beforeCreate( function( user, options, fn ) {fn();} ); -User.beforeCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.beforeCreate(function (user, options) { user.isNewRecord; }); +User.beforeCreate(function (user, options, fn) { fn(); }); +User.beforeCreate('myHook', function (user, options) { user.isNewRecord; }); -User.afterCreate( function( user, options ) { user.isNewRecord; } ); -User.afterCreate( function( user, options, fn ) {fn();} ); -User.afterCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.afterCreate(function (user, options) { user.isNewRecord; }); +User.afterCreate(function (user, options, fn) { fn(); }); +User.afterCreate('myHook', function (user, options) { user.isNewRecord; }); -User.beforeDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.beforeDestroy( function( user, options, fn ) {fn();} ); -User.beforeDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); -User.beforeDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.beforeDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDestroy(function (user, options) { throw new Error('Whoops!'); }); +User.beforeDestroy(function (user, options, fn) { fn(); }); +User.beforeDestroy('myHook', function (user, options) { throw new Error('Whoops!'); }); +User.beforeDelete(function (user, options) { throw new Error('Whoops!'); }); +User.beforeDelete('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.afterDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterDestroy( function( user, options, fn ) {fn();} ); -User.afterDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDestroy(function (user, options) { throw new Error('Whoops!'); }); +User.afterDestroy('myHook', function (user, options) { throw new Error('Whoops!'); }); +User.afterDestroy(function (user, options, fn) { fn(); }); +User.afterDelete(function (user, options) { throw new Error('Whoops!'); }); +User.afterDelete('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.beforeUpdate( function( user, options ) {throw new Error( 'Whoops!' ); } ); -User.beforeUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' ); } ); +User.beforeUpdate(function (user, options) { throw new Error('Whoops!'); }); +User.beforeUpdate('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.afterUpdate( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterUpdate(function (user, options) { throw new Error('Whoops!'); }); +User.afterUpdate('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.beforeBulkCreate( function( daos, options ) { throw new Error( 'Whoops!' );} ); -User.beforeBulkCreate( 'myHook', function( daos, options ) { throw new Error( 'Whoops!' );} ); -User.beforeBulkCreate( function( daos, options, fn ) {fn();} ); +User.beforeBulkCreate(function (daos, options) { throw new Error('Whoops!'); }); +User.beforeBulkCreate('myHook', function (daos, options) { throw new Error('Whoops!'); }); +User.beforeBulkCreate(function (daos, options, fn) { fn(); }); -User.afterBulkCreate( function( daos, options ) {throw new Error( 'Whoops!' ); } ); -User.afterBulkCreate( 'myHook', function( daos, options ) {throw new Error( 'Whoops!' ); } ); -User.afterBulkCreate( function( daos, options, fn ) {fn();} ); +User.afterBulkCreate(function (daos, options) { throw new Error('Whoops!'); }); +User.afterBulkCreate('myHook', function (daos, options) { throw new Error('Whoops!'); }); +User.afterBulkCreate(function (daos, options, fn) { fn(); }); -User.beforeBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); -User.beforeBulkDestroy( function( options, fn ) {fn();} ); -User.beforeBulkDestroy( 'myHook', function( options, fn ) {fn();} ); -User.beforeBulkDelete( 'myHook', function( options, fn ) {fn();} ); +User.beforeBulkDestroy(function (options) { throw new Error('Whoops!'); }); +User.beforeBulkDestroy(function (options, fn) { fn(); }); +User.beforeBulkDestroy('myHook', function (options, fn) { fn(); }); +User.beforeBulkDelete('myHook', function (options, fn) { fn(); }); -User.afterBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); -User.afterBulkDestroy( function( options, fn ) {fn();} ); -User.afterBulkDestroy( 'myHook', function( options, fn ) {fn();} ); -User.afterBulkDelete( 'myHook', function( options, fn ) {fn();} ); +User.afterBulkDestroy(function (options) { throw new Error('Whoops!'); }); +User.afterBulkDestroy(function (options, fn) { fn(); }); +User.afterBulkDestroy('myHook', function (options, fn) { fn(); }); +User.afterBulkDelete('myHook', function (options, fn) { fn(); }); -User.beforeBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); -User.beforeBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); +User.beforeBulkUpdate(function (options) { throw new Error('Whoops!'); }); +User.beforeBulkUpdate('myHook', function (options) { throw new Error('Whoops!'); }); -User.afterBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); -User.afterBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); +User.afterBulkUpdate(function (options) { throw new Error('Whoops!'); }); +User.afterBulkUpdate('myHook', function (options) { throw new Error('Whoops!'); }); -User.beforeFind( function( options ) {} ); -User.beforeFind( 'myHook', function( options ) {} ); +User.beforeFind(function (options) { }); +User.beforeFind('myHook', function (options) { }); -User.beforeFindAfterExpandIncludeAll( function( options ) {} ); -User.beforeFindAfterExpandIncludeAll( 'myHook', function( options ) {} ); +User.beforeFindAfterExpandIncludeAll(function (options) { }); +User.beforeFindAfterExpandIncludeAll('myHook', function (options) { }); -User.beforeFindAfterOptions( function( options ) {} ); -User.beforeFindAfterOptions( 'myHook', function( options ) {} ); +User.beforeFindAfterOptions(function (options) { }); +User.beforeFindAfterOptions('myHook', function (options) { }); -User.afterFind( function( user ) {} ); -User.afterFind( 'myHook', function( user ) {} ); +User.afterFind(function (user) { }); +User.afterFind('myHook', function (user) { }); -s.beforeDefine( function( attributes, options ) {} ); -s.beforeDefine( 'myHook', function( attributes, options ) {} ); +s.beforeDefine(function (attributes, options) { }); +s.beforeDefine('myHook', function (attributes, options) { }); -s.afterDefine( function( model ) {} ); -s.afterDefine( 'myHook', function( model ) {} ); +s.afterDefine(function (model) { }); +s.afterDefine('myHook', function (model) { }); -s.beforeInit( function( config, options ) {} ); -s.beforeInit( 'myHook', function( attributes, options ) {} ); +s.beforeInit(function (config, options) { }); +s.beforeInit('myHook', function (attributes, options) { }); -s.afterInit( function( model ) {} ); -s.afterInit( 'myHook', function( model ) {} ); +s.afterInit(function (model) { }); +s.afterInit('myHook', function (model) { }); -s.define( 'User', {}, { - hooks : { - beforeValidate : function( user, options, fn ) {fn();}, - afterValidate : function( user, options, fn ) {fn();}, - beforeCreate : function( user, options, fn ) {fn();}, - afterCreate : function( user, options, fn ) {fn();}, - beforeDestroy : function( user, options, fn ) {fn();}, - afterDestroy : function( user, options, fn ) {fn();}, - beforeDelete : function( user, options, fn ) {fn();}, - afterDelete : function( user, options, fn ) {fn();}, - beforeUpdate : function( user, options, fn ) {fn();}, - afterUpdate : function( user, options, fn ) {fn();} +s.define('User', {}, { + hooks: { + beforeValidate: function (user, options, fn) { fn(); }, + afterValidate: function (user, options, fn) { fn(); }, + beforeCreate: function (user, options, fn) { fn(); }, + afterCreate: function (user, options, fn) { fn(); }, + beforeDestroy: function (user, options, fn) { fn(); }, + afterDestroy: function (user, options, fn) { fn(); }, + beforeDelete: function (user, options, fn) { fn(); }, + afterDelete: function (user, options, fn) { fn(); }, + beforeUpdate: function (user, options, fn) { fn(); }, + afterUpdate: function (user, options, fn) { fn(); } } -} ); +}); // // Instance @@ -752,71 +752,71 @@ s.define( 'User', {}, { user.isNewRecord = true; -user.Model.build( { a : 'b' } ); +user.Model.build({ a: 'b' }); user.sequelize.close(); user.where(); -user.getDataValue( '' ); +user.getDataValue(''); -user.setDataValue( '', '' ); -user.setDataValue( '', {} ); +user.setDataValue('', ''); +user.setDataValue('', {}); -user.get( 'aNumber', { plain : true, clone : true } ); +user.get('aNumber', { plain: true, clone: true }); user.get(); -user.set( 'email', 'B' ); -user.set( { name : 'B', bio : 'B' } ).save().then( ( p ) => p ); -user.set( 'birthdate', new Date() ); -user.set( { id : 1, t : 'c', q : [{ id : 1, n : 'a' }, { id : 2, n : 'Beta' }], u : { id : 1, f : 'b', l : 'd' } } ); -user.setAttributes( { a : 3 } ); -user.setAttributes( { id : 1, a : 'n', c : [{ id : 1 }, { id : 2, f : 'e' }], x : { id : 1, f : 'h', l : 'd' } } ); +user.set('email', 'B'); +user.set({ name: 'B', bio: 'B' }).save().then((p) => p); +user.set('birthdate', new Date()); +user.set({ id: 1, t: 'c', q: [{ id: 1, n: 'a' }, { id: 2, n: 'Beta' }], u: { id: 1, f: 'b', l: 'd' } }); +user.setAttributes({ a: 3 }); +user.setAttributes({ id: 1, a: 'n', c: [{ id: 1 }, { id: 2, f: 'e' }], x: { id: 1, f: 'h', l: 'd' } }); -user.changed( 'name' ); +user.changed('name'); user.changed(); -user.previous( 'name' ); +user.previous('name'); -user.save().then( ( p ) => p ); -user.save( { fields : ['a'] } ).then( ( p ) => p ); -user.save( { transaction : t } ); +user.save().then((p) => p); +user.save({ fields: ['a'] }).then((p) => p); +user.save({ transaction: t }); user.reload(); -user.reload( { attributes : ['bNumber'] } ); -user.reload( { transaction : t } ); +user.reload({ attributes: ['bNumber'] }); +user.reload({ transaction: t }); user.validate(); -user.update( { bNumber : 2 }, { where : { id : 1 } } ); -user.update( { username : 'userman' }, { silent : true } ); -user.update( { username : 'yolo' }, { logging : function() { } } ); -user.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); -user.updateAttributes( { a : 3 } ).then( ( p ) => p ); -user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( ) {} } ); +user.update({ bNumber: 2 }, { where: { id: 1 } }); +user.update({ username: 'userman' }, { silent: true }); +user.update({ username: 'yolo' }, { logging: function () { } }); +user.update({ username: 'bar' }, { where: { username: 'foo' }, transaction: t }).then((p) => p); +user.updateAttributes({ a: 3 }).then((p) => p); +user.updateAttributes({ a: 3 }, { fields: ['secretValue'], logging: function () { } }); -user.destroy().then( ( p ) => p ); -user.destroy( { logging : function( ) {} } ); -user.destroy( { transaction : t } ).then( ( p ) => p ); +user.destroy().then((p) => p); +user.destroy({ logging: function () { } }); +user.destroy({ transaction: t }).then((p) => p); user.restore(); -user.increment( 'number', { by : 2 } ).then( ( p ) => p ); -user.increment( ['aNumber'], { by : 2, where : { bNumber : 1 } } ).then( ( p ) => p ); -user.increment( ['aNumber'], { by : 2 } ).then( ( p ) => p ); -user.increment( 'aNumber' ).then( ( p ) => p ); -user.increment( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); -user.increment( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); +user.increment('number', { by: 2 }).then((p) => p); +user.increment(['aNumber'], { by: 2, where: { bNumber: 1 } }).then((p) => p); +user.increment(['aNumber'], { by: 2 }).then((p) => p); +user.increment('aNumber').then((p) => p); +user.increment({ 'aNumber': 1, 'bNumber': 2 }).then((p) => p); +user.increment('number', { by: 2, transaction: t }).then((p) => p); -user.decrement( 'aNumber', { by : 2 } ).then( ( p ) => p ); -user.decrement( ['aNumber'], { by : 2 } ).then( ( p ) => p ); -user.decrement( 'aNumber' ).then( ( p ) => p ); -user.decrement( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); -user.decrement( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); +user.decrement('aNumber', { by: 2 }).then((p) => p); +user.decrement(['aNumber'], { by: 2 }).then((p) => p); +user.decrement('aNumber').then((p) => p); +user.decrement({ 'aNumber': 1, 'bNumber': 2 }).then((p) => p); +user.decrement('number', { by: 2, transaction: t }).then((p) => p); -user.equals( user ); +user.equals(user); -user.equalsOneOf( [user, user] ); +user.equalsOneOf([user, user]); user.toJSON(); @@ -827,215 +827,215 @@ user.toJSON(); // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/model.test.js // -User.removeAttribute( 'id' ); +User.removeAttribute('id'); -User.sync( { force : true } ).then( function() { } ); -User.sync( { force : true, logging : function() { } } ); +User.sync({ force: true }).then(function () { }); +User.sync({ force: true, logging: function () { } }); User.drop(); -User.schema( 'special' ); -User.schema( 'special' ).create( { age : 3 }, { logging : function( ) {} } ); +User.schema('special'); +User.schema('special').create({ age: 3 }, { logging: function () { } }); User.getTableName(); -User.addScope('lowAccess', { where : { parent_id : 2 } }); -User.addScope('lowAccess', { where : { parent_id : 2 } }, { override: true }); -User.addScope('lowAccessWithParam', function(id: number) { - return { where : { parent_id : id } } -} ); +User.addScope('lowAccess', { where: { parent_id: 2 } }); +User.addScope('lowAccess', { where: { parent_id: 2 } }, { override: true }); +User.addScope('lowAccessWithParam', function (id: number) { + return { where: { parent_id: id } } +}); -User.scope( 'lowAccess' ).count(); -User.scope( { where : { parent_id : 2 } } ); -User.scope( [ 'lowAccess', { method: ['lowAccessWithParam', 2] }, { where : { parent_id : 2 } } ] ) +User.scope('lowAccess').count(); +User.scope({ where: { parent_id: 2 } }); +User.scope(['lowAccess', { method: ['lowAccessWithParam', 2] }, { where: { parent_id: 2 } }]) User.findAll(); -User.findAll( { where : { data : { employment : null } } } ); -User.findAll( { where : { aNumber : { gte : 10 } } } ).then( ( u ) => u[0].isNewRecord ); -User.findAll( { where : [s.or( { u : 'b' }, { u : ';' } ), s.and( { id : [1, 2] } )], include : [{ model : User }] } ); -User.findAll( { - where : [s.or( { a : 'b' }, { c : 'd' } ), s.and( { id : [1, 2, 3] }, - s.or( { deletedAt : null }, { deletedAt : { gt : new Date( 0 ) } } ) )] -} ); -User.findAll( { paranoid : false, where : [' IS NOT NULL '], include : [{ model : User }] } ); -User.findAll( { transaction : t } ); -User.findAll( { where : { data : { name : { last : 's' }, employment : { $ne : 'a' } } }, order : [['id', 'ASC']] } ); -User.findAll( { where : { username : ['boo', 'boo2'] } } ); -User.findAll( { where : { username : { like : '%2' } } } ); -User.findAll( { where : { theDate : { '..' : ['2013-01-02', '2013-01-11'] } } } ); -User.findAll( { where : { intVal : { '!..' : [8, 10] } } } ); -User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] } } } ); -User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] }, intVal : 10 } } ); -User.findAll( { where : { theDate : { between : ['2012-12-10', '2013-01-02'] } } } ); -User.findAll( { where : { theDate : { nbetween : ['2013-01-04', '2013-01-20'] } } } ); -User.findAll( { order : [s.col( 'name' )] } ); -User.findAll( { order : [['theDate', 'DESC']] } ); -User.findAll( { include : [User], order : [[User, User, 'numYears', 'c']] } ); -User.findAll( { include : [{ model : User, include : [User, { model : User, as : 'residents' }] }] } ); -User.findAll( { order : [[User, { model : User, as : 'residents' }, 'lastName', 'c']] } ); -User.findAll( { include : [User], order : [[User, 'name', 'c']] } ); -User.findAll( { include : [{ all : 'HasMany', attributes : ['name'] }] } ); -User.findAll( { include : [{ all : true }, { model : User, attributes : ['id'] }] } ); -User.findAll( { include : [{ all : 'BelongsTo' }] } ); -User.findAll( { include : [{ all : true }] } ); -User.findAll( { where : { username : 'barfooz' }, raw : true } ); -User.findAll( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDos' }] } ); -User.findAll( { where : { user_id : 1 }, attributes : ['a', 'b'], include : [{ model : User, attributes : ['c'] }] } ); -User.findAll( { order : s.literal( 'email =' ) } ); -User.findAll( { order : [s.literal( 'email = ' + s.escape( 'test@sequelizejs.com' ) )] } ); -User.findAll( { order : [['id', ';DELETE YOLO INJECTIONS']] } ); -User.findAll( { include : [User], order : [[User, 'id', ';DELETE YOLO INJECTIONS']] } ); -User.findAll( { include : [User], order : [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] } ); -User.findAll( { include : [{ model : User, where : { title : 'DoDat' }, include : [{ model : User }] }] } ); -User.findAll( { attributes: ['username', 'data']}); -User.findAll( { attributes: {include: ['username', 'data']} }); -User.findAll( { attributes: [['username', 'user_name'], ['email', 'user_email']] }); -User.findAll( { attributes: [s.fn('count', Sequelize.col('*'))] }); -User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']] }); -User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']], group: ['sex'] }); -User.findAll( { attributes: [s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER')] }); -User.findAll( { attributes: [[s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER'), 'count']] }); +User.findAll({ where: { data: { employment: null } } }); +User.findAll({ where: { aNumber: { gte: 10 } } }).then((u) => u[0].isNewRecord); +User.findAll({ where: [s.or({ u: 'b' }, { u: ';' }), s.and({ id: [1, 2] })], include: [{ model: User }] }); +User.findAll({ + where: [s.or({ a: 'b' }, { c: 'd' }), s.and({ id: [1, 2, 3] }, + s.or({ deletedAt: null }, { deletedAt: { gt: new Date(0) } }))] +}); +User.findAll({ paranoid: false, where: [' IS NOT NULL '], include: [{ model: User }] }); +User.findAll({ transaction: t }); +User.findAll({ where: { data: { name: { last: 's' }, employment: { $ne: 'a' } } }, order: [['id', 'ASC']] }); +User.findAll({ where: { username: ['boo', 'boo2'] } }); +User.findAll({ where: { username: { like: '%2' } } }); +User.findAll({ where: { theDate: { '..': ['2013-01-02', '2013-01-11'] } } }); +User.findAll({ where: { intVal: { '!..': [8, 10] } } }); +User.findAll({ where: { theDate: { between: ['2013-01-02', '2013-01-11'] } } }); +User.findAll({ where: { theDate: { between: ['2013-01-02', '2013-01-11'] }, intVal: 10 } }); +User.findAll({ where: { theDate: { between: ['2012-12-10', '2013-01-02'] } } }); +User.findAll({ where: { theDate: { nbetween: ['2013-01-04', '2013-01-20'] } } }); +User.findAll({ order: [s.col('name')] }); +User.findAll({ order: [['theDate', 'DESC']] }); +User.findAll({ include: [User], order: [[User, User, 'numYears', 'c']] }); +User.findAll({ include: [{ model: User, include: [User, { model: User, as: 'residents' }] }] }); +User.findAll({ order: [[User, { model: User, as: 'residents' }, 'lastName', 'c']] }); +User.findAll({ include: [User], order: [[User, 'name', 'c']] }); +User.findAll({ include: [{ all: 'HasMany', attributes: ['name'] }] }); +User.findAll({ include: [{ all: true }, { model: User, attributes: ['id'] }] }); +User.findAll({ include: [{ all: 'BelongsTo' }] }); +User.findAll({ include: [{ all: true }] }); +User.findAll({ where: { username: 'barfooz' }, raw: true }); +User.findAll({ where: { name: 'worker' }, include: [{ model: User, as: 'ToDos' }] }); +User.findAll({ where: { user_id: 1 }, attributes: ['a', 'b'], include: [{ model: User, attributes: ['c'] }] }); +User.findAll({ order: s.literal('email =') }); +User.findAll({ order: [s.literal('email = ' + s.escape('test@sequelizejs.com'))] }); +User.findAll({ order: [['id', ';DELETE YOLO INJECTIONS']] }); +User.findAll({ include: [User], order: [[User, 'id', ';DELETE YOLO INJECTIONS']] }); +User.findAll({ include: [User], order: [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] }); +User.findAll({ include: [{ model: User, where: { title: 'DoDat' }, include: [{ model: User }] }] }); +User.findAll({ attributes: ['username', 'data'] }); +User.findAll({ attributes: { include: ['username', 'data'] } }); +User.findAll({ attributes: [['username', 'user_name'], ['email', 'user_email']] }); +User.findAll({ attributes: [s.fn('count', Sequelize.col('*'))] }); +User.findAll({ attributes: [[s.fn('count', Sequelize.col('*')), 'count']] }); +User.findAll({ attributes: [[s.fn('count', Sequelize.col('*')), 'count']], group: ['sex'] }); +User.findAll({ attributes: [s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER')] }); +User.findAll({ attributes: [[s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER'), 'count']] }); -User.findById( 'a string' ); +User.findById('a string'); -User.findOne( { where : { username : 'foo' } } ); -User.findOne( { where : { id : 1 }, attributes : ['id', ['username', 'name']] } ); -User.findOne( { where : { id : 1 }, attributes : ['id'] } ); -User.findOne( { where : { username : 'foo' }, logging : function( ) { } } ); -User.findOne( { limit : 10 } ); -User.findOne( { include : [1] } ); -User.findOne( { where : { title : 'homework' }, include : [User] } ); -User.findOne( { where : { name : 'environment' }, include : [{ model : User, as : 'PrivateDomain' }] } ); -User.findOne( { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); -User.findOne( { include : [User] } ); -User.findOne( { include : [{ model : User, as : 'Work' }] } ); -User.findOne( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDo' }] } ); -User.findOne( { include : [{ model : User, as : 'ToDo' }, { model : User, as : 'DoTo' }] } ); -User.findOne( { where : { name : 'worker' }, include : [User] } ); -User.findOne( { where : { name : 'Boris' }, include : [User, { model : User, as : 'Photos' }] } ); -User.findOne( { where : { username : 'someone' }, include : [User] } ); -User.findOne( { where : { username : 'barfooz' }, raw : true } ); +User.findOne({ where: { username: 'foo' } }); +User.findOne({ where: { id: 1 }, attributes: ['id', ['username', 'name']] }); +User.findOne({ where: { id: 1 }, attributes: ['id'] }); +User.findOne({ where: { username: 'foo' }, logging: function () { } }); +User.findOne({ limit: 10 }); +User.findOne({ include: [1] }); +User.findOne({ where: { title: 'homework' }, include: [User] }); +User.findOne({ where: { name: 'environment' }, include: [{ model: User, as: 'PrivateDomain' }] }); +User.findOne({ where: { username: 'foo' }, transaction: t }).then((p) => p); +User.findOne({ include: [User] }); +User.findOne({ include: [{ model: User, as: 'Work' }] }); +User.findOne({ where: { name: 'worker' }, include: [{ model: User, as: 'ToDo' }] }); +User.findOne({ include: [{ model: User, as: 'ToDo' }, { model: User, as: 'DoTo' }] }); +User.findOne({ where: { name: 'worker' }, include: [User] }); +User.findOne({ where: { name: 'Boris' }, include: [User, { model: User, as: 'Photos' }] }); +User.findOne({ where: { username: 'someone' }, include: [User] }); +User.findOne({ where: { username: 'barfooz' }, raw: true }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOne( { updatedAt : { ne : null } } ); */ -User.find( { where : { intVal : { gt : 5 } } } ); -User.find( { where : { intVal : { lte : 5 } } } ); +User.find({ where: { intVal: { gt: 5 } } }); +User.find({ where: { intVal: { lte: 5 } } }); User.count(); -User.count( { transaction : t } ); -User.count().then( function( c ) { c.toFixed(); } ); -User.count( { where : ["username LIKE '%us%'"] } ); -User.count( { include : [{ model : User, required : false }] } ); -User.count( { distinct : true, include : [{ model : User, required : false }] } ); -User.count( { attributes : ['data'], group : ['data'] } ); -User.count( { where : { access_level : { gt : 5 } } } ); +User.count({ transaction: t }); +User.count().then(function (c) { c.toFixed(); }); +User.count({ where: ["username LIKE '%us%'"] }); +User.count({ include: [{ model: User, required: false }] }); +User.count({ distinct: true, include: [{ model: User, required: false }] }); +User.count({ attributes: ['data'], group: ['data'] }); +User.count({ where: { access_level: { gt: 5 } } }); -User.findAndCountAll( { offset : 5, limit : 1, include : [User, { model : User, as : 'a' }] } ); +User.findAndCountAll({ offset: 5, limit: 1, include: [User, { model: User, as: 'a' }] }); -User.max( 'age', { transaction : t } ); -User.max( 'age' ); -User.max( 'age', { logging : function( ) { } } ); +User.max('age', { transaction: t }); +User.max('age'); +User.max('age', { logging: function () { } }); -User.min( 'age', { transaction : t } ); -User.min( 'age' ); -User.min( 'age', { logging : function( ) { } } ); +User.min('age', { transaction: t }); +User.min('age'); +User.min('age', { logging: function () { } }); -User.sum( 'order' ); -User.sum( 'age', { where : { 'gender' : 'male' } } ); -User.sum( 'age', { logging : function( ) { } } ); +User.sum('order'); +User.sum('age', { where: { 'gender': 'male' } }); +User.sum('age', { logging: function () { } }); -User.build( { username : 'John Wayne' } ).save(); +User.build({ username: 'John Wayne' }).save(); User.build(); -User.build( { id : 1, T : [{ n : 'a' }, { id : 2 }], A : { id : 1, n : 'a', c : 'a' } }, { include : [User, Task] } ); -User.build( { id : 1, }, { include : [{ model : User, as : 'followers' }, { model : Task, as : 'categories' }] } ); +User.build({ id: 1, T: [{ n: 'a' }, { id: 2 }], A: { id: 1, n: 'a', c: 'a' } }, { include: [User, Task] }); +User.build({ id: 1, }, { include: [{ model: User, as: 'followers' }, { model: Task, as: 'categories' }] }); User.create(); -User.create( { createdAt : 1, updatedAt : 2 }, { silent : true } ); -User.create( {}, { returning : true } ); -User.create( { intVal : s.literal( 'CAST(1-2 AS' ) } ); -User.create( { secretValue : s.fn( 'upper', 'sequelize' ) } ); -User.create( { myvals : [1, 2, 3, 4], mystr : ['One', 'Two', 'Three', 'Four'] } ); -User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( ) {} } ); -User.create( {}, { fields : [] } ); -User.create( { name : 'Yolo Bear', email : 'yolo@bear.com' }, { fields : ['name'] } ); -User.create( { title : 'Chair', User : { first_name : 'Mick', last_name : 'Broadstone' } }, { include : [User] } ); -User.create( { title : 'Chair', creator : { first_name : 'Matt', last_name : 'Hansen' } }, { include : [User] } ); -User.create( { id : 1, title : 'e', Tags : [{ id : 1, name : 'c' }, { id : 2, name : 'd' }] }, { include : [User] } ); -User.create( { id : 'My own ID!' } ).then( ( i ) => i.isNewRecord ); +User.create({ createdAt: 1, updatedAt: 2 }, { silent: true }); +User.create({}, { returning: true }); +User.create({ intVal: s.literal('CAST(1-2 AS') }); +User.create({ secretValue: s.fn('upper', 'sequelize') }); +User.create({ myvals: [1, 2, 3, 4], mystr: ['One', 'Two', 'Three', 'Four'] }); +User.create({ name: 'Fluffy Bunny', smth: 'else' }, { logging: function () { } }); +User.create({}, { fields: [] }); +User.create({ name: 'Yolo Bear', email: 'yolo@bear.com' }, { fields: ['name'] }); +User.create({ title: 'Chair', User: { first_name: 'Mick', last_name: 'Broadstone' } }, { include: [User] }); +User.create({ title: 'Chair', creator: { first_name: 'Matt', last_name: 'Hansen' } }, { include: [User] }); +User.create({ id: 1, title: 'e', Tags: [{ id: 1, name: 'c' }, { id: 2, name: 'd' }] }, { include: [User] }); +User.create({ id: 'My own ID!' }).then((i) => i.isNewRecord); -User.findOrInitialize( { where : { username : 'foo' } } ).then( ( p ) => p ); -User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); -User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); +User.findOrInitialize({ where: { username: 'foo' } }).then((p) => p); +User.findOrInitialize({ where: { username: 'foo' }, transaction: t }); +User.findOrInitialize({ where: { username: 'foo' }, defaults: { foo: 'asd' }, transaction: t }); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); +User.findOrCreate({ where: { a: 'b' }, defaults: { json: { a: { b: 'c' }, d: [1, 2, 3] } } }); +User.findOrCreate({ where: { a: 'b' }, defaults: { json: 'a', data: 'b' } }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); */ -User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); -User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); -User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); -User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); -User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); -User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); -User.findOrCreate( { where : 'c', defaults : {} } ); +User.findOrCreate({ where: { a: 'b' }, logging: function () { } }); +User.findOrCreate({ where: { username: 'Username' }, defaults: { data: 'some data' }, transaction: t }); +User.findOrCreate({ where: { objectId: 'asdasdasd' }, defaults: { username: 'gottlieb' } }); +User.findOrCreate({ where: { id: undefined }, defaults: { name: Math.random().toString() } }); +User.findOrCreate({ where: { email: 'unique.email.@d.com', companyId: Math.floor(Math.random() * 5) } }); +User.findOrCreate({ where: { objectId: 1 }, defaults: { bool: false } }); +User.findOrCreate({ where: 'c', defaults: {} }); -User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); +User.upsert({ id: 42, username: 'doe', foo: s.fn('upper', 'mixedCase2') }); -User.bulkCreate( [{ aNumber : 10 }, { aNumber : 12 }] ).then( ( i ) => i[0].isNewRecord ); -User.bulkCreate( [{ username : 'bar' }, { username : 'bar' }, { username : 'bar' }] ); -User.bulkCreate( [{}, {}], { validate : true, individualHooks : true } ); -User.bulkCreate( [{ style : 'ipa' }], { logging : function() { } } ); -User.bulkCreate( [{ a : 'b', c : 'd', e : 'f' }, { a : 'b', c : 'd', e : 'f' }], { fields : ['a', 'b'] } ); -User.bulkCreate( [{ name : 'foo', code : '123' }, { code : 'c' }, { name : 'bar', code : '1' }], { validate : true } ); -User.bulkCreate( [{ name : 'foo', code : '123' }, { code : '1234' }], { fields : ['code'], validate : true } ); -User.bulkCreate( [{ name : 'a', c : 'b' }, { name : 'e', c : 'f' }], { fields : ['e', 'f'], ignoreDuplicates : true } ); +User.bulkCreate([{ aNumber: 10 }, { aNumber: 12 }]).then((i) => i[0].isNewRecord); +User.bulkCreate([{ username: 'bar' }, { username: 'bar' }, { username: 'bar' }]); +User.bulkCreate([{}, {}], { validate: true, individualHooks: true }); +User.bulkCreate([{ style: 'ipa' }], { logging: function () { } }); +User.bulkCreate([{ a: 'b', c: 'd', e: 'f' }, { a: 'b', c: 'd', e: 'f' }], { fields: ['a', 'b'] }); +User.bulkCreate([{ name: 'foo', code: '123' }, { code: 'c' }, { name: 'bar', code: '1' }], { validate: true }); +User.bulkCreate([{ name: 'foo', code: '123' }, { code: '1234' }], { fields: ['code'], validate: true }); +User.bulkCreate([{ name: 'a', c: 'b' }, { name: 'e', c: 'f' }], { fields: ['e', 'f'], ignoreDuplicates: true }); User.truncate(); -User.destroy( { where : { client_id : 13 } } ).then( ( a ) => a.toFixed() ); -User.destroy( { force : true } ); -User.destroy( { where : {}, transaction : t } ); -User.destroy( { where : { access_level : { lt : 5 } } } ); -User.destroy( { truncate : true } ); -User.destroy( { where : {} } ); +User.destroy({ where: { client_id: 13 } }).then((a) => a.toFixed()); +User.destroy({ force: true }); +User.destroy({ where: {}, transaction: t }); +User.destroy({ where: { access_level: { lt: 5 } } }); +User.destroy({ truncate: true }); +User.destroy({ where: {} }); -User.restore( { where : { secretValue : '42' } } ); +User.restore({ where: { secretValue: '42' } }); -User.update( { username : 'ruben' }, { where : {} } ); -User.update( { username : 'ruben' }, { where : { access_level : { lt : 5 } } } ); -User.update( { username : 'ruben' }, { where : { username : 'dan' } } ); -User.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ); -User.update( { username : 'Bill', secretValue : '43' }, { where : { secretValue : '42' }, fields : ['username'] } ); -User.update( { username : s.cast( '1', 'char' ) }, { where : { username : 'John' } } ); -User.update( { username : s.fn( 'upper', s.col( 'username' ) ) }, { where : { username : 'John' } } ); -User.update( { username : 'Bill' }, { where : { secretValue : '42' }, returning : true } ); -User.update( { secretValue : '43' }, { where : { username : 'Peter' }, limit : 1 } ); -User.update( { name : Math.random().toString() }, { where : { id : '1' } } ); -User.update( { a : { b : 10, c : 'd' } }, { where : { username : 'Jan' }, sideEffects : false } ); -User.update( { geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } }, { - where : { - u : { - u : 'u', - geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } +User.update({ username: 'ruben' }, { where: {} }); +User.update({ username: 'ruben' }, { where: { access_level: { lt: 5 } } }); +User.update({ username: 'ruben' }, { where: { username: 'dan' } }); +User.update({ username: 'bar' }, { where: { username: 'foo' }, transaction: t }); +User.update({ username: 'Bill', secretValue: '43' }, { where: { secretValue: '42' }, fields: ['username'] }); +User.update({ username: s.cast('1', 'char') }, { where: { username: 'John' } }); +User.update({ username: s.fn('upper', s.col('username')) }, { where: { username: 'John' } }); +User.update({ username: 'Bill' }, { where: { secretValue: '42' }, returning: true }); +User.update({ secretValue: '43' }, { where: { username: 'Peter' }, limit: 1 }); +User.update({ name: Math.random().toString() }, { where: { id: '1' } }); +User.update({ a: { b: 10, c: 'd' } }, { where: { username: 'Jan' }, sideEffects: false }); +User.update({ geometry: { type: 'Point', coordinates: [49.807222, -86.984722] } }, { + where: { + u: { + u: 'u', + geometry: { type: 'Point', coordinates: [49.807222, -86.984722] } } } -} ); -User.update( { - geometry : { - type : 'Polygon', - coordinates : [[[100.0, 0.0], [102.0, 0.0], [102.0, 1.0], [100.0, 1.0], [100.0, 0.0]]] +}); +User.update({ + geometry: { + type: 'Polygon', + coordinates: [[[100.0, 0.0], [102.0, 0.0], [102.0, 1.0], [100.0, 1.0], [100.0, 0.0]]] } }, { - where : { - username : { - username : 'username', - geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } + where: { + username: { + username: 'username', + geometry: { type: 'Point', coordinates: [49.807222, -86.984722] } + } } - } -} ); + }); -User.unscoped().find( { where : { username : 'bob' } } ); +User.unscoped().find({ where: { username: 'bob' } }); User.unscoped().count(); // @@ -1048,77 +1048,77 @@ User.unscoped().count(); var queryInterface = s.getQueryInterface(); queryInterface.dropAllTables(); -queryInterface.showAllTables( { logging : function() { } } ); -queryInterface.createTable( 'table', { name : Sequelize.STRING }, { logging : function() { } } ); -queryInterface.createTable( 'skipme', { name : Sequelize.STRING } ); +queryInterface.showAllTables({ logging: function () { } }); +queryInterface.createTable('table', { name: Sequelize.STRING }, { logging: function () { } }); +queryInterface.createTable('skipme', { name: Sequelize.STRING }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.dropAllTables( { skip : ['skipme'] } ); */ -queryInterface.dropTable( 'Group', { logging : function() { } } ); -queryInterface.addIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); -queryInterface.showIndex( 'Group', { logging : function() { } } ); -queryInterface.removeIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); -queryInterface.showIndex( 'Group' ); +queryInterface.dropTable('Group', { logging: function () { } }); +queryInterface.addIndex('Group', ['username', 'isAdmin'], { logging: function () { } }); +queryInterface.showIndex('Group', { logging: function () { } }); +queryInterface.removeIndex('Group', ['username', 'isAdmin'], { logging: function () { } }); +queryInterface.showIndex('Group'); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.createTable( 'table', { name : { type : Sequelize.STRING } }, { schema : 'schema' } ); */ -queryInterface.addIndex( { schema : 'a', tableName : 'c' }, ['d', 'e'], { logging : function() {} }, 'schema_table' ); -queryInterface.showIndex( { schema : 'schema', tableName : 'table' }, { logging : function() {} } ); -queryInterface.addIndex( 'Group', ['from'] ); -queryInterface.describeTable( '_Users', { logging : function() {} } ); -queryInterface.createTable( 's', { table_id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.addIndex({ schema: 'a', tableName: 'c' }, ['d', 'e'], { logging: function () { } }, 'schema_table'); +queryInterface.showIndex({ schema: 'schema', tableName: 'table' }, { logging: function () { } }); +queryInterface.addIndex('Group', ['from']); +queryInterface.describeTable('_Users', { logging: function () { } }); +queryInterface.createTable('s', { table_id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.insert( null, 'TableWithPK', {}, { raw : true, returning : true, plain : true } ); */ -queryInterface.createTable( 'SomeTable', { someEnum : Sequelize.ENUM( 'value1', 'value2', 'value3' ) } ); -queryInterface.createTable( 'SomeTable', { someEnum : { type : Sequelize.ENUM, values : ['b1', 'b2', 'b3'] } } ); -queryInterface.createTable( 't', { someEnum : { type : Sequelize.ENUM, values : ['c1', 'c2', 'c3'], field : 'd' } } ); +queryInterface.createTable('SomeTable', { someEnum: Sequelize.ENUM('value1', 'value2', 'value3') }); +queryInterface.createTable('SomeTable', { someEnum: { type: Sequelize.ENUM, values: ['b1', 'b2', 'b3'] } }); +queryInterface.createTable('t', { someEnum: { type: Sequelize.ENUM, values: ['c1', 'c2', 'c3'], field: 'd' } }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.createTable( 'User', { name : { type : Sequelize.STRING } }, { schema : 'hero' } ); queryInterface.rawSelect( 'User', { schema : 'hero', logging : function() {} }, 'name' ); */ -queryInterface.renameColumn( '_Users', 'username', 'pseudo', { logging : function() {} } ); -queryInterface.renameColumn( { schema : 'archive', tableName : 'Users' }, 'username', 'pseudo' ); -queryInterface.renameColumn( '_Users', 'username', 'pseudo' ); -queryInterface.createTable( { tableName : 'y', schema : 'a' }, - { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, currency : Sequelize.INTEGER } ); -queryInterface.changeColumn( { tableName : 'a', schema : 'b' }, 'c', { type : Sequelize.FLOAT }, - { logging : () => s } ); -queryInterface.createTable( 'users', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); -queryInterface.createTable( 'level', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); -queryInterface.addColumn( 'users', 'someEnum', Sequelize.ENUM( 'value1', 'value2', 'value3' ) ); -queryInterface.addColumn( 'users', 'so', { type : Sequelize.ENUM, values : ['value1', 'value2', 'value3'] } ); -queryInterface.createTable( 'hosts', { - id : { - type : Sequelize.INTEGER, - primaryKey : true, - autoIncrement : true +queryInterface.renameColumn('_Users', 'username', 'pseudo', { logging: function () { } }); +queryInterface.renameColumn({ schema: 'archive', tableName: 'Users' }, 'username', 'pseudo'); +queryInterface.renameColumn('_Users', 'username', 'pseudo'); +queryInterface.createTable({ tableName: 'y', schema: 'a' }, + { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, currency: Sequelize.INTEGER }); +queryInterface.changeColumn({ tableName: 'a', schema: 'b' }, 'c', { type: Sequelize.FLOAT }, + { logging: () => s }); +queryInterface.createTable('users', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } }); +queryInterface.createTable('level', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } }); +queryInterface.addColumn('users', 'someEnum', Sequelize.ENUM('value1', 'value2', 'value3')); +queryInterface.addColumn('users', 'so', { type: Sequelize.ENUM, values: ['value1', 'value2', 'value3'] }); +queryInterface.createTable('hosts', { + id: { + type: Sequelize.INTEGER, + primaryKey: true, + autoIncrement: true }, - admin : { - type : Sequelize.INTEGER, - references : { - model : User, - key : 'id' + admin: { + type: Sequelize.INTEGER, + references: { + model: User, + key: 'id' } }, - operator : { - type : Sequelize.INTEGER, - references : { - model : User, - key : 'id' + operator: { + type: Sequelize.INTEGER, + references: { + model: User, + key: 'id' }, - onUpdate : 'cascade' + onUpdate: 'cascade' }, - owner : { - type : Sequelize.INTEGER, - references : { - model : User, - key : 'id' + owner: { + type: Sequelize.INTEGER, + references: { + model: User, + key: 'id' }, - onUpdate : 'cascade', - onDelete : 'set null' + onUpdate: 'cascade', + onDelete: 'set null' } -} ); +}); // // Query Types @@ -1128,136 +1128,136 @@ queryInterface.createTable( 'hosts', { s.getDialect(); s.validate(); s.authenticate(); -s.isDefined( '' ); -s.model( 'pp' ); -s.query( '', { raw : true } ); -s.query( '' ); -s.query( '' ).then( function( res ) {} ); -s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { raw : true, replacements : [1, 2] } ); -s.query( '', { raw : true, nest : false } ); -s.query( 'select ? as foo, ? as bar', { type : this.sequelize.QueryTypes.SELECT, replacements : [1, 2] } ); -s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { type : s.QueryTypes.SELECT } ); -s.query( 'select :one as foo, :two as bar', { raw : true, replacements : { one : 1, two : 2 } } ); -s.transaction().then( function( t ) { s.set( { foo : 'bar' }, { transaction : t } ); } ); -s.define( 'foo', { bar : Sequelize.STRING }, { collate : 'utf8_bin' } ); -s.define( 'Foto', { name : Sequelize.STRING }, { tableName : 'photos' } ); -s.databaseVersion().then( function( version ) { } ); +s.isDefined(''); +s.model('pp'); +s.query('', { raw: true }); +s.query(''); +s.query('').then(function (res) { }); +s.query({ query: 'select ? as foo, ? as bar', values: [1, 2] }, { raw: true, replacements: [1, 2] }); +s.query('', { raw: true, nest: false }); +s.query('select ? as foo, ? as bar', { type: this.sequelize.QueryTypes.SELECT, replacements: [1, 2] }); +s.query({ query: 'select ? as foo, ? as bar', values: [1, 2] }, { type: s.QueryTypes.SELECT }); +s.query('select :one as foo, :two as bar', { raw: true, replacements: { one: 1, two: 2 } }); +s.transaction().then(function (t) { s.set({ foo: 'bar' }, { transaction: t }); }); +s.define('foo', { bar: Sequelize.STRING }, { collate: 'utf8_bin' }); +s.define('Foto', { name: Sequelize.STRING }, { tableName: 'photos' }); +s.databaseVersion().then(function (version) { }); // // Sequelize // ~~~~~~~~~~~ // -new Sequelize( 'db', 'user', 'pw', { logging : false } ); -new Sequelize( 'db', 'user', 'pass', { - dialect : '', - port : 99999, - pool : {} -} ); -new Sequelize( '' ).query( '', { type : s.QueryTypes.FOREIGNKEYS, logging : function() {} } ); -new Sequelize( 'sqlite://test.sqlite' ); -new Sequelize( 'wat', 'trololo', 'wow', { port : 99999 } ); -new Sequelize( 'localhost', 'wtf', 'lol', { port : 99999 } ); -new Sequelize( 'sequelize', null, null, { - replication : { - read : { - host : 'localhost', - username : 'omg', - password : 'lol' +new Sequelize('db', 'user', 'pw', { logging: false }); +new Sequelize('db', 'user', 'pass', { + dialect: '', + port: 99999, + pool: {} +}); +new Sequelize('').query('', { type: s.QueryTypes.FOREIGNKEYS, logging: function () { } }); +new Sequelize('sqlite://test.sqlite'); +new Sequelize('wat', 'trololo', 'wow', { port: 99999 }); +new Sequelize('localhost', 'wtf', 'lol', { port: 99999 }); +new Sequelize('sequelize', null, null, { + replication: { + read: { + host: 'localhost', + username: 'omg', + password: 'lol' } } -} ); +}); -s.model( 'Project' ); +s.model('Project'); s.models['Project']; -s.define( 'Project', { - name : Sequelize.STRING -} ); +s.define('Project', { + name: Sequelize.STRING +}); -var s = new Sequelize( '' ); -var testModel = s.define( 'User', { - username : Sequelize.STRING, - secretValue : Sequelize.STRING, - data : Sequelize.STRING, - intVal : Sequelize.INTEGER, - theDate : Sequelize.DATE, - aBool : Sequelize.BOOLEAN -} ); -var testModel = s.define( 'FrozenUser', {}, { freezeTableName : true } ); -s.define( 'UserWithClassAndInstanceMethods', {}, { - classMethods : { doSmth : function() { return 1; } }, - instanceMethods : { makeItSo : function() { return 2; } } -} ); -s.define( 'UserCol', { - id : { - type : Sequelize.STRING, - defaultValue : 'User', - primaryKey : true +var s = new Sequelize(''); +var testModel = s.define('User', { + username: Sequelize.STRING, + secretValue: Sequelize.STRING, + data: Sequelize.STRING, + intVal: Sequelize.INTEGER, + theDate: Sequelize.DATE, + aBool: Sequelize.BOOLEAN +}); +var testModel = s.define('FrozenUser', {}, { freezeTableName: true }); +s.define('UserWithClassAndInstanceMethods', {}, { + classMethods: { doSmth: function () { return 1; } }, + instanceMethods: { makeItSo: function () { return 2; } } +}); +s.define('UserCol', { + id: { + type: Sequelize.STRING, + defaultValue: 'User', + primaryKey: true } -} ); -s.define( 'UserWithTwoAutoIncrements', { - userid : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, - userscore : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } -} ); -s.define( 'Foo', { - field : Sequelize.INTEGER +}); +s.define('UserWithTwoAutoIncrements', { + userid: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + userscore: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } +}); +s.define('Foo', { + field: Sequelize.INTEGER }, { - validate : { - field : function() {} - } -} ); -var UserTable = s.define( 'UserCol', { - aNumber : Sequelize.INTEGER, - createdAt : { - type : Sequelize.DATE, - defaultValue : new Date() + validate: { + field: function () { } + } + }); +var UserTable = s.define('UserCol', { + aNumber: Sequelize.INTEGER, + createdAt: { + type: Sequelize.DATE, + defaultValue: new Date() }, - updatedAt : { - type : Sequelize.DATE, - defaultValue : new Date() + updatedAt: { + type: Sequelize.DATE, + defaultValue: new Date() } -}, { timestamps : true } ); +}, { timestamps: true }); -s.define( 'UserCol', { - aNumber : Sequelize.INTEGER +s.define('UserCol', { + aNumber: Sequelize.INTEGER }, { - timestamps : true, - updatedAt : 'updatedOn', - createdAt : 'dateCreated', - deletedAt : 'deletedAtThisTime', - paranoid : true -} ); -s.define( 'UpdatingUser', { - name : Sequelize.STRING + timestamps: true, + updatedAt: 'updatedOn', + createdAt: 'dateCreated', + deletedAt: 'deletedAtThisTime', + paranoid: true + }); +s.define('UpdatingUser', { + name: Sequelize.STRING }, { - timestamps : true, - updatedAt : false, - createdAt : false, - deletedAt : 'deletedAtThisTime', - paranoid : true -} ); -s.define( 'TaskBuild', { - title : { - type : Sequelize.STRING( 50 ), - allowNull : false, - defaultValue : '' + timestamps: true, + updatedAt: false, + createdAt: false, + deletedAt: 'deletedAtThisTime', + paranoid: true + }); +s.define('TaskBuild', { + title: { + type: Sequelize.STRING(50), + allowNull: false, + defaultValue: '' } }, { - setterMethods : { - title : function() { } - } -} ); -s.define( 'UserCol', { - aNumber : Sequelize.INTEGER + setterMethods: { + title: function () { } + } + }); +s.define('UserCol', { + aNumber: Sequelize.INTEGER }, { - paranoid : true, - underscored : true -} ); + paranoid: true, + underscored: true + }); -s.define( 'UserWithUniqueUsername', { - username : { type : Sequelize.STRING, unique : { name : 'user_and_email', msg : 'User and email must be unique' } }, - email : { type : Sequelize.STRING, unique : 'user_and_email' } -} ); +s.define('UserWithUniqueUsername', { + username: { type: Sequelize.STRING, unique: { name: 'user_and_email', msg: 'User and email must be unique' } }, + email: { type: Sequelize.STRING, unique: 'user_and_email' } +}); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 s.define( 'UserWithUniqueUsername', { user_id : { type : Sequelize.INTEGER }, @@ -1273,271 +1273,271 @@ s.define( 'UserWithUniqueUsername', { }] } ); */ -s.define( 'TaskBuild', { - title : { type : Sequelize.STRING, defaultValue : 'a task!' }, - foo : { type : Sequelize.INTEGER, defaultValue : 2 }, - bar : { type : Sequelize.DATE }, - foobar : { type : Sequelize.TEXT, defaultValue : 'asd' }, - flag : { type : Sequelize.BOOLEAN, defaultValue : false } -} ); -s.define( 'ProductWithSettersAndGetters1', { - price : { - type : Sequelize.INTEGER, - get : function() { - return 'answer = ' + this.getDataValue( 'price' ); +s.define('TaskBuild', { + title: { type: Sequelize.STRING, defaultValue: 'a task!' }, + foo: { type: Sequelize.INTEGER, defaultValue: 2 }, + bar: { type: Sequelize.DATE }, + foobar: { type: Sequelize.TEXT, defaultValue: 'asd' }, + flag: { type: Sequelize.BOOLEAN, defaultValue: false } +}); +s.define('ProductWithSettersAndGetters1', { + price: { + type: Sequelize.INTEGER, + get: function () { + return 'answer = ' + this.getDataValue('price'); }, - set : function( v ) { - return this.setDataValue( 'price', v + 42 ); + set: function (v) { + return this.setDataValue('price', v + 42); } } -} ); -s.define( 'ProductWithSettersAndGetters2', { - priceInCents : Sequelize.INTEGER +}); +s.define('ProductWithSettersAndGetters2', { + priceInCents: Sequelize.INTEGER }, { - setterMethods : { - price : function( value ) { - this.dataValues.priceInCents = value * 100; - } - }, - getterMethods : { - price : function() { - return '$' + (this.getDataValue( 'priceInCents' ) / 100); + setterMethods: { + price: function (value) { + this.dataValues.priceInCents = value * 100; + } }, + getterMethods: { + price: function () { + return '$' + (this.getDataValue('priceInCents') / 100); + }, - priceInCents : function() { - return this.dataValues.priceInCents; + priceInCents: function () { + return this.dataValues.priceInCents; + } } - } -} ); + }); -s.define( 'post', { - title : Sequelize.STRING, - authorId : { type : Sequelize.INTEGER, references : testModel, referencesKey : 'id' } +s.define('post', { + title: Sequelize.STRING, + authorId: { type: Sequelize.INTEGER, references: testModel, referencesKey: 'id' } } as any /* TODO please remove `as any` */); -s.define( 'post', { - title : Sequelize.STRING, - authorId : { type : Sequelize.INTEGER, references : { model : testModel, key : 'id' } } -} ); +s.define('post', { + title: Sequelize.STRING, + authorId: { type: Sequelize.INTEGER, references: { model: testModel, key: 'id' } } +}); -s.define( 'User', { - username : Sequelize.STRING, - geometry : Sequelize.GEOMETRY( 'POINT' ) -} ); +s.define('User', { + username: Sequelize.STRING, + geometry: Sequelize.GEOMETRY('POINT') +}); -s.define( 'ScopeMe', { - username : Sequelize.STRING, - email : Sequelize.STRING, - access_level : Sequelize.INTEGER, - other_value : Sequelize.INTEGER, - parent_id : Sequelize.INTEGER +s.define('ScopeMe', { + username: Sequelize.STRING, + email: Sequelize.STRING, + access_level: Sequelize.INTEGER, + other_value: Sequelize.INTEGER, + parent_id: Sequelize.INTEGER }, { - defaultScope : { - where : { - access_level : { - gte : 5 - } - } - }, - scopes : { - isTony : { - where : { - username : 'tony' - } - }, - } -} ); -s.define( 'company', { - active : Sequelize.BOOLEAN -}, { - defaultScope : { - where : { active : true } - }, - scopes : { - notActive : { - where : { - active : false - } - }, - reversed : { - order : [['id', 'DESC']] - } - } -} ); -s.define( 'profile', { - active : Sequelize.BOOLEAN -}, { - defaultScope : { - where : { active : true } - }, - scopes : { - notActive : { - where : { - active : false - } - }, - } -} ); - -s.define( 'ScopeMe', { - username : Sequelize.STRING, - email : Sequelize.STRING, - access_level : Sequelize.INTEGER, - other_value : Sequelize.INTEGER -}, { - defaultScope : { - where : { - access_level : { - gte : 5 - } - } - }, - scopes : { - lowAccess : { - where : { - access_level : { - lte : 5 + defaultScope: { + where: { + access_level: { + gte: 5 } } }, - withOrder : { - order : 'username' + scopes: { + isTony: { + where: { + username: 'tony' + } + }, } - } -} ); - -s.define( 'ScopeMe', { - username : Sequelize.STRING, - email : Sequelize.STRING, - access_level : Sequelize.INTEGER, - other_value : Sequelize.INTEGER + }); +s.define('company', { + active: Sequelize.BOOLEAN }, { - defaultScope : { - where : { - access_level : { - gte : 5 + defaultScope: { + where: { active: true } + }, + scopes: { + notActive: { + where: { + active: false + } + }, + reversed: { + order: [['id', 'DESC']] } } - }, - scopes : { - lowAccess : { - where : { - access_level : { - lte : 5 + }); +s.define('profile', { + active: Sequelize.BOOLEAN +}, { + defaultScope: { + where: { active: true } + }, + scopes: { + notActive: { + where: { + active: false + } + }, + } + }); + +s.define('ScopeMe', { + username: Sequelize.STRING, + email: Sequelize.STRING, + access_level: Sequelize.INTEGER, + other_value: Sequelize.INTEGER +}, { + defaultScope: { + where: { + access_level: { + gte: 5 + } + } + }, + scopes: { + lowAccess: { + where: { + access_level: { + lte: 5 + } + } + }, + withOrder: { + order: 'username' + } + } + }); + +s.define('ScopeMe', { + username: Sequelize.STRING, + email: Sequelize.STRING, + access_level: Sequelize.INTEGER, + other_value: Sequelize.INTEGER +}, { + defaultScope: { + where: { + access_level: { + gte: 5 + } + } + }, + scopes: { + lowAccess: { + where: { + access_level: { + lte: 5 + } } } } - } -} ); + }); -s.define( 'user', { - id : { - type : Sequelize.INTEGER, - allowNull : false, - primaryKey : true, - autoIncrement : true, - field : 'userId' +s.define('user', { + id: { + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true, + autoIncrement: true, + field: 'userId' }, - name : { - type : Sequelize.STRING, - field : 'full_name' + name: { + type: Sequelize.STRING, + field: 'full_name' }, - taskCount : { - type : Sequelize.INTEGER, - field : 'task_count', - defaultValue : 0, - allowNull : false + taskCount: { + type: Sequelize.INTEGER, + field: 'task_count', + defaultValue: 0, + allowNull: false } }, { - tableName : 'users', - timestamps : false -} ); -s.define( 'task', { - id : { - type : Sequelize.INTEGER, - allowNull : false, - primaryKey : true, - autoIncrement : true, - field : 'taskId' + tableName: 'users', + timestamps: false + }); +s.define('task', { + id: { + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true, + autoIncrement: true, + field: 'taskId' }, - title : { - type : Sequelize.STRING, - field : 'name' + title: { + type: Sequelize.STRING, + field: 'name' } }, { - tableName : 'tasks', - timestamps : false -} ); -s.define( 'comment', { - id : { - type : Sequelize.INTEGER, - allowNull : false, - primaryKey : true, - autoIncrement : true, - field : 'commentId' + tableName: 'tasks', + timestamps: false + }); +s.define('comment', { + id: { + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true, + autoIncrement: true, + field: 'commentId' }, - text : { - type : Sequelize.STRING, - field : 'comment_text' + text: { + type: Sequelize.STRING, + field: 'comment_text' }, - notes : { - type : Sequelize.STRING, - field : 'notes' + notes: { + type: Sequelize.STRING, + field: 'notes' } }, { - tableName : 'comments', - timestamps : false -} ); -s.define( 'test', { - id : { - type : Sequelize.INTEGER, - field : 'test_id', - autoIncrement : true, - primaryKey : true, - validate : { - min : 1 + tableName: 'comments', + timestamps: false + }); +s.define('test', { + id: { + type: Sequelize.INTEGER, + field: 'test_id', + autoIncrement: true, + primaryKey: true, + validate: { + min: 1 } }, - title : { - allowNull : false, - type : Sequelize.STRING( 255 ), - field : 'test_title' + title: { + allowNull: false, + type: Sequelize.STRING(255), + field: 'test_title' } }, { - timestamps : true, - underscored : true, - freezeTableName : true -} ); + timestamps: true, + underscored: true, + freezeTableName: true + }); -s.define( 'User', { - deletedAt : { - type : Sequelize.DATE, - field : 'deleted_at' +s.define('User', { + deletedAt: { + type: Sequelize.DATE, + field: 'deleted_at' } }, { - timestamps : true, - paranoid : true -} ); + timestamps: true, + paranoid: true + }); -s.define( 'TriggerTest', { - id : { - type : Sequelize.INTEGER, - field : 'test_id', - autoIncrement : true, - primaryKey : true, - validate : { - min : 1 +s.define('TriggerTest', { + id: { + type: Sequelize.INTEGER, + field: 'test_id', + autoIncrement: true, + primaryKey: true, + validate: { + min: 1 } }, - title : { - allowNull : false, - type : Sequelize.STRING( 255 ), - field : 'test_title' + title: { + allowNull: false, + type: Sequelize.STRING(255), + field: 'test_title' } }, { - timestamps : false, - underscored : true, - hasTrigger : true -} ); + timestamps: false, + underscored: true, + hasTrigger: true + }); // // Transaction @@ -1546,68 +1546,80 @@ s.define( 'TriggerTest', { // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/transaction.test.js // -s.transaction().then( function( t ) { +s.transaction().then(function (t) { t.commit(); t.rollback(); - User.find( { - where : { - username : 'John' + User.find({ + where: { + username: 'John' }, - include : [User], - lock : t.LOCK.UPDATE, - transaction : t - } ); - User.find( { - where : { - username : 'John' + include: [User], + lock: t.LOCK.UPDATE, + transaction: t + }); + User.find({ + where: { + username: 'John' }, - include : [User], - lock : { - level : t.LOCK.UPDATE, - of : User + include: [User], + lock: { + level: t.LOCK.UPDATE, + of: User }, - transaction : t - } ); - User.update( { - active : true + transaction: t + }); + User.update({ + active: true }, { - where : { - active : false + where: { + active: false + }, + transaction: t + }); + User.find({ + where: { + username: 'jan' }, - transaction : t - } ); - User.find( { - where : { - username : 'jan' + lock: t.LOCK.NO_KEY_UPDATE, + transaction: t + }); + User.find({ + where: { + username: 'jan' }, - lock : t.LOCK.NO_KEY_UPDATE, - transaction : t - } ); - User.find( { - where : { - username : 'jan' - }, - lock : t.LOCK.KEY_SHARE, - transaction : t - } ); + lock: t.LOCK.KEY_SHARE, + transaction: t + }); -} ); +}); -s.transaction( function() { +s.transaction({ + isolationLevel: s.Transaction.ISOLATION_LEVELS.READ_COMMITTED +}).then(function (t2) { + return User.find({ + where: { + username: 'jan' + }, + lock: t2.LOCK.UPDATE, + transaction: t2 + }); +}); + +s.transaction(function () { return Promise.resolve(); -} ); -s.transaction( { isolationLevel : 'SERIALIZABLE' }, function( t ) { return Promise.resolve(); } ); -s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.SERIALIZABLE }, (t) => Promise.resolve() ); -s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.READ_COMMITTED }, (t) => Promise.resolve() ); +}); +s.transaction({ isolationLevel: 'SERIALIZABLE' }, function (t) { return Promise.resolve(); }); +s.transaction({ isolationLevel: s.Transaction.ISOLATION_LEVELS.SERIALIZABLE }, (t) => Promise.resolve()); +s.transaction({ isolationLevel: s.Transaction.ISOLATION_LEVELS.READ_COMMITTED }, (t) => Promise.resolve()); // transaction types -new Sequelize( '', { transactionType: 'DEFERRED' } ); -new Sequelize( '', { transactionType: Sequelize.Transaction.TYPES.DEFERRED} ); -new Sequelize( '', { transactionType: Sequelize.Transaction.TYPES.IMMEDIATE} ); -new Sequelize( '', { transactionType: Sequelize.Transaction.TYPES.EXCLUSIVE} ); -s.transaction( { type : 'DEFERRED' }, (t) => Promise.resolve() ); -s.transaction( { type : s.Transaction.TYPES.DEFERRED }, (t) => Promise.resolve() ); -s.transaction( { type : s.Transaction.TYPES.IMMEDIATE }, (t) => Promise.resolve() ); -s.transaction( { type : s.Transaction.TYPES.EXCLUSIVE }, (t) => Promise.resolve() ); +new Sequelize('', { transactionType: 'DEFERRED' }); +new Sequelize('', { transactionType: Sequelize.Transaction.TYPES.DEFERRED }); +new Sequelize('', { transactionType: Sequelize.Transaction.TYPES.IMMEDIATE }); +new Sequelize('', { transactionType: Sequelize.Transaction.TYPES.EXCLUSIVE }); +s.transaction({ type: 'DEFERRED' }, (t) => Promise.resolve()); +s.transaction({ type: s.Transaction.TYPES.DEFERRED }, (t) => Promise.resolve()); +s.transaction({ type: s.Transaction.TYPES.IMMEDIATE }, (t) => Promise.resolve()); +s.transaction({ type: s.Transaction.TYPES.EXCLUSIVE }, (t) => Promise.resolve()); From a84ff5234e5e3d83c36aea98fdc5c25d0bfa50ea Mon Sep 17 00:00:00 2001 From: Konrad Mattheis Date: Sat, 20 May 2017 00:40:18 +0200 Subject: [PATCH 0026/1618] * move qlik-engineapi types from / to new /types --- {qlik-engineapi => types/qlik-engineapi}/index.d.ts | 0 {qlik-engineapi => types/qlik-engineapi}/qlik-engineapi-tests.ts | 0 {qlik-engineapi => types/qlik-engineapi}/tsconfig.json | 0 {qlik-engineapi => types/qlik-engineapi}/tslint.json | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename {qlik-engineapi => types/qlik-engineapi}/index.d.ts (100%) rename {qlik-engineapi => types/qlik-engineapi}/qlik-engineapi-tests.ts (100%) rename {qlik-engineapi => types/qlik-engineapi}/tsconfig.json (100%) rename {qlik-engineapi => types/qlik-engineapi}/tslint.json (100%) diff --git a/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts similarity index 100% rename from qlik-engineapi/index.d.ts rename to types/qlik-engineapi/index.d.ts diff --git a/qlik-engineapi/qlik-engineapi-tests.ts b/types/qlik-engineapi/qlik-engineapi-tests.ts similarity index 100% rename from qlik-engineapi/qlik-engineapi-tests.ts rename to types/qlik-engineapi/qlik-engineapi-tests.ts diff --git a/qlik-engineapi/tsconfig.json b/types/qlik-engineapi/tsconfig.json similarity index 100% rename from qlik-engineapi/tsconfig.json rename to types/qlik-engineapi/tsconfig.json diff --git a/qlik-engineapi/tslint.json b/types/qlik-engineapi/tslint.json similarity index 100% rename from qlik-engineapi/tslint.json rename to types/qlik-engineapi/tslint.json From 7fbcd08359659b6f9db5cec24bdc6f155622ad7f Mon Sep 17 00:00:00 2001 From: Konrad Mattheis Date: Sat, 20 May 2017 01:24:13 +0200 Subject: [PATCH 0027/1618] fix TSLint errors Signed-off-by: Konrad Mattheis --- types/qlik-engineapi/index.d.ts | 70 ++++++++------------ types/qlik-engineapi/qlik-engineapi-tests.ts | 1 + types/qlik-engineapi/tslint.json | 8 +-- 3 files changed, 33 insertions(+), 46 deletions(-) diff --git a/types/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts index 4baf80e8fe..6b6adc25d8 100644 --- a/types/qlik-engineapi/index.d.ts +++ b/types/qlik-engineapi/index.d.ts @@ -101,7 +101,7 @@ declare namespace EngineAPI { interface IGenericProperties { qInfo: INxInfo; - //?Dynamic properties? + // ?Dynamic properties? [qMetaDef: string]: any; } @@ -1021,10 +1021,10 @@ declare namespace EngineAPI { } interface IImplementOn { - //? nicht in der docu - on(event: "changed" | "closed", func: () => void); + // ? not in Docu + on(event: "changed" | "closed", func: () => void): void; - //? not in Docu + // ? not in Docu id: string; } @@ -1053,7 +1053,13 @@ declare namespace EngineAPI { getChild(qId: string): Promise; getEffectiveProperties(): Promise; getFullPropertyTree(): Promise; - getHyperCubeBinnedData(qPath: string, qPages: INxPage[], qViewport: INxViewPort, qDataRanges: INxDataAreaPage, qMaxNbrCells: number, qQueryLevel: number, qBinningMethod: number): Promise; + getHyperCubeBinnedData(qPath: string, + qPages: INxPage[], + qViewport: INxViewPort, + qDataRanges: INxDataAreaPage, + qMaxNbrCells: number, + qQueryLevel: number, + qBinningMethod: number): Promise; getHyperCubeContinuousData(qPath: string, qOptions: IContinuousDataOptions[]): Promise | Promise | Promise; getHyperCubeData(qPath: string, qPages: INxPage[]): Promise; getHyperCubePivotData(qPath: string, qPages: INxPage[]): Promise; @@ -1287,13 +1293,13 @@ declare namespace EngineAPI { cancelRequest(qRequestId: number): Promise; configureReload(qCancelOnScriptError: boolean, qUseErrorData: boolean, qInteractOnError: boolean): Promise; copyApp(qTargetAppId: string, qSrcAppId: string, qIds: string[]): Promise; - createApp(qAppName: string, qLocalizedScriptMainSection: string): Promise; //?Result + createApp(qAppName: string, qLocalizedScriptMainSection: string): Promise; // ?Result createDocEx(qDocName: string, qUserName?: string, qPassword?: string, qSerial?: string, qLocalizedScriptMainSection?: string): Promise; createSessionApp(): Promise; createSessionAppFromApp(qSrcAppId: string): Promise; deleteApp(qAppId: string): Promise; exportApp(qTargetPath: string, qSrcAppId: string, qIds: string[]): Promise; - getActiveDoc(): Promise; //?Result + getActiveDoc(): Promise; // ?Result getAppEntry(qAppID: string): Promise; getAuthenticatedUser(): Promise; getBNF(qBnfType: BnfType): Promise; @@ -1595,7 +1601,7 @@ declare namespace EngineAPI { * Validation error. * REF(NxValidationError) */ - //?Type = REF(NxValidationError)? + // ?Type = REF(NxValidationError)? qError: INxValidationError; } @@ -1743,8 +1749,8 @@ declare namespace EngineAPI { qAttributeExpressions?: INxAttrExprDef[]; qAttributeDimensions?: INxAttrDimDef[]; - qIncludeElemValue?: boolean; //?Nicht in Doku - qShowTotal?: boolean; //?Nicht in Doku + qIncludeElemValue?: boolean; // ?Nicht in Doku + qShowTotal?: boolean; // ?Nicht in Doku } interface INxCellPosition { @@ -1765,7 +1771,7 @@ declare namespace EngineAPI { qSortByExpression?: TypeSortDirection; qExpression?: IValueExpr; - qSortByGreyness?: TypeSortDirection; //?Nicht in Doku + qSortByGreyness?: TypeSortDirection; // ?Nicht in Doku } interface IStringExpressionContainer { @@ -1825,20 +1831,20 @@ declare namespace EngineAPI { qData: T; } - //public enum NxHypercubeMode { + // public enum NxHypercubeMode { // [QixName("P: // DATA_MODE_PIVOT = 1, // [QixName("K: // DATA_MODE_PIVOT_STACK = 2, // [QixName("S: // DATA_MODE_STRAIGHT = 0 - //} + // } - //public enum SortDirection { + // public enum SortDirection { // Ascending = 1, // Descending = -1, // None = 0 - //} + // } } //#region Prototype Interfaces for Class definitions @@ -1957,8 +1963,8 @@ declare namespace EngineAPI { qCalcCond: IValueExpr; qSortbyYValue: string; - qPseudoDimPos: number; //?Dokufehler - qReductionMode: ReductionModeType; //?Dokufehler + qPseudoDimPos: number; // ?Dokufehler + qReductionMode: ReductionModeType; // ?Dokufehler } interface IVisualizationHyperCubeDef extends IHyperCubeDef { @@ -2059,7 +2065,7 @@ declare namespace EngineAPI { interface IBookmarkListDef { qType: "bookmark"; - // qData: //?nicht dokumentiert + // qData: nicht dokumentiert // example from websocket // qData: { title: "/qMetaDef/title", description: "/qMetaDef/description", sheetId: "/sheetId", title: "/qMetaDef/title" } } @@ -2101,7 +2107,7 @@ declare namespace EngineAPI { interface IMeasureListDef { qType: "measure"; - // qData: INxMeasure[]; //?nicht dokumentiert + // qData: INxMeasure[]; nicht dokumentiert // example from websocket // qData : { title: "/qMetaDef/title", tags: "/qMetaDef/tags" } } @@ -2143,7 +2149,7 @@ declare namespace EngineAPI { interface IDimensionListDef { qType: "dimension"; - //qData: INxDimension[]; //?nicht dokumentiert + // qData: INxDimension[]; nicht dokumentiert } interface IDimensionListObject extends IGenericObject { @@ -2167,7 +2173,7 @@ declare namespace EngineAPI { qIsReserved?: boolean; qMeta?: INxMeta; qInfo: INxInfo; - qData: any; //?nicht dokumentiert + qData: any; // ? nicht dokumentiert qIsScriptCreated: boolean; } @@ -2187,7 +2193,7 @@ declare namespace EngineAPI { qType: string; qShowReserved: boolean; qShowConfig: boolean; - qData: any; //?nicht dokumentiert + qData: any; // ?nicht dokumentiert } interface IVariableListObject extends IGenericObject { @@ -2271,23 +2277,3 @@ declare namespace EngineAPI { } } //#endregion - -// extens the AppAPI Namespace with the access of the EnigmaModel - -declare namespace AppAPI { - interface IApp { - model: IModel; - } - - interface IModel { - enigmaModel: Enigma.IApp; - } -} - -declare namespace ExtensionAPI { - - interface IExtensionModel { - enigmaModel: Enigma.IGenericObject; - } - -} \ No newline at end of file diff --git a/types/qlik-engineapi/qlik-engineapi-tests.ts b/types/qlik-engineapi/qlik-engineapi-tests.ts index e69de29bb2..3484d95073 100644 --- a/types/qlik-engineapi/qlik-engineapi-tests.ts +++ b/types/qlik-engineapi/qlik-engineapi-tests.ts @@ -0,0 +1 @@ +let app: EngineAPI.IApp; diff --git a/types/qlik-engineapi/tslint.json b/types/qlik-engineapi/tslint.json index cae1bdf2ad..9a48ae7955 100644 --- a/types/qlik-engineapi/tslint.json +++ b/types/qlik-engineapi/tslint.json @@ -1,8 +1,8 @@ -{ - "extends": "../tslint.json", +{ + "extends": "dtslint/dt.json", "rules": { - "forbidden-types": false, + "ban-types": false, "no-empty-interface": false, "interface-name": false } -} \ No newline at end of file +} From 23b7cd16744128ce293bad27f9760773e3dff5ce Mon Sep 17 00:00:00 2001 From: Flur Date: Mon, 12 Jun 2017 15:45:17 +0300 Subject: [PATCH 0028/1618] * add OBJLoader * add MTLLoader * Geometry merge add parameter * Object3D onBeforeRender, on AfterRender * Object3D add delete fixed number of parameters --- types/three/index.d.ts | 4 ++- types/three/three-core.d.ts | 19 ++++++++++-- types/three/three-examples.d.ts | 1 - types/three/three-mtlloader.d.ts | 52 ++++++++++++++++++++++++++++++++ types/three/three-objloader.d.ts | 21 +++++++++++++ 5 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 types/three/three-mtlloader.d.ts create mode 100644 types/three/three-objloader.d.ts diff --git a/types/three/index.d.ts b/types/three/index.d.ts index b8c5b5669f..17156bed94 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -25,5 +25,7 @@ export * from "./three-trackballcontrols"; export * from "./three-transformcontrols"; export * from "./three-vrcontrols"; export * from "./three-vreffect"; +export * from "./three-objloader"; +export * from "./three-mtlloader"; -export as namespace THREE; \ No newline at end of file +export as namespace THREE; diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 5679c4e8c7..ea0e6f917c 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -1355,7 +1355,7 @@ export class Geometry extends EventDispatcher { */ computeBoundingSphere(): void; - merge(geometry: Geometry, matrix: Matrix, materialIndexOffset?: number): void; + merge(geometry: Geometry, matrix?: Matrix, materialIndexOffset?: number): void; mergeMesh(mesh: Mesh): void; @@ -1605,6 +1605,18 @@ export class Object3D extends EventDispatcher { */ userData: any; + /** + * Calls before rendering object + */ + onBeforeRender: (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, geometry: THREE.Geometry | THREE.BufferGeometry, + material: THREE.Material, group: THREE.Group) => any; + + /** + * Calls after rendering object + */ + onAfterRender: (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, geometry: THREE.Geometry | THREE.BufferGeometry, + material: THREE.Material, group: THREE.Group) => any; + /** * */ @@ -1706,7 +1718,7 @@ export class Object3D extends EventDispatcher { /** * Adds object as child of this object. */ - add(object: Object3D): void; + add(...object: Object3D[]): void; /** * Removes object as child of this object. @@ -2796,9 +2808,12 @@ export class MeshPhysicalMaterial extends MeshStandardMaterial { export class MultiMaterial extends Material { constructor(materials?: Material[]); + isMultiMaterial: true; + materials: Material[]; toJSON(meta: any): any; + } /** diff --git a/types/three/three-examples.d.ts b/types/three/three-examples.d.ts index d416757b00..67efcc566a 100644 --- a/types/three/three-examples.d.ts +++ b/types/three/three-examples.d.ts @@ -3,7 +3,6 @@ import {EventDispatcher, Shader} from "./three-core"; export var AWDLoader: any; -export var OBJLoader: any; export var OBJLoader2: any; export var STLLoader: any; export var FlyControls: any; diff --git a/types/three/three-mtlloader.d.ts b/types/three/three-mtlloader.d.ts new file mode 100644 index 0000000000..5113d67df2 --- /dev/null +++ b/types/three/three-mtlloader.d.ts @@ -0,0 +1,52 @@ + +import {Material} from "./three-core"; +import {LoadingManager} from "./three-core"; +import {EventDispatcher} from "./three-core"; +import {BufferGeometry} from "./three-core"; +import {Texture} from "./three-core"; + +export class MTLLoader extends EventDispatcher { + + constructor(manager?: LoadingManager); + manager: LoadingManager; + materialOptions: {}; + materials: Material[]; + path: string; + texturePath: string; + crossOrigin: boolean; + + load(url: string, onLoad: (materialCreator: MaterialCreator) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + parse(text: string) : MaterialCreator; + setPath(path: string) : void; + setTexturePath(path: string) : void; + setBaseUrl(path: string) : void; + setCrossOrigin(value: boolean) : void; + setMaterialOptions(value: any) : void; +} + +export class MaterialCreator { + + constructor(baseUrl?: string, options?: any); + + baseUrl : string; + options : any; + materialsInfo : any; + materials : any; + materialsArray : Material[]; + nameLookup : any; + side : number; + wrap : number; + + setCrossOrigin( value: boolean ) : void; + setManager( value: any ) : void; + setMaterials( materialsInfo: any ) : void; + convert( materialsInfo: any ) : any; + preload() : void; + getIndex( materialName: string ) : Material; + getAsArray() : Material[]; + create( materialName: string ) : Material; + createMaterial_( materialName: string ) : Material; + getTextureParams( value: string, matParams: any ) : any; + loadTexture(url: string, mapping: any, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): Texture; + +} diff --git a/types/three/three-objloader.d.ts b/types/three/three-objloader.d.ts new file mode 100644 index 0000000000..25a3adf93f --- /dev/null +++ b/types/three/three-objloader.d.ts @@ -0,0 +1,21 @@ + +import {Material} from "./three-core"; +import {LoadingManager} from "./three-core"; +import {Group} from "./three-core"; +import {MaterialCreator} from "./three-mtlloader"; + +export class OBJLoader { + + constructor(manager?: LoadingManager); + manager: LoadingManager; + regexp: any; + materials: Material[]; + path: string; + + load(url: string, onLoad: (group: Group) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + parse(data: string) : Group; + setPath(value: string) : void; + setMaterials(materials: MaterialCreator) : void; + _createParserState() : any; + +} From f1706757e0bea678d644e9d4452c1139f6435926 Mon Sep 17 00:00:00 2001 From: Christopher Cortes Date: Mon, 12 Jun 2017 17:50:31 +0200 Subject: [PATCH 0029/1618] [nouislider]: fix TSC error: "global module exports may only appear at top level". Fix Callback signature (unencodedValues) Fix TSC error: "global module exports may only appear at top level" (remove wrong duplicate namespace export). Fix Callback interface: unencodedValues is an array of values instead of single value. --- types/nouislider/index.d.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/types/nouislider/index.d.ts b/types/nouislider/index.d.ts index 9662de4204..b905991a18 100644 --- a/types/nouislider/index.d.ts +++ b/types/nouislider/index.d.ts @@ -5,7 +5,6 @@ /// export = noUiSlider; -export as namespace noUiSlider; declare namespace noUiSlider { /** @@ -155,10 +154,9 @@ declare namespace noUiSlider { * Array for both one-handle and two-handle sliders. It contains the current slider values, * with formatting applied. */ - (values: any[], handle: number, unencoded: number): void + (values: any[], handle: number, unencodedValues: number[]): void; } - interface noUiSlider { /** * Bind event to the slider. @@ -193,6 +191,6 @@ declare namespace noUiSlider { } interface Instance extends HTMLElement { - noUiSlider: noUiSlider + noUiSlider: noUiSlider; } } From b9bdcb0fd856bec6bf9d9a2fb50f5e7cb5a5b805 Mon Sep 17 00:00:00 2001 From: Christopher Cortes Date: Fri, 16 Jun 2017 13:09:26 +0200 Subject: [PATCH 0030/1618] =?UTF-8?q?[nouislider]:=20fix=20TSC=20error:=20?= =?UTF-8?q?"global=20module=20exports=20may=20only=20appear=20a=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- types/nouislider/index.d.ts | 359 ++++++++++++++++++------------------ 1 file changed, 181 insertions(+), 178 deletions(-) diff --git a/types/nouislider/index.d.ts b/types/nouislider/index.d.ts index b905991a18..a8a68ef378 100644 --- a/types/nouislider/index.d.ts +++ b/types/nouislider/index.d.ts @@ -4,193 +4,196 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -export = noUiSlider; +declare module "nouislider" { -declare namespace noUiSlider { - /** - * To create a slider, call noUiSlider.create() with an element and your options. - */ - function create(target: HTMLElement, options: Options): void; + export = noUiSlider; - interface Options { + namespace noUiSlider { /** - * The start option sets the number of handles and their start positions, relative to range. + * To create a slider, call noUiSlider.create() with an element and your options. */ - start: number | number[] | number[][]; - /** - * The connect setting can be used to control the bar between the handles, - * or the edges of the slider. Use "lower" to connect to the lower side, - * or "upper" to connect to the upper side. Setting true sets the bar between the handles. - */ - range: Object; - /** - * The connect setting can be used to control the (green) bar between the handles, or the edges of the slider. - * Pass an array with a boolean for every connecting element, including the edges of the slider. - * The length of this array must match the handle count + 1. - * Setting true sets the bars between the handles, but not between the handles and the sliders edges. - */ - connect?: boolean | boolean[]; - /** - * When using two handles, the minimum distance between the handles can be set using the margin option. - * The margin value is relative to the value set in 'range'. - * This option is only available on standard linear sliders. - */ - margin?: number; - /** - * The limit option is the oposite of the margin option, - * limiting the maximum distance between two handles. - * As with the margin option, the limit option can only be used on linear sliders. - */ - limit?: number; - /** - * By default, the slider slides fluently. - * In order to make the handles jump between intervals, you can use this option. - * The step option is relative to the values provided to range. - */ - step?: number; - /** - * The orientation setting can be used to set the slider to "vertical" or "horizontal". - * Set dimensions! Vertical sliders don't assume a default height, so you'll need to set one. - * You can use any unit you want, including % or px. - */ - orientation?: string; // "vertical" | "horizontal" - /** - * By default the sliders are top-to-bottom and left-to-right, - * but you can change this using the direction option, - * which decides where the upper side of the slider is. - */ - direction?: string; // "ltr" | "rtl" - /** - * noUiSlider can provide a basic tooltip without using its events system. - * Set the tooltips option to true to enable. - * This option can also accept formatting options to format the tooltips content. - * In that case, pass an array with a formatter for each handle, true to use the default or false to display no tooltip. - */ - tooltips?: boolean | Object | ((...args:any[]) => any); - /** - * Set the animate option to false to prevent the slider from animating to a new value with when calling .val(). - */ - animate?: boolean; - /** - * The animationDuration option can be used to set the animation speed assumed by the slider library. In addition to this, you must manually set the CSS (-webkit-)transition property for the .noUi-state-tap .noUi-origin selector. - */ - animationDuration?: number; - /** - * When a non-linear slider has been configured, the snap option can be set to true to force the slider to jump between the specified values. - */ - snap?: boolean; - /** - * All values on the slider are part of a range. The range has a minimum and maximum value. - */ - behaviour?: string; - /** - * To format the slider output, noUiSlider offers a format option. - * Simply specify to and from functions to encode and decode the values. - * See manual formatting to the right for usage information. - * By default, noUiSlider will format output with 2 decimals. - */ - format?: Object | ((...args:any[]) => any); + function create(target: HTMLElement, options: Options): void; - /** - * Allows you to generate points along the slider. - */ - pips?: PipsOptions; - } + interface Options { + /** + * The start option sets the number of handles and their start positions, relative to range. + */ + start: number | number[] | number[][]; + /** + * The connect setting can be used to control the bar between the handles, + * or the edges of the slider. Use "lower" to connect to the lower side, + * or "upper" to connect to the upper side. Setting true sets the bar between the handles. + */ + range: Object; + /** + * The connect setting can be used to control the (green) bar between the handles, or the edges of the slider. + * Pass an array with a boolean for every connecting element, including the edges of the slider. + * The length of this array must match the handle count + 1. + * Setting true sets the bars between the handles, but not between the handles and the sliders edges. + */ + connect?: boolean | boolean[]; + /** + * When using two handles, the minimum distance between the handles can be set using the margin option. + * The margin value is relative to the value set in 'range'. + * This option is only available on standard linear sliders. + */ + margin?: number; + /** + * The limit option is the oposite of the margin option, + * limiting the maximum distance between two handles. + * As with the margin option, the limit option can only be used on linear sliders. + */ + limit?: number; + /** + * By default, the slider slides fluently. + * In order to make the handles jump between intervals, you can use this option. + * The step option is relative to the values provided to range. + */ + step?: number; + /** + * The orientation setting can be used to set the slider to "vertical" or "horizontal". + * Set dimensions! Vertical sliders don't assume a default height, so you'll need to set one. + * You can use any unit you want, including % or px. + */ + orientation?: string; // "vertical" | "horizontal" + /** + * By default the sliders are top-to-bottom and left-to-right, + * but you can change this using the direction option, + * which decides where the upper side of the slider is. + */ + direction?: string; // "ltr" | "rtl" + /** + * noUiSlider can provide a basic tooltip without using its events system. + * Set the tooltips option to true to enable. + * This option can also accept formatting options to format the tooltips content. + * In that case, pass an array with a formatter for each handle, true to use the default or false to display no tooltip. + */ + tooltips?: boolean | Object | ((...args:any[]) => any); + /** + * Set the animate option to false to prevent the slider from animating to a new value with when calling .val(). + */ + animate?: boolean; + /** + * The animationDuration option can be used to set the animation speed assumed by the slider library. + * In addition to this, you must manually set the CSS (-webkit-)transition property for the .noUi-state-tap .noUi-origin selector. + */ + animationDuration?: number; + /** + * When a non-linear slider has been configured, the snap option can be set to true to force the slider to jump + * between the specified values. + */ + snap?: boolean; + /** + * All values on the slider are part of a range. The range has a minimum and maximum value. + */ + behaviour?: string; + /** + * To format the slider output, noUiSlider offers a format option. + * Simply specify to and from functions to encode and decode the values. + * See manual formatting to the right for usage information. + * By default, noUiSlider will format output with 2 decimals. + */ + format?: Object | ((...args:any[]) => any); + /** + * Allows you to generate points along the slider. + */ + pips?: PipsOptions; + } - interface PipsOptions { - /** - * The 'range' mode uses the slider range to determine where the pips should be. A pip is generated for every percentage specified. - * - * The 'steps', like 'range', uses the slider range. In steps mode, a pip is generated for every step. - * The 'filter' option can be used to filter the generated pips from the 'steps' options' - * The filter function must return 0 (no value), 1 (large value) or 2 (small value). - * - * In 'positions' mode, pips are generated at percentage-based positions on the slider. - * Optionally, the stepped option can be set to true to match the pips to the slider steps. - * - * The 'count' mode can be used to generate a fixed number of pips. As with positions mode, the stepped option can be used. - * - * The 'values' mode is similar to positions, but it accepts values instead of percentages. The stepped option can be used for this mode. - * - */ - mode: string; // "range" | "steps" | "positions" | "count" | "values" - /** - * Range Mode: percentage for range mode - * Step Mode: step number for steps - * Positions Mode: percentage-based positions on the slider - * Count Mode: positions between pips - */ - density?: number; - /** - * Step Mode: The filter option can be used to filter the generated pips. - * The filter function must return 0 (no value), 1 (large value) or 2 (small value). - */ - filter?: (...args: any[]) => PipFilterResult; - /** - * format for step mode - * see noUiSlider format - */ - format?: Object | ((...args:any[]) => any); - /** - * - * values for positions and values mode - * number pips for count mode - */ - values?: number | number[]; - /** - * stepped option for positions, values and count mode - */ - stepped?: boolean; - } + interface PipsOptions { + /** + * The 'range' mode uses the slider range to determine where the pips should be. A pip is generated for every percentage specified. + * + * The 'steps', like 'range', uses the slider range. In steps mode, a pip is generated for every step. + * The 'filter' option can be used to filter the generated pips from the 'steps' options' + * The filter function must return 0 (no value), 1 (large value) or 2 (small value). + * + * In 'positions' mode, pips are generated at percentage-based positions on the slider. + * Optionally, the stepped option can be set to true to match the pips to the slider steps. + * + * The 'count' mode can be used to generate a fixed number of pips. As with positions mode, the stepped option can be used. + * + * The 'values' mode is similar to positions, but it accepts values instead of percentages. The stepped option can be used for this mode. + * + */ + mode: string; // "range" | "steps" | "positions" | "count" | "values" + /** + * Range Mode: percentage for range mode + * Step Mode: step number for steps + * Positions Mode: percentage-based positions on the slider + * Count Mode: positions between pips + */ + density?: number; + /** + * Step Mode: The filter option can be used to filter the generated pips. + * The filter function must return 0 (no value), 1 (large value) or 2 (small value). + */ + filter?: (...args: any[]) => PipFilterResult; + /** + * format for step mode + * see noUiSlider format + */ + format?: Object | ((...args:any[]) => any); + /** + * + * values for positions and values mode + * number pips for count mode + */ + values?: number | number[]; + /** + * stepped option for positions, values and count mode + */ + stepped?: boolean; + } - const enum PipFilterResult { - NoValue, - LargeValue, - SmallValue, - } + const enum PipFilterResult { + NoValue, + LargeValue, + SmallValue, + } - interface Callback { - /** - * Array for both one-handle and two-handle sliders. It contains the current slider values, - * with formatting applied. - */ - (values: any[], handle: number, unencodedValues: number[]): void; - } + interface Callback { + /** + * Array for both one-handle and two-handle sliders. It contains the current slider values, + * with formatting applied. + */ + (values: any[], handle: number, unencodedValues: number[]): void; + } - interface noUiSlider { - /** - * Bind event to the slider. - */ - on(eventName: string, callback: Callback): void; - /** - * Unbind event to the slider. - */ - off(eventName: string): void; - /** - * Destroy's the slider. - */ - destroy(): void; + interface noUiSlider { + /** + * Bind event to the slider. + */ + on(eventName: string, callback: Callback): void; + /** + * Unbind event to the slider. + */ + off(eventName: string): void; + /** + * Destroy's the slider. + */ + destroy(): void; + /** + * To get the current slider value. For one-handle sliders, calling .get() will return the value. + * For two-handle sliders, an array[value, value] will be returned. + */ + get(): number | number[]; + /** + * noUiSlider will keep your values within the slider range, which saves you a bunch of validation. + * If you have configured the slider to use one handle, you can change the current value by passing + * a number to the .set() method. If you have two handles, pass an array. One-handled sliders + * will also accept arrays. Within an array, you can set one position to null + * if you want to leave a handle unchanged. + */ + set(value: number | number[]): void; + /** + * To return to the initial slider values, you can use the .reset() method. This will only reset the slider values. + */ + reset(): void; + } - /** - * To get the current slider value. For one-handle sliders, calling .get() will return the value. - * For two-handle sliders, an array[value, value] will be returned. - */ - get(): number | number[]; - /** - * noUiSlider will keep your values within the slider range, which saves you a bunch of validation. - * If you have configured the slider to use one handle, you can change the current value by passing - * a number to the .set() method. If you have two handles, pass an array. One-handled sliders - * will also accept arrays. Within an array, you can set one position to null - * if you want to leave a handle unchanged. - */ - set(value: number | number[]): void; - /* - * To return to the initial slider values, you can use the .reset() method. This will only reset the slider values. - */ - reset(): void; - } - - interface Instance extends HTMLElement { - noUiSlider: noUiSlider; + interface Instance extends HTMLElement { + noUiSlider: noUiSlider; + } } } From bcc73a6700e3a833cae32073e06c902e765658e9 Mon Sep 17 00:00:00 2001 From: Jonny Taylor Date: Sun, 18 Jun 2017 21:07:12 +0100 Subject: [PATCH 0031/1618] add mainloop.js export --- types/mainloop.js/index.d.ts | 4 ++++ types/mainloop.js/tsconfig.json | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/mainloop.js/index.d.ts b/types/mainloop.js/index.d.ts index f34d6f035a..e6263218c1 100644 --- a/types/mainloop.js/index.d.ts +++ b/types/mainloop.js/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Isaac Sukin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module 'mainloop.js' { + export default MainLoop; +} + /** * Interface for the MainLoop.js global. * diff --git a/types/mainloop.js/tsconfig.json b/types/mainloop.js/tsconfig.json index 86c619379e..5dae699f05 100644 --- a/types/mainloop.js/tsconfig.json +++ b/types/mainloop.js/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "mainloop.js-tests.ts" ] -} \ No newline at end of file +} From 3cfa831f26910a4e55a5028cb4139557e96f6c75 Mon Sep 17 00:00:00 2001 From: Morten Houston Ludvigsen Date: Mon, 19 Jun 2017 15:49:25 +0200 Subject: [PATCH 0032/1618] Make it possible to extend interfaces for subscribables and observables --- types/knockout/index.d.ts | 31 ++++++++++++++++++++----------- types/knockout/test/index.ts | 2 +- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 40464a3bd8..aed252c049 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -5,21 +5,28 @@ interface KnockoutSubscribableFunctions { - [key: string]: KnockoutBindingHandler | undefined; - notifySubscribers(valueToWrite?: T, event?: string): void; } +interface KnockoutSubscribableExtensionFunctions extends KnockoutSubscribableFunctions { + [key: string]: KnockoutBindingHandler | undefined; +} + interface KnockoutComputedFunctions { +} + +interface KnockoutComputedExtensionFunctions extends KnockoutComputedFunctions { [key: string]: KnockoutBindingHandler | undefined; } interface KnockoutObservableFunctions { - [key: string]: KnockoutBindingHandler | undefined; - equalityComparer(a: any, b: any): boolean; } +interface KnockoutObservableExtensionFunctions extends KnockoutObservableFunctions { + [key: string]: KnockoutBindingHandler | undefined; +} + interface KnockoutObservableArrayFunctions { // General Array functions indexOf(searchElement: T, fromIndex?: number): number; @@ -35,8 +42,6 @@ interface KnockoutObservableArrayFunctions { sort(compareFunction: (left: T, right: T) => number): KnockoutObservableArray; // Ko specific - [key: string]: KnockoutBindingHandler | undefined; - replace(oldItem: T, newItem: T): void; remove(item: T): T[]; @@ -50,8 +55,12 @@ interface KnockoutObservableArrayFunctions { destroyAll(): void; } +interface KnockoutObservableArrayExtensionFunctions extends KnockoutObservableArrayFunctions { + [key: string]: KnockoutBindingHandler | undefined; +} + interface KnockoutSubscribableStatic { - fn: KnockoutSubscribableFunctions; + fn: KnockoutSubscribableExtensionFunctions; new (): KnockoutSubscribable; } @@ -70,7 +79,7 @@ interface KnockoutSubscribable extends KnockoutSubscribableFunctions { } interface KnockoutComputedStatic { - fn: KnockoutComputedFunctions; + fn: KnockoutComputedExtensionFunctions; (): KnockoutComputed; (func: () => T, context?: any, options?: any): KnockoutComputed; @@ -78,7 +87,7 @@ interface KnockoutComputedStatic { } interface KnockoutComputed extends KnockoutObservable, KnockoutComputedFunctions { - fn: KnockoutComputedFunctions; + fn: KnockoutComputedExtensionFunctions; dispose(): void; isActive(): boolean; @@ -87,7 +96,7 @@ interface KnockoutComputed extends KnockoutObservable, KnockoutComputedFun } interface KnockoutObservableArrayStatic { - fn: KnockoutObservableArrayFunctions; + fn: KnockoutObservableArrayExtensionFunctions; (value?: T[] | null): KnockoutObservableArray; } @@ -102,7 +111,7 @@ interface KnockoutObservableArray extends KnockoutObservable, KnockoutOb } interface KnockoutObservableStatic { - fn: KnockoutObservableFunctions; + fn: KnockoutObservableExtensionFunctions; (value?: T | null): KnockoutObservable; } diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index ba96f6863f..ab31e0a6aa 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -1,4 +1,4 @@ - +/// /// declare var $; From 9e8aa6c0c1a730711894af5619f2c2a3fb0f0cb9 Mon Sep 17 00:00:00 2001 From: Morten Houston Ludvigsen Date: Mon, 19 Jun 2017 15:52:28 +0200 Subject: [PATCH 0033/1618] Tab to spaces --- types/knockout/index.d.ts | 118 +++++++++++++++++++------------------- 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index aed252c049..d95a10e3e2 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -5,7 +5,7 @@ interface KnockoutSubscribableFunctions { - notifySubscribers(valueToWrite?: T, event?: string): void; + notifySubscribers(valueToWrite?: T, event?: string): void; } interface KnockoutSubscribableExtensionFunctions extends KnockoutSubscribableFunctions { @@ -20,7 +20,7 @@ interface KnockoutComputedExtensionFunctions extends KnockoutComputedFunction } interface KnockoutObservableFunctions { - equalityComparer(a: any, b: any): boolean; + equalityComparer(a: any, b: any): boolean; } interface KnockoutObservableExtensionFunctions extends KnockoutObservableFunctions { @@ -66,16 +66,16 @@ interface KnockoutSubscribableStatic { } interface KnockoutSubscription { - dispose(): void; + dispose(): void; } interface KnockoutSubscribable extends KnockoutSubscribableFunctions { subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; - subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; - subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; + subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; - extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; - getSubscriptionsCount(): number; + extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; + getSubscriptionsCount(): number; } interface KnockoutComputedStatic { @@ -87,11 +87,11 @@ interface KnockoutComputedStatic { } interface KnockoutComputed extends KnockoutObservable, KnockoutComputedFunctions { - fn: KnockoutComputedExtensionFunctions; + fn: KnockoutComputedExtensionFunctions; - dispose(): void; - isActive(): boolean; - getDependenciesCount(): number; + dispose(): void; + isActive(): boolean; + getDependenciesCount(): number; extend(requestedExtenders: { [key: string]: any; }): KnockoutComputed; } @@ -117,23 +117,23 @@ interface KnockoutObservableStatic { } interface KnockoutObservable extends KnockoutSubscribable, KnockoutObservableFunctions { - (): T; - (value: T | null): void; + (): T; + (value: T | null): void; - peek(): T; - valueHasMutated?:{(): void;}; - valueWillMutate?:{(): void;}; + peek(): T; + valueHasMutated?:{(): void;}; + valueWillMutate?:{(): void;}; extend(requestedExtenders: { [key: string]: any; }): KnockoutObservable; } interface KnockoutComputedDefine { - read(): T; - write? (value: T): void; - disposeWhenNodeIsRemoved?: Node; - disposeWhen? (): boolean; - owner?: any; - deferEvaluation?: boolean; - pure?: boolean; + read(): T; + write? (value: T): void; + disposeWhenNodeIsRemoved?: Node; + disposeWhen? (): boolean; + owner?: any; + deferEvaluation?: boolean; + pure?: boolean; } interface KnockoutBindingContext { @@ -198,10 +198,10 @@ interface KnockoutBindingHandlers { uniqueName: KnockoutBindingHandler; // Rendering templates - template: KnockoutBindingHandler; + template: KnockoutBindingHandler; - // Components (new for v3.2) - component: KnockoutBindingHandler; + // Components (new for v3.2) + component: KnockoutBindingHandler; } interface KnockoutMemoization { @@ -226,12 +226,12 @@ interface KnockoutVirtualElements { interface KnockoutExtenders { throttle(target: any, timeout: number): KnockoutComputed; - notify(target: any, notifyWhen: string): any; + notify(target: any, notifyWhen: string): any; - rateLimit(target: any, timeout: number): any; - rateLimit(target: any, options: { timeout: number; method?: string; }): any; + rateLimit(target: any, timeout: number): any; + rateLimit(target: any, options: { timeout: number; method?: string; }): any; - trackArrayChanges(target: any): any; + trackArrayChanges(target: any): any; } // @@ -361,20 +361,20 @@ interface KnockoutTemplateSourcesDomElement { } interface KnockoutTemplateAnonymous extends KnockoutTemplateSourcesDomElement { - nodes(): any; - nodes(value: any): void; + nodes(): any; + nodes(value: any): void; } interface KnockoutTemplateSources { domElement: { - prototype: KnockoutTemplateSourcesDomElement - new (element: Element): KnockoutTemplateSourcesDomElement + prototype: KnockoutTemplateSourcesDomElement + new (element: Element): KnockoutTemplateSourcesDomElement }; anonymousTemplate: { - prototype: KnockoutTemplateAnonymous; - new (element: Element): KnockoutTemplateAnonymous; + prototype: KnockoutTemplateAnonymous; + new (element: Element): KnockoutTemplateAnonymous; }; } @@ -421,26 +421,26 @@ interface KnockoutStatic { utils: KnockoutUtils; memoization: KnockoutMemoization; - bindingHandlers: KnockoutBindingHandlers; - getBindingHandler(handler: string): KnockoutBindingHandler; + bindingHandlers: KnockoutBindingHandlers; + getBindingHandler(handler: string): KnockoutBindingHandler; virtualElements: KnockoutVirtualElements; extenders: KnockoutExtenders; applyBindings(viewModelOrBindingContext?: any, rootNode?: any): void; - applyBindingsToDescendants(viewModelOrBindingContext: any, rootNode: any): void; - applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, bindingContext: KnockoutBindingContext): void; - applyBindingAccessorsToNode(node: Node, bindings: {}, bindingContext: KnockoutBindingContext): void; - applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, viewModel: any): void; - applyBindingAccessorsToNode(node: Node, bindings: {}, viewModel: any): void; + applyBindingsToDescendants(viewModelOrBindingContext: any, rootNode: any): void; + applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, bindingContext: KnockoutBindingContext): void; + applyBindingAccessorsToNode(node: Node, bindings: {}, bindingContext: KnockoutBindingContext): void; + applyBindingAccessorsToNode(node: Node, bindings: (bindingContext: KnockoutBindingContext, node: Node) => {}, viewModel: any): void; + applyBindingAccessorsToNode(node: Node, bindings: {}, viewModel: any): void; applyBindingsToNode(node: Node, bindings: any, viewModelOrBindingContext?: any): any; subscribable: KnockoutSubscribableStatic; observable: KnockoutObservableStatic; - computed: KnockoutComputedStatic; - pureComputed(evaluatorFunction: () => T, context?: any): KnockoutComputed; - pureComputed(options: KnockoutComputedDefine, context?: any): KnockoutComputed; + computed: KnockoutComputedStatic; + pureComputed(evaluatorFunction: () => T, context?: any): KnockoutComputed; + pureComputed(options: KnockoutComputedDefine, context?: any): KnockoutComputed; observableArray: KnockoutObservableArrayStatic; @@ -456,9 +456,9 @@ interface KnockoutStatic { cleanNode(node: Element): Element; renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any; renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any; - unwrap(value: KnockoutObservable | T): T; + unwrap(value: KnockoutObservable | T): T; - computedContext: KnockoutComputedContext; + computedContext: KnockoutComputedContext; ////////////////////////////////// // templateSources.js @@ -566,10 +566,10 @@ interface KnockoutStatic { ///////////////////////////////// - bindingProvider: { - instance: KnockoutBindingProvider; - new (): KnockoutBindingProvider; - } + bindingProvider: { + instance: KnockoutBindingProvider; + new (): KnockoutBindingProvider; + } ///////////////////////////////// // selectExtensions.js @@ -608,15 +608,15 @@ interface KnockoutStatic { } interface KnockoutBindingProvider { - nodeHasBindings(node: Node): boolean; - getBindings(node: Node, bindingContext: KnockoutBindingContext): {}; - getBindingAccessors?(node: Node, bindingContext: KnockoutBindingContext): { [key: string]: string; }; + nodeHasBindings(node: Node): boolean; + getBindings(node: Node, bindingContext: KnockoutBindingContext): {}; + getBindingAccessors?(node: Node, bindingContext: KnockoutBindingContext): { [key: string]: string; }; } interface KnockoutComputedContext { - getDependenciesCount(): number; - isInitial: () => boolean; - isSleeping: boolean; + getDependenciesCount(): number; + isInitial: () => boolean; + isSleeping: boolean; } // @@ -697,5 +697,5 @@ interface KnockoutComponents { declare var ko: KnockoutStatic; declare module "knockout" { - export = ko; + export = ko; } From 43fb6d0f27e3b6a2a4c2541421166efe1494aa94 Mon Sep 17 00:00:00 2001 From: Morten Houston Ludvigsen Date: Tue, 20 Jun 2017 11:49:25 +0200 Subject: [PATCH 0034/1618] Fix error resulting from typings for knockout.deferred.updates --- types/knockout/index.d.ts | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index d95a10e3e2..063d1c4ec5 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -4,28 +4,23 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +interface KnockoutExtensionFunctions { + [key: string]: KnockoutBindingHandler | undefined; +} + interface KnockoutSubscribableFunctions { notifySubscribers(valueToWrite?: T, event?: string): void; } - -interface KnockoutSubscribableExtensionFunctions extends KnockoutSubscribableFunctions { - [key: string]: KnockoutBindingHandler | undefined; -} +type KnockoutSubscribableExtensionFunctions = KnockoutSubscribableFunctions & KnockoutExtensionFunctions; interface KnockoutComputedFunctions { } - -interface KnockoutComputedExtensionFunctions extends KnockoutComputedFunctions { - [key: string]: KnockoutBindingHandler | undefined; -} +type KnockoutComputedExtensionFunctions = KnockoutComputedFunctions & KnockoutExtensionFunctions; interface KnockoutObservableFunctions { equalityComparer(a: any, b: any): boolean; } - -interface KnockoutObservableExtensionFunctions extends KnockoutObservableFunctions { - [key: string]: KnockoutBindingHandler | undefined; -} +type KnockoutObservableExtensionFunctions = KnockoutObservableFunctions & KnockoutExtensionFunctions; interface KnockoutObservableArrayFunctions { // General Array functions @@ -54,10 +49,7 @@ interface KnockoutObservableArrayFunctions { destroyAll(items: T[]): void; destroyAll(): void; } - -interface KnockoutObservableArrayExtensionFunctions extends KnockoutObservableArrayFunctions { - [key: string]: KnockoutBindingHandler | undefined; -} +type KnockoutObservableArrayExtensionFunctions = KnockoutObservableArrayFunctions & KnockoutExtensionFunctions; interface KnockoutSubscribableStatic { fn: KnockoutSubscribableExtensionFunctions; From 520466194adc51122d3ef080042603ac07976366 Mon Sep 17 00:00:00 2001 From: Morten Houston Ludvigsen Date: Tue, 20 Jun 2017 12:02:16 +0200 Subject: [PATCH 0035/1618] Add test interfaces, that extend subscribables and observables --- types/knockout/test/index.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index ab31e0a6aa..e3f7820f94 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -723,4 +723,20 @@ function observableArrayEventsTests() { count--; }); }, null, "arrayChange"); +} + +interface MySubscribable extends KnockoutSubscribable { + isBeautiful?: boolean; +} + +interface MyObservable extends KnockoutObservable { + isBeautiful?: boolean; +} + +interface MyObservableArray extends KnockoutObservableArray { + isBeautiful?: boolean; +} + +interface MyComputed extends KnockoutComputed { + isBeautiful?: boolean; } \ No newline at end of file From 027ef3b94b970056bd3b34492b97aaf4738d0806 Mon Sep 17 00:00:00 2001 From: Andre Wiggins Date: Tue, 27 Jun 2017 00:20:27 -0700 Subject: [PATCH 0036/1618] Cleanup Angular readme and angular-resource Fixes #15274 --- .../angular-resource-tests.ts | 95 ++++++++--- types/angular-resource/index.d.ts | 38 ++--- types/angular-resource/tslint.json | 12 ++ types/angular/README.md | 151 ++---------------- 4 files changed, 116 insertions(+), 180 deletions(-) create mode 100644 types/angular-resource/tslint.json diff --git a/types/angular-resource/angular-resource-tests.ts b/types/angular-resource/angular-resource-tests.ts index d2e25a72b5..c5b71ee39f 100644 --- a/types/angular-resource/angular-resource-tests.ts +++ b/types/angular-resource/angular-resource-tests.ts @@ -1,15 +1,75 @@ +// Examples of working with resource, previously from the angular.d.ts. readme +// Working with $resource + +// 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(): IArticleResource; + get(params: IArticleParameters, onSuccess: Function): IArticleResource; + + // Add our custom resource actions + publish(params?: IArticleParameters): IArticleResource; + unpublish(params: IArticleParameters): IArticleResource; +} + +function MainController($resource: ng.resource.IResourceService): void { + // IntelliSense will provide IActionDescriptor interface and will validate + // your assignment against it + let publishDescriptor: ng.resource.IActionDescriptor = { + method: 'GET', + isArray: false + }; + + // 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 + let articleResource: IArticleResourceClass = $resource('/articles/:id', null, { + publish : publishDescriptor, + unpublish : { + method: 'POST' + } + }); + + // Now we can do this + articleResource.unpublish({ id: 1 }); + + // IResourceClass.get() will be automatically available here + let article: IArticleResource = articleResource.get({id: 1}, function success(): void { + // Again, default + custom action here... + article.title = 'New Title'; + article.$save(); + article.$publish(); + }); +} import IHttpPromiseCallbackArg = angular.IHttpPromiseCallbackArg; interface IMyData {} interface IMyHttpPromiseCallbackArg extends IHttpPromiseCallbackArg {} -interface IMyResource extends angular.resource.IResource { } -interface IMyResourceClass extends angular.resource.IResourceClass { } +interface IMyResource extends angular.resource.IResource {} +interface IMyResourceClass extends angular.resource.IResourceClass {} /////////////////////////////////////// // IActionDescriptor /////////////////////////////////////// -var actionDescriptor: angular.resource.IActionDescriptor; +let actionDescriptor: angular.resource.IActionDescriptor; angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactoryService) { actionDescriptor.method = 'method action'; @@ -27,19 +87,18 @@ angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactorySe actionDescriptor.withCredentials = true; actionDescriptor.responseType = 'response type'; actionDescriptor.interceptor = { - response: function () { return {}; }, - responseError: function () {} + response() { return {} as IMyHttpPromiseCallbackArg; }, + responseError() {} }; actionDescriptor.cancellable = true; }); - /////////////////////////////////////// // IResourceClass /////////////////////////////////////// -var resourceClass: IMyResourceClass; -var resource: IMyResource; -var resourceArray: angular.resource.IResourceArray; +let resourceClass: IMyResourceClass; +let resource: IMyResource; +let resourceArray: angular.resource.IResourceArray; resource = resourceClass.delete(); resource = resourceClass.delete({ key: 'value' }); @@ -94,9 +153,9 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { // IResource /////////////////////////////////////// -var promise : angular.IPromise; -var arrayPromise : angular.IPromise; -var json: IMyResource; +let promise: angular.IPromise; +let arrayPromise: angular.IPromise; +let json: IMyResource; promise = resource.$delete(); promise = resource.$delete({ key: 'value' }); @@ -140,7 +199,7 @@ json = resource.toJSON(); /////////////////////////////////////// // IResourceService /////////////////////////////////////// -var resourceService: angular.resource.IResourceService; +let resourceService: angular.resource.IResourceService; resourceClass = resourceService('test'); resourceClass = resourceService('test'); resourceClass = resourceService('test'); @@ -148,22 +207,20 @@ resourceClass = resourceService('test'); /////////////////////////////////////// // IModule /////////////////////////////////////// -var mod: ng.IModule; -var resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction; -var resourceService: angular.resource.IResourceService; +let mod: ng.IModule; +let resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction; resourceClass = resourceServiceFactoryFunction(resourceService); -resourceServiceFactoryFunction = function (resourceService: angular.resource.IResourceService) { return resourceClass; }; +resourceServiceFactoryFunction = function (resourceService: angular.resource.IResourceService) { return resourceClass as any; }; mod = mod.factory('factory name', resourceServiceFactoryFunction); /////////////////////////////////////// // IResource /////////////////////////////////////// - /////////////////////////////////////// // IResourceServiceProvider /////////////////////////////////////// -var resourceServiceProvider: angular.resource.IResourceServiceProvider; +let resourceServiceProvider: angular.resource.IResourceServiceProvider; resourceServiceProvider.defaults.stripTrailingSlashes = false; diff --git a/types/angular-resource/index.d.ts b/types/angular-resource/index.d.ts index 6b33790de5..9a036f336d 100644 --- a/types/angular-resource/index.d.ts +++ b/types/angular-resource/index.d.ts @@ -37,23 +37,21 @@ declare module 'angular' { // that deeply. /////////////////////////////////////////////////////////////////////////// interface IResourceService { - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: IActionHash, options?: IResourceOptions): IResourceClass>; - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: IActionHash, options?: IResourceOptions): U; - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: IActionHash, options?: IResourceOptions): IResourceClass; + /** + * A factory which creates a resource object that lets you interact with RESTful server-side data sources. + * @param url A parameterized URL template with parameters prefixed by : as in /user/:username + * @param paramDefaults Default values for url parameters. + * @param actions example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor: IActionDescriptor + * @param options Hash with custom settings that should extend the default $resourceProvider behavior + */ + (url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): IResourceClass>; + (url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): IResourceClass; + (url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): U; } // Hash of action descriptors allows custom action names interface IActionHash { - [action: string]: IActionDescriptor + [action: string]: IActionDescriptor; } // Just a reference to facilitate describing new actions @@ -71,7 +69,7 @@ declare module 'angular' { * would be used for multiple requests. If you are looking for a way to cancel requests, you should * use the cancellable option. */ - timeout?: number + timeout?: number; cancellable?: boolean; withCredentials?: boolean; responseType?: string; @@ -116,7 +114,7 @@ declare module 'angular' { // Also, static calls always return the IResource (or IResourceArray) retrieved // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549 interface IResourceClass { - new(dataOrParams? : any) : T & IResource; + new(dataOrParams?: any): T & IResource; get: IResourceMethod; query: IResourceArrayMethod; @@ -153,7 +151,7 @@ declare module 'angular' { $cancelRequest(): void; - /** the promise of the original server interaction that created this instance. **/ + /** The promise of the original server interaction that created this instance. */ $promise: angular.IPromise; $resolved: boolean; toJSON(): T; @@ -165,7 +163,7 @@ declare module 'angular' { interface IResourceArray extends Array> { $cancelRequest(): void; - /** the promise of the original server interaction that created this collection. **/ + /** The promise of the original server interaction that created this collection. */ $promise: angular.IPromise>; $resolved: boolean; } @@ -178,10 +176,8 @@ declare module 'angular' { // IResourceServiceProvider used to configure global settings interface IResourceServiceProvider extends angular.IServiceProvider { - defaults: IResourceOptions; } - } /** extensions to base ng based on using angular-resource */ @@ -199,8 +195,8 @@ declare module 'angular' { declare global { interface Array { - /** the promise of the original server interaction that created this collection. **/ - $promise: angular.IPromise>; + /** The promise of the original server interaction that created this collection. */ + $promise: angular.IPromise; $resolved: boolean; } } diff --git a/types/angular-resource/tslint.json b/types/angular-resource/tslint.json new file mode 100644 index 0000000000..7ebd5d5d2d --- /dev/null +++ b/types/angular-resource/tslint.json @@ -0,0 +1,12 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO: Fix up types to remove these + "interface-name": false, + "only-arrow-functions": false, + "no-empty-interface": false, + "ban-types": false, + "space-before-function-paren": false, + "unified-signatures": false + } +} diff --git a/types/angular/README.md b/types/angular/README.md index 1b3affc92c..871d9d37fa 100644 --- a/types/angular/README.md +++ b/types/angular/README.md @@ -2,27 +2,23 @@ ## 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. +Read the [TypeScript handbook](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html) for details on consuming these type definitions. 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. + + +Having these modules in separated packages 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-animate.d.ts (for the **ngAnimate** 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) +* angular-resource/index.d.ts (for the **ngResource** module) +* angular-route/index.d.ts (for the **ngRoute** module) +* angular-cookies/index.d.ts (for the **ngCookies** module) +* angular-sanitize/index.d.ts (for the **ngSanitize** module) +* angular-animate/index.d.ts (for the **ngAnimate** module) +* angular-mocks/index.d.ts (for the **ngMock** and **ngMockE2E** modules) ## The Angular Static @@ -31,7 +27,7 @@ The definitions declare the AngularJS static variable `angular` as ambient. That ## Definitions modularized -To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace: +To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace after you include their respective definitions: * `ng` for AngularJS' **ng** module * `ng.auto` for **AUTO** @@ -105,128 +101,3 @@ function Controller($scope: ICustomScope) { ## 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(); - -} -``` From 686775b8d68234997d45ea5b1b48d01af422f2b1 Mon Sep 17 00:00:00 2001 From: Zebulon McCorkle Date: Tue, 27 Jun 2017 19:07:05 -0400 Subject: [PATCH 0037/1618] Add extremely alpha typings for http-proxy-middleware --- .../http-proxy-middleware-tests.ts | 23 +++++++ types/http-proxy-middleware/index.d.ts | 67 +++++++++++++++++++ types/http-proxy-middleware/tsconfig.json | 22 ++++++ 3 files changed, 112 insertions(+) create mode 100644 types/http-proxy-middleware/http-proxy-middleware-tests.ts create mode 100644 types/http-proxy-middleware/index.d.ts create mode 100644 types/http-proxy-middleware/tsconfig.json diff --git a/types/http-proxy-middleware/http-proxy-middleware-tests.ts b/types/http-proxy-middleware/http-proxy-middleware-tests.ts new file mode 100644 index 0000000000..db331eec3d --- /dev/null +++ b/types/http-proxy-middleware/http-proxy-middleware-tests.ts @@ -0,0 +1,23 @@ +// Derived from https://github.com/chimurai/http-proxy-middleware#example + +import * as express from 'express'; +import * as proxy from 'http-proxy-middleware'; + +const options = { + target: 'http://www.example.org', + changeOrigin: true, + ws: true, + pathRewrite: { + '^/api/old-path': '/api/new-path', + '^/api/remove/path': '/path' + }, + router: { + 'dev.localhost:3000': 'http://localhost:8000' + } +}; + +const myProxy = proxy(options); + +const app = express(); +app.use('/api', myProxy); +app.listen(3000); diff --git a/types/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts new file mode 100644 index 0000000000..516ba72709 --- /dev/null +++ b/types/http-proxy-middleware/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for http-proxy-middleware +// Project: https://github.com/chimurai/http-proxy-middleware +// Definitions by: Zebulon McCorkle +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +import * as http from 'http'; +import * as net from 'net'; +import * as tls from 'tls'; +import * as connect from 'connect'; + +declare function proxy(config: proxy.Config): proxy.Proxy; +declare function proxy(contextOrUri: string, config: proxy.Config): proxy.Proxy; + +declare namespace proxy { + type Logger = (...objs: any[]) => void; + export interface LogProvider { + log: Logger, + debug?: Logger, + info?: Logger, + warn?: Logger, + error?: Logger, + } + + export interface Config { + pathRewrite?: { [regexp: string]: string } | ((path: string, req: http.IncomingMessage) => string), + router?: { [hostOrPath: string]: string } | ((req: http.IncomingMessage) => string), + logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent', + logProvider?: (provider: LogProvider) => LogProvider, + + onError?: connect.HandleFunction, + onProxyRes?: (proxyRes: http.ServerResponse, req: http.IncomingMessage, res: http.ServerResponse) => void, + onProxyReq?: (proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse) => void, + onProxyReqWs?: (proxyReq: http.ClientRequest, req: http.IncomingMessage, socket: any, options: any, head: any) => void, // TODO: Figure out the types of the last 3 + onOpen?: (proxySocket: net.Socket) => void, + onClose?: (res: http.ServerResponse, socket: net.Socket) => void, + + target?: string, + forward?: string, + agent?: http.Agent, + ssl?: tls.TlsOptions, + ws?: boolean, + xfwd?: boolean, + secure?: boolean, + toProxy?: boolean, + prependPath?: boolean, + ignorePath?: boolean, + localAddress?: string, + changeOrigin?: boolean, + auth?: string, + hostRewrite?: any, // TODO + autoRewrite?: any, // TODO + protocolRewrite?: any, // TODO + cookieDomainRewrite?: false | string | { [domain: string]: string }, + headers?: { [header: string]: string }, + proxyTimeout?: number, + } + + export interface Proxy extends connect.NextHandleFunction { + + } +} + +export = proxy; diff --git a/types/http-proxy-middleware/tsconfig.json b/types/http-proxy-middleware/tsconfig.json new file mode 100644 index 0000000000..1fa2b32d6d --- /dev/null +++ b/types/http-proxy-middleware/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "http-proxy-middleware-tests.ts" + ] +} From c2f0d06c2ad46a2ed74d35f62a1d3c778c1e36d5 Mon Sep 17 00:00:00 2001 From: laureysruben Date: Wed, 28 Jun 2017 10:51:57 +0200 Subject: [PATCH 0038/1618] Update to Jquery.foundation method typing As it is, the typing makes it impossible to use big parts of the api. I changed to using spread to define a parameter array of type any to support the entire api. Because the amount and type of parameters may change depending on the first string parameter (method), it is impossible to define the api more strict. --- types/foundation-sites/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/foundation-sites/index.d.ts b/types/foundation-sites/index.d.ts index 0bafdd6ae1..7209a9060f 100644 --- a/types/foundation-sites/index.d.ts +++ b/types/foundation-sites/index.d.ts @@ -447,7 +447,7 @@ declare namespace FoundationSites { } interface JQuery { - foundation(method?:string|Array) : JQuery; + foundation(method?: string, ...args: any[]): JQuery; } declare var Foundation:FoundationSites.FoundationSitesStatic; From 99a46764e213e822111f1ddc798f0ac8b60c4ea1 Mon Sep 17 00:00:00 2001 From: Francis Filion Date: Wed, 28 Jun 2017 06:41:13 -0400 Subject: [PATCH 0039/1618] [pouchdb-core] Added missing parameter on RemoveAttachmentResponse --- types/pouchdb-core/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/pouchdb-core/index.d.ts b/types/pouchdb-core/index.d.ts index 7352707324..5b8c8e4ddb 100644 --- a/types/pouchdb-core/index.d.ts +++ b/types/pouchdb-core/index.d.ts @@ -452,6 +452,7 @@ declare namespace PouchDB { } interface RemoveAttachmentResponse extends BasicResponse { + id: Core.DocumentId; rev: Core.RevisionId; } } From a79170dbe5297cef95ea2c5f1e8dfc99c959471b Mon Sep 17 00:00:00 2001 From: Sergei Dorogin Date: Wed, 28 Jun 2017 22:06:42 +0300 Subject: [PATCH 0040/1618] [bootstrap.v3.datetimepicker] fixed JQuery plugin declaration to more standard approach (see #12685); added `$.fn.datetimepicker.defaults` field typing --- types/bootstrap.v3.datetimepicker/index.d.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/types/bootstrap.v3.datetimepicker/index.d.ts b/types/bootstrap.v3.datetimepicker/index.d.ts index 0dee893fc5..e7ff041aa3 100644 --- a/types/bootstrap.v3.datetimepicker/index.d.ts +++ b/types/bootstrap.v3.datetimepicker/index.d.ts @@ -2,8 +2,8 @@ // Project: http://eonasdan.github.io/bootstrap-datetimepicker // Definitions by: Katona Péter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 // based on the previous version created by Jesica N. Fera +// TypeScript Version: 2.3 /** * bootstrap-datetimepicker.js 4.17.45 Copyright (c) 2015 Jonathan Peterson @@ -328,6 +328,18 @@ export interface Datetimepicker { * Usually you should not override those options unless you have a special need in your layout. */ widgetPositioning(value: WidgetPositioningOptions): void; + + /** + * JQuery plugin function. + * @param {DatetimepickerOptions} options + */ + (options?: DatetimepickerOptions): JQuery; + + /** + * Default options that will be used for all instances. + * To change: `$.fn.datetimepicker.defaults` + */ + defaults: DatetimepickerOptions; } export interface DatetimepickerOptions { @@ -581,7 +593,7 @@ export type EventName = "dp.show" | "dp.hide" | "dp.error"; declare global { interface JQuery { - datetimepicker(options?: DatetimepickerOptions): JQuery; + datetimepicker: Datetimepicker; data(key: "DateTimePicker"): Datetimepicker; From 1cc0cc672bd9cba21c9599ba5e07afa7b430805d Mon Sep 17 00:00:00 2001 From: Sergei Dorogin Date: Wed, 28 Jun 2017 22:29:33 +0300 Subject: [PATCH 0041/1618] [select2] JQuery plugin definition was extracted into interface to support `$.select2.amd` field --- types/select2/index.d.ts | 129 ++++++++++++++++++++------------------- 1 file changed, 67 insertions(+), 62 deletions(-) diff --git a/types/select2/index.d.ts b/types/select2/index.d.ts index 8830f270dc..740f329742 100644 --- a/types/select2/index.d.ts +++ b/types/select2/index.d.ts @@ -114,7 +114,74 @@ interface Select2SelectionObject { title: string; } +interface Select2Plugin { + amd: any; + + (): JQuery; + (it: IdTextPair): JQuery; + + /** + * Get the id value of the current selection + */ + (method: 'val'): any; + /** + * Set the id value of the current selection + * @params value Value to set the id to + * @params triggerChange Should a change event be triggered + */ + (method: 'val', value: any, triggerChange?: boolean): any; + /** + * Get the data object of the current selection + */ + (method: 'data'): any; + /** + * Set the data of the current selection + * @params value Object to set the data to + * @params triggerChange Should a change event be triggered + */ + (method: 'data', value: any, triggerChange?: boolean): any; + /** + * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. + */ + (method: 'destroy'): JQuery; + /** + * Opens the dropdown + */ + (method: 'open'): JQuery; + /** + * Closes the dropdown + */ + (method: 'close'): JQuery; + /** + * Enables or disables Select2 and its underlying form component + * @param value True if it should be enabled false if it should be disabled + */ + (method: 'enable', value: boolean): JQuery; + /** + * Toggles readonly mode on Select2 and its underlying form component + * @param value True if it should be readonly false if it should be read write + */ + (method: 'readonly', value: boolean): JQuery; + /** + * Retrieves the main container element that wraps all of DOM added by Select2 + */ + (method: 'container'): JQuery; + /** + * Notifies Select2 that a drag and drop sorting operation has started + */ + (method: 'onSortStart'): JQuery; + /** + * Notifies Select2 that a drag and drop sorting operation has finished + */ + (method: 'onSortEnd'): JQuery; + + (method: string): any; + (method: string, value: any, trigger?: boolean): any; + (options: Select2Options): JQuery; +} + interface JQuery { + select2: Select2Plugin; off(events?: "change", selector?: any, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery; on(events: "change", selector?: string, data?: any, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery; @@ -140,68 +207,6 @@ interface JQuery { on(events: "select2-loaded", handler?: (eventObject: Select2JQueryEventObject) => any): JQuery; on(events: "select2-focus", handler?: (eventObject: Select2JQueryEventObject) => any): JQuery; on(events: "select2-blur", handler?: (eventObject: Select2JQueryEventObject) => any): JQuery; - - select2(): JQuery; - select2(it: IdTextPair): JQuery; - - /** - * Get the id value of the current selection - */ - select2(method: 'val'): any; - /** - * Set the id value of the current selection - * @params value Value to set the id to - * @params triggerChange Should a change event be triggered - */ - select2(method: 'val', value: any, triggerChange?: boolean): any; - /** - * Get the data object of the current selection - */ - select2(method: 'data'): any; - /** - * Set the data of the current selection - * @params value Object to set the data to - * @params triggerChange Should a change event be triggered - */ - select2(method: 'data', value: any, triggerChange?: boolean): any; - /** - * Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved. - */ - select2(method: 'destroy'): JQuery; - /** - * Opens the dropdown - */ - select2(method: 'open'): JQuery; - /** - * Closes the dropdown - */ - select2(method: 'close'): JQuery; - /** - * Enables or disables Select2 and its underlying form component - * @param value True if it should be enabled false if it should be disabled - */ - select2(method: 'enable', value: boolean): JQuery; - /** - * Toggles readonly mode on Select2 and its underlying form component - * @param value True if it should be readonly false if it should be read write - */ - select2(method: 'readonly', value: boolean): JQuery; - /** - * Retrieves the main container element that wraps all of DOM added by Select2 - */ - select2(method: 'container'): JQuery; - /** - * Notifies Select2 that a drag and drop sorting operation has started - */ - select2(method: 'onSortStart'): JQuery; - /** - * Notifies Select2 that a drag and drop sorting operation has finished - */ - select2(method: 'onSortEnd'): JQuery; - - select2(method: string): any; - select2(method: string, value: any, trigger?: boolean): any; - select2(options: Select2Options): JQuery; } declare class Select2 { From d80cb8f1f5f0d72aaed55745a0715c4748f38e8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADtor=20Castro?= Date: Thu, 29 Jun 2017 00:24:13 +0100 Subject: [PATCH 0042/1618] Improve ramda pick types --- types/ramda/index.d.ts | 138 ++++++++++++++++++++----------------- types/ramda/ramda-tests.ts | 2 +- 2 files changed, 75 insertions(+), 65 deletions(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index ba6908d57c..49321a4497 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -6,6 +6,7 @@ // Matt Dziuban // Stephen King // Alejandro Fernandez Haro +// Vítor Castro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -344,18 +345,20 @@ declare namespace R { compose(fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T5; compose(fn5: (x: T5) => T6, fn4: (x: T4) => T5, fn3: (x: T3) => T4, fn2: (x: T2) => T3, fn1: (x: T1) => T2, fn0: (x: V0) => T1): (x: V0) => T6; - compose(fn5: (x: T5) => T6, - fn4: (x: T4) => T5, - fn3: (x: T3) => T4, - fn2: (x: T2) => T3, - fn1: (x: T1) => T2, - fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T6; - compose(fn5: (x: T5) => T6, - fn4: (x: T4) => T5, - fn3: (x: T3) => T4, - fn2: (x: T2) => T3, - fn1: (x: T1) => T2, - fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T6; + compose( + fn5: (x: T5) => T6, + fn4: (x: T4) => T5, + fn3: (x: T3) => T4, + fn2: (x: T2) => T3, + fn1: (x: T1) => T2, + fn0: (x0: V0, x1: V1) => T1): (x0: V0, x1: V1) => T6; + compose( + fn5: (x: T5) => T6, + fn4: (x: T4) => T5, + fn3: (x: T3) => T4, + fn2: (x: T2) => T3, + fn1: (x: T1) => T2, + fn0: (x0: V0, x1: V1, x2: V2) => T1): (x0: V0, x1: V1, x2: V2) => T6; /** * TODO composeK @@ -1181,7 +1184,7 @@ declare namespace R { * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the * property is ignored. */ - pick(names: string[], obj: T): U; + pick(names: Array, obj: T): Pick; pick(names: string[]): (obj: T) => U; /** @@ -1223,59 +1226,66 @@ declare namespace R { pipe(fn0: (x: V0) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x: V0) => T6; pipe(fn0: (x0: V0, x1: V1) => T1, fn1: (x: T1) => T2, fn2: (x: T2) => T3, fn3: (x: T3) => T4, fn4: (x: T4) => T5, fn5: (x: T5) => T6): (x0: V0, x1: V1) => T6; - pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, - fn1: (x: T1) => T2, - fn2: (x: T2) => T3, - fn3: (x: T3) => T4, - fn4: (x: T4) => T5, - fn5: (x: T5) => T6): (x0: V0, x1: V1, x2: V2) => T6; + pipe( + fn0: (x0: V0, x1: V1, x2: V2) => T1, + fn1: (x: T1) => T2, + fn2: (x: T2) => T3, + fn3: (x: T3) => T4, + fn4: (x: T4) => T5, + fn5: (x: T5) => T6): (x0: V0, x1: V1, x2: V2) => T6; - pipe(fn0: (x: V0) => T1, - fn1: (x: T1) => T2, - fn2: (x: T2) => T3, - fn3: (x: T3) => T4, - fn4: (x: T4) => T5, - fn5: (x: T5) => T6, - fn: (x: T6) => T7): (x: V0) => T7; - pipe(fn0: (x0: V0, x1: V1) => T1, - fn1: (x: T1) => T2, - fn2: (x: T2) => T3, - fn3: (x: T3) => T4, - fn4: (x: T4) => T5, - fn5: (x: T5) => T6, - fn6: (x: T6) => T7): (x0: V0, x1: V1) => T7; - pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, - fn1: (x: T1) => T2, - fn2: (x: T2) => T3, - fn3: (x: T3) => T4, - fn4: (x: T4) => T5, - fn5: (x: T5) => T6, - fn6: (x: T6) => T7): (x0: V0, x1: V1, x2: V2) => T7; + pipe( + fn0: (x: V0) => T1, + fn1: (x: T1) => T2, + fn2: (x: T2) => T3, + fn3: (x: T3) => T4, + fn4: (x: T4) => T5, + fn5: (x: T5) => T6, + fn: (x: T6) => T7): (x: V0) => T7; + pipe( + fn0: (x0: V0, x1: V1) => T1, + fn1: (x: T1) => T2, + fn2: (x: T2) => T3, + fn3: (x: T3) => T4, + fn4: (x: T4) => T5, + fn5: (x: T5) => T6, + fn6: (x: T6) => T7): (x0: V0, x1: V1) => T7; + pipe( + fn0: (x0: V0, x1: V1, x2: V2) => T1, + fn1: (x: T1) => T2, + fn2: (x: T2) => T3, + fn3: (x: T3) => T4, + fn4: (x: T4) => T5, + fn5: (x: T5) => T6, + fn6: (x: T6) => T7): (x0: V0, x1: V1, x2: V2) => T7; - pipe(fn0: (x: V0) => T1, - fn1: (x: T1) => T2, - fn2: (x: T2) => T3, - fn3: (x: T3) => T4, - fn4: (x: T4) => T5, - fn5: (x: T5) => T6, - fn6: (x: T6) => T7, - fn: (x: T7) => T8): (x: V0) => T8; - pipe(fn0: (x0: V0, x1: V1) => T1, - fn1: (x: T1) => T2, - fn2: (x: T2) => T3, - fn3: (x: T3) => T4, - fn4: (x: T4) => T5, - fn5: (x: T5) => T6, - fn6: (x: T5) => T6, - fn7: (x: T7) => T8): (x0: V0, x1: V1) => T8; - pipe(fn0: (x0: V0, x1: V1, x2: V2) => T1, - fn1: (x: T1) => T2, - fn2: (x: T2) => T3, - fn3: (x: T3) => T4, - fn4: (x: T4) => T5, - fn5: (x: T5) => T6, - fn6: (x: T5) => T6, - fn7: (x: T7) => T8): (x0: V0, x1: V1, x2: V2) => T8; + pipe( + fn0: (x: V0) => T1, + fn1: (x: T1) => T2, + fn2: (x: T2) => T3, + fn3: (x: T3) => T4, + fn4: (x: T4) => T5, + fn5: (x: T5) => T6, + fn6: (x: T6) => T7, + fn: (x: T7) => T8): (x: V0) => T8; + pipe( + fn0: (x0: V0, x1: V1) => T1, + fn1: (x: T1) => T2, + fn2: (x: T2) => T3, + fn3: (x: T3) => T4, + fn4: (x: T4) => T5, + fn5: (x: T5) => T6, + fn6: (x: T5) => T6, + fn7: (x: T7) => T8): (x0: V0, x1: V1) => T8; + pipe( + fn0: (x0: V0, x1: V1, x2: V2) => T1, + fn1: (x: T1) => T2, + fn2: (x: T2) => T3, + fn3: (x: T3) => T4, + fn4: (x: T4) => T5, + fn5: (x: T5) => T6, + fn6: (x: T5) => T6, + fn7: (x: T7) => T8): (x0: V0, x1: V1, x2: V2) => T8; /** * Returns a new list by plucking the same named property off all objects in the list supplied. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 70298f53e6..e78364a8ec 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1414,7 +1414,7 @@ class Rectangle { () => { const a1 = R.pick(["a", "d"], {a: 1, b: 2, c: 3, d: 4}); // => {a: 1, d: 4} - const a2 = R.pick(["a", "e", "f"], {a: 1, b: 2, c: 3, d: 4}); // => {a: 1} + const a2 = R.pick(["a", "e", "f"], {a: 1, b: 2, c: 3, d: 4}); // => {a: 1} const a3 = R.pick(["a", "e", "f"])({a: 1, b: 2, c: 3, d: 4}); // => {a: 1} const a4 = R.pick(["a", "e", "f"], [1, 2, 3, 4]); // => {a: 1} }; From e5860485cce39be27a321377a6f3b04b1d89d284 Mon Sep 17 00:00:00 2001 From: pueue Date: Thu, 29 Jun 2017 16:52:13 +0900 Subject: [PATCH 0043/1618] Add EmptyResultError --- types/sequelize/index.d.ts | 15 +++++++++++++++ types/sequelize/sequelize-tests.ts | 2 ++ 2 files changed, 17 insertions(+) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 86ecb00809..97047aada6 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -2185,6 +2185,15 @@ declare namespace sequelize { } + interface EmptyResultError extends BaseError { + + /** + * Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details) + */ + new (parent: Error): EmptyResultError; + + } + /** * Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors * are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the @@ -2206,6 +2215,7 @@ declare namespace sequelize { HostNotReachableError: HostNotReachableError; InvalidConnectionError: InvalidConnectionError; ConnectionTimedOutError: ConnectionTimedOutError; + EmptyResultError: EmptyResultError; } // @@ -3263,6 +3273,11 @@ declare namespace sequelize { * Prevents a subquery on the main table when using include */ subQuery?: boolean; + + /** + * Throw EmptyResultError if a record is not found + */ + rejectOnEmpty?: boolean; } /** diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index d786dfc4a2..02249377a9 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -629,6 +629,7 @@ new s.HostNotFoundError( new Error( 'original connection error message' ) ); new s.HostNotReachableError( new Error( 'original connection error message' ) ); new s.InvalidConnectionError( new Error( 'original connection error message' ) ); new s.ConnectionTimedOutError( new Error( 'original connection error message' ) ); +new s.EmptyResultError(); const uniqueConstraintError: Sequelize.ValidationError = new s.UniqueConstraintError({}); @@ -914,6 +915,7 @@ User.findAll( { attributes: [s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER' User.findAll( { attributes: [[s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER'), 'count']] }); User.findAll( { where : s.fn('count', [0, 10]) } ); User.findAll( { subQuery: false, include : [User], order : [[User, User, 'numYears', 'c']] } ); +User.findAll( { rejectOnEmpty: true }); User.findById( 'a string' ); From 20dae297ab3cb68b170f29584a152d7a633f71b0 Mon Sep 17 00:00:00 2001 From: mbilsing Date: Thu, 29 Jun 2017 11:17:30 +0200 Subject: [PATCH 0044/1618] Changes typings of CodeMirror's show-hint module to use the Editor object in most parameters instead of the Doc object. . --- types/codemirror/codemirror-showhint.d.ts | 13 +++++-------- types/codemirror/test/showhint.ts | 12 ++++++------ 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/types/codemirror/codemirror-showhint.d.ts b/types/codemirror/codemirror-showhint.d.ts index 55a3d6012b..745e481737 100644 --- a/types/codemirror/codemirror-showhint.d.ts +++ b/types/codemirror/codemirror-showhint.d.ts @@ -1,6 +1,6 @@ // Type definitions for CodeMirror // Project: https://github.com/marijnh/CodeMirror -// Definitions by: jacqt , basarat +// Definitions by: jacqt , basarat , mbilsing // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // See docs https://codemirror.net/doc/manual.html#addon_show-hint @@ -16,7 +16,7 @@ declare module "codemirror" { and return a {list, from, to} object, where list is an array of strings or objects (the completions), and from and to give the start and end of the token that is being completed as {line, ch} objects. An optional selectedHint property (an integer) can be added to the completion object to control the initially selected hint. */ - function showHint(cm: CodeMirror.Doc, hinter?: HintFunction, options?: ShowHintOptions): void; + function showHint(cm: CodeMirror.Editor, hinter?: HintFunction, options?: ShowHintOptions): void; interface Hints { from: Position; @@ -32,7 +32,7 @@ declare module "codemirror" { displayText?: string; from?: Position; /** Called if a completion is picked. If provided *you* are responsible for applying the completion */ - hint?: (cm: any, data: Hints, cur: Hint) => void; + hint?: (cm: CodeMirror.Editor, data: Hints, cur: Hint) => void; render?: (element: HTMLLIElement, data: Hints, cur: Hint) => void; to?: Position; } @@ -41,18 +41,15 @@ declare module "codemirror" { /** An extension of the existing CodeMirror typings for the Editor.on("keyup", func) syntax */ on(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void; off(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void; - } - - interface Doc { showHint: (options: ShowHintOptions) => void; } interface HintFunction { - (doc: CodeMirror.Doc): Hints; + (cm: CodeMirror.Editor): Hints; } interface AsyncHintFunction { - (doc: CodeMirror.Doc, callback: (hints: Hints) => any): any; + (cm: CodeMirror.Editor, callback: (hints: Hints) => any): any; async?: boolean; } diff --git a/types/codemirror/test/showhint.ts b/types/codemirror/test/showhint.ts index 00dbe6bed4..0aabcc9a86 100644 --- a/types/codemirror/test/showhint.ts +++ b/types/codemirror/test/showhint.ts @@ -1,16 +1,16 @@ -var doc = new CodeMirror.Doc('text'); +var cm = CodeMirror(document.body, {value: 'text'}); var pos = new CodeMirror.Pos(2, 3); -CodeMirror.showHint(doc); -CodeMirror.showHint(doc, function (cm) { +CodeMirror.showHint(cm); +CodeMirror.showHint(cm, function (cm) { return { from: pos, list: ["one", "two"], to: pos }; }); -CodeMirror.showHint(doc, function (cm) { +CodeMirror.showHint(cm, function (cm) { return { from: pos, list: [ @@ -32,7 +32,7 @@ CodeMirror.showHint(doc, function (cm) { }; }); var asyncHintFunc : CodeMirror.AsyncHintFunction = - (doc: CodeMirror.Doc, callback: (hints: CodeMirror.Hints) => any) => { + (cm: CodeMirror.Editor, callback: (hints: CodeMirror.Hints) => any) => { callback({ from: pos, list: ["one", "two"], @@ -41,7 +41,7 @@ var asyncHintFunc : CodeMirror.AsyncHintFunction = }; asyncHintFunc.async = true; -doc.showHint({ +cm.showHint({ completeSingle: false, hint: asyncHintFunc }) From 51e7287c86e23281e6f45efa68becd574032cea2 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Thu, 29 Jun 2017 13:31:52 +0200 Subject: [PATCH 0045/1618] React.SFC<...> | React.ComponentClass<...> => React.ComponentType<...> --- types/react-router-config/index.d.ts | 2 +- types/react-router/index.d.ts | 4 ++-- types/rrc/index.d.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react-router-config/index.d.ts b/types/react-router-config/index.d.ts index 8497b0d4b8..7644b8f062 100644 --- a/types/react-router-config/index.d.ts +++ b/types/react-router-config/index.d.ts @@ -14,7 +14,7 @@ export interface RouteConfigComponentProps extends RouteComponentProps { export interface RouteConfig { location?: Location; - component?: React.SFC | void> | React.ComponentClass | void>; + component?: React.ComponentType | void>; path?: string; exact?: boolean; strict?: boolean; diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 72afa50e3b..2f38251db8 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -64,7 +64,7 @@ export interface RouteComponentProps

{ export interface RouteProps { location?: H.Location; - component?: React.SFC | undefined> | React.ComponentClass | undefined>; + component?: React.ComponentType | undefined>; render?: ((props: RouteComponentProps) => React.ReactNode); children?: ((props: RouteComponentProps) => React.ReactNode) | React.ReactNode; path?: string; @@ -99,4 +99,4 @@ export interface match

{ } export function matchPath

(pathname: string, props: RouteProps): match

| null; -export function withRouter

(component: React.SFC & P> | React.ComponentClass & P>): React.ComponentClass

; +export function withRouter

(component: React.ComponentType & P>): React.ComponentClass

; diff --git a/types/rrc/index.d.ts b/types/rrc/index.d.ts index 6a56baf3fc..891ceeaa64 100644 --- a/types/rrc/index.d.ts +++ b/types/rrc/index.d.ts @@ -22,7 +22,7 @@ export interface WithScrollOptions { alignToTop?: boolean; } -export type ComponentConstructor = React.ComponentClass | React.SFC; +export type ComponentConstructor = React.ComponentType; export function withScroll(component: ComponentConstructor | undefined>, options?: WithScrollOptions) : ComponentConstructor | undefined>; From 552051f56f4e46da801297a8631447f97aaade0c Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Thu, 29 Jun 2017 13:54:42 +0200 Subject: [PATCH 0046/1618] Default props should be {}, not undefined or void --- types/react-router-config/index.d.ts | 2 +- types/react-router/index.d.ts | 2 +- .../PreventingTransitions.tsx | 2 +- types/rrc/index.d.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/types/react-router-config/index.d.ts b/types/react-router-config/index.d.ts index 7644b8f062..2040a8a721 100644 --- a/types/react-router-config/index.d.ts +++ b/types/react-router-config/index.d.ts @@ -14,7 +14,7 @@ export interface RouteConfigComponentProps extends RouteComponentProps { export interface RouteConfig { location?: Location; - component?: React.ComponentType | void>; + component?: React.ComponentType | {}>; path?: string; exact?: boolean; strict?: boolean; diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 2f38251db8..cfd0b20c66 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -64,7 +64,7 @@ export interface RouteComponentProps

{ export interface RouteProps { location?: H.Location; - component?: React.ComponentType | undefined>; + component?: React.ComponentType | {}>; render?: ((props: RouteComponentProps) => React.ReactNode); children?: ((props: RouteComponentProps) => React.ReactNode) | React.ReactNode; path?: string; diff --git a/types/react-router/test/examples-from-react-router-website/PreventingTransitions.tsx b/types/react-router/test/examples-from-react-router-website/PreventingTransitions.tsx index bd5d76ae2b..9f1858c89f 100644 --- a/types/react-router/test/examples-from-react-router-website/PreventingTransitions.tsx +++ b/types/react-router/test/examples-from-react-router-website/PreventingTransitions.tsx @@ -22,7 +22,7 @@ const PreventingTransitionsExample = () => ( ); -class Form extends React.Component { +class Form extends React.Component<{}, {isBlocking: boolean}> { state = { isBlocking: false }; diff --git a/types/rrc/index.d.ts b/types/rrc/index.d.ts index 891ceeaa64..f4ef84e568 100644 --- a/types/rrc/index.d.ts +++ b/types/rrc/index.d.ts @@ -24,8 +24,8 @@ export interface WithScrollOptions { export type ComponentConstructor = React.ComponentType; -export function withScroll(component: ComponentConstructor | undefined>, options?: WithScrollOptions) - : ComponentConstructor | undefined>; +export function withScroll(component: ComponentConstructor | {}>, options?: WithScrollOptions) + : ComponentConstructor | {}>; export type RouteConfiguration = RouteProps & { inject?: { [key: string]: any } }; From 5addbe9b7270c558b5ef26d4bfd84b3df08e4427 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Thu, 29 Jun 2017 13:55:50 +0200 Subject: [PATCH 0047/1618] React.ComponentType

=> React.ComponentType

--- types/react/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 577959ae7b..de21376a94 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -35,7 +35,7 @@ declare namespace React { // ---------------------------------------------------------------------- type ReactType = string | ComponentType; - type ComponentType

= ComponentClass

| StatelessComponent

; + type ComponentType

= ComponentClass

| StatelessComponent

; type Key = string | number; type Ref = string | ((instance: T | null) => any); From caa25e1acbbab9db1c053d76d930dc623b5dec07 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 08:10:51 -0400 Subject: [PATCH 0048/1618] [tough-cookie] Revert weak-type workaround. --- types/tough-cookie/index.d.ts | 104 ++++++++++++++-------------------- 1 file changed, 42 insertions(+), 62 deletions(-) diff --git a/types/tough-cookie/index.d.ts b/types/tough-cookie/index.d.ts index 9871e2579f..7aeb7b111f 100644 --- a/types/tough-cookie/index.d.ts +++ b/types/tough-cookie/index.d.ts @@ -65,11 +65,11 @@ export function permutePath(path: string): string[]; // region Cookie export class Cookie { - static parse(cookieString: string, options?: Cookie.ParseOptions | object): Cookie | undefined; + static parse(cookieString: string, options?: Cookie.ParseOptions): Cookie | undefined; static fromJSON(strOrObj: string | object): Cookie | null; - constructor(properties?: Cookie.Properties | object); + constructor(properties?: Cookie.Properties); // TODO: Some of the following properties might actually be nullable. @@ -115,34 +115,26 @@ export class Cookie { } export namespace Cookie { - interface ParseOptions extends Pick { } - - namespace ParseOptions { - interface _Impl { - loose: boolean; - } + interface ParseOptions { + loose?: boolean; } - interface Properties extends Pick { } + interface Properties { + key?: string; + value?: string; + expires?: Date; + maxAge?: number | 'Infinity' | '-Infinity'; + domain?: string; + path?: string; + secure?: boolean; + httpOnly?: boolean; + extensions?: string[]; + creation?: Date; + creationIndex?: number; - namespace Properties { - interface _Impl { - key: string; - value: string; - expires: Date; - maxAge: number | 'Infinity' | '-Infinity'; - domain: string; - path: string; - secure: boolean; - httpOnly: boolean; - extensions: string[]; - creation: Date; - creationIndex: number; - - hostOnly: boolean; - pathIsDefault: boolean; - lastAccessed: Date; - } + hostOnly?: boolean; + pathIsDefault?: boolean; + lastAccessed?: Date; } interface Serialized { @@ -162,27 +154,27 @@ export class CookieJar { static fromJSON(string: string): CookieJar; - constructor(store?: Store, options?: CookieJar.Options | object); + constructor(store?: Store, options?: CookieJar.Options); - setCookie(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions | object, cb: (err: Error | null, cookie: Cookie) => void): void; + setCookie(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions, cb: (err: Error | null, cookie: Cookie) => void): void; setCookie(cookieOrString: Cookie | string, currentUrl: string, cb: (err: Error, cookie: Cookie) => void): void; - setCookieSync(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions | object): void; + setCookieSync(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions): void; - getCookies(currentUrl: string, options: CookieJar.GetCookiesOptions | object, cb: (err: Error | null, cookies: Cookie[]) => void): void; + getCookies(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: Cookie[]) => void): void; getCookies(currentUrl: string, cb: (err: Error | null, cookies: Cookie[]) => void): void; - getCookiesSync(currentUrl: string, options?: CookieJar.GetCookiesOptions | object): Cookie[]; + getCookiesSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): Cookie[]; - getCookieString(currentUrl: string, options: CookieJar.GetCookiesOptions | object, cb: (err: Error | null, cookies: string) => void): void; + getCookieString(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: string) => void): void; getCookieString(currentUrl: string, cb: (err: Error | null, cookies: string) => void): void; - getCookieStringSync(currentUrl: string, options?: CookieJar.GetCookiesOptions | object): string; + getCookieStringSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): string; - getSetCookieStrings(currentUrl: string, options: CookieJar.GetCookiesOptions | object, cb: (err: Error | null, cookies: string) => void): void; + getSetCookieStrings(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: string) => void): void; getSetCookieStrings(currentUrl: string, cb: (err: Error | null, cookies: string) => void): void; - getSetCookieStringsSync(currentUrl: string, options?: CookieJar.GetCookiesOptions | object): string; + getSetCookieStringsSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): string; serialize(cb: (err: Error | null, serializedObject: CookieJar.Serialized) => void): void; @@ -197,36 +189,24 @@ export class CookieJar { } export namespace CookieJar { - interface Options extends Pick { } - - namespace Options { - interface _Impl { - rejectPublicSuffixes: boolean; - looseMode: boolean; - } + interface Options { + rejectPublicSuffixes?: boolean; + looseMode?: boolean; } - interface SetCookieOptions extends Pick { } - - namespace SetCookieOptions { - interface _Impl { - http: boolean; - secure: boolean; - now: Date; - ignoreError: boolean; - } + interface SetCookieOptions { + http?: boolean; + secure?: boolean; + now?: Date; + ignoreError?: boolean; } - interface GetCookiesOptions extends Pick { } - - namespace GetCookiesOptions { - interface _Impl { - http: boolean; - secure: boolean; - date: Date; - expire: boolean; - allPoints: boolean; - } + interface GetCookiesOptions { + http?: boolean; + secure?: boolean; + date?: Date; + expire?: boolean; + allPoints?: boolean; } interface Serialized { From ef01aca5cb15fce5ff1cc204d44a2b61af403f6c Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 08:15:14 -0400 Subject: [PATCH 0049/1618] [electron-settings] Revert weak-type workaround. --- types/electron-settings/v2/index.d.ts | 75 ++++++++++-------------- types/electron-settings/v2/tsconfig.json | 1 + 2 files changed, 32 insertions(+), 44 deletions(-) diff --git a/types/electron-settings/v2/index.d.ts b/types/electron-settings/v2/index.d.ts index 71677cb0df..a869fd52b8 100644 --- a/types/electron-settings/v2/index.d.ts +++ b/types/electron-settings/v2/index.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/nathanbuchar/electron-settings // Definitions by: Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 /// @@ -20,7 +19,7 @@ declare class Settings extends EventEmitter { * * @throws if options is not an object. */ - configure(options: ElectronSettings.Options.Param): void; + configure(options: ElectronSettings.Options): void; /** * Globally configures default settings. @@ -79,14 +78,14 @@ declare class Settings extends EventEmitter { * @throws if options is not an object. * @see setSync */ - set(keyPath: string, value: any, options?: ElectronSettings.Options.Param): Promise; + set(keyPath: string, value: any, options?: ElectronSettings.Options): Promise; /** * The synchronous version of set(). * * @see set */ - setSync(keyPath: string, value: any, options?: ElectronSettings.Options.Param): void; + setSync(keyPath: string, value: any, options?: ElectronSettings.Options): void; /** * Deletes the key and value at the chosen key path. @@ -97,14 +96,14 @@ declare class Settings extends EventEmitter { * @throws if options is not an object. * @see deleteSync */ - delete(keyPath: string, options?: ElectronSettings.Options.Param): Promise; + delete(keyPath: string, options?: ElectronSettings.Options): Promise; /** * The synchronous version of delete(). * * @see delete */ - deleteSync(keyPath: string, options?: ElectronSettings.Options.Param): void; + deleteSync(keyPath: string, options?: ElectronSettings.Options): void; /** * Clears the entire settings object. @@ -113,14 +112,14 @@ declare class Settings extends EventEmitter { * @throws if options is not an object. * @see clearSync */ - clear(options?: ElectronSettings.Options.Param): Promise; + clear(options?: ElectronSettings.Options): Promise; /** * The synchronous version of clear(). * * @see clear */ - clearSync(options?: ElectronSettings.Options.Param): void; + clearSync(options?: ElectronSettings.Options): void; /** * Applies defaults to the current settings object (deep). @@ -133,14 +132,14 @@ declare class Settings extends EventEmitter { * @see defaults * @see applyDefaultsSync */ - applyDefaults(options?: ElectronSettings.ApplyDefaultsOptions.Param): Promise; + applyDefaults(options?: ElectronSettings.ApplyDefaultsOptions): Promise; /** * The synchronous version of applyDefaults(). * * @see applyDefaults */ - applyDefaultsSync(options?: ElectronSettings.ApplyDefaultsOptions.Param): void; + applyDefaultsSync(options?: ElectronSettings.ApplyDefaultsOptions): void; /** * Resets all settings to defaults. @@ -151,14 +150,14 @@ declare class Settings extends EventEmitter { * @see defaults * @see resetToDefaultsSync */ - resetToDefaults(options?: ElectronSettings.Options.Param): Promise; + resetToDefaults(options?: ElectronSettings.Options): Promise; /** * The synchronous version of resetToDefaults(). * * @see resetToDefaults */ - resetToDefaultsSync(options?: ElectronSettings.Options.Param): void; + resetToDefaultsSync(options?: ElectronSettings.Options): void; /** * Observes the chosen key path for changes and calls the handler if the value changes. @@ -209,40 +208,28 @@ declare namespace ElectronSettings { dispose(): void; } - interface Options extends Pick { } - - namespace Options { - type Param = Options | object; - - interface _Impl { - /** - * Whether electron-settings should create a tmp file during save to ensure data-write consistency. - * - * @default true - */ - atomicSaving: boolean; - /** - * Prettify the JSON output. - * - * @default false - */ - prettify: boolean; - } + interface Options { + /** + * Whether electron-settings should create a tmp file during save to ensure data-write consistency. + * + * @default true + */ + atomicSaving?: boolean; + /** + * Prettify the JSON output. + * + * @default false + */ + prettify?: boolean; } - interface ApplyDefaultsOptions extends Pick { } - - namespace ApplyDefaultsOptions { - type Param = ApplyDefaultsOptions | object; - - interface _Impl extends Options._Impl { - /** - * Overwrite pre-existing settings with their respective default values. - * - * @default false - */ - overwrite: boolean; - } + interface ApplyDefaultsOptions extends Options { + /** + * Overwrite pre-existing settings with their respective default values. + * + * @default false + */ + overwrite?: boolean; } interface ChangeEvent { diff --git a/types/electron-settings/v2/tsconfig.json b/types/electron-settings/v2/tsconfig.json index 3a5b7b152c..335711f7ef 100644 --- a/types/electron-settings/v2/tsconfig.json +++ b/types/electron-settings/v2/tsconfig.json @@ -4,6 +4,7 @@ "lib": [ "es6" ], + "target": "es2015", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, From 6cfc342e879fb3a3d3e2bd48dfd524997c96f1fd Mon Sep 17 00:00:00 2001 From: mbilsing Date: Thu, 29 Jun 2017 14:32:40 +0200 Subject: [PATCH 0050/1618] . --- types/codemirror/codemirror-showhint.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/codemirror/codemirror-showhint.d.ts b/types/codemirror/codemirror-showhint.d.ts index 745e481737..c6f367d0d2 100644 --- a/types/codemirror/codemirror-showhint.d.ts +++ b/types/codemirror/codemirror-showhint.d.ts @@ -1,6 +1,8 @@ // Type definitions for CodeMirror // Project: https://github.com/marijnh/CodeMirror -// Definitions by: jacqt , basarat , mbilsing +// Definitions by: jacqt +// basarat +// mbilsing // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // See docs https://codemirror.net/doc/manual.html#addon_show-hint From 41eb14e2dd0bb885d50b49010d910584a20bab16 Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Thu, 29 Jun 2017 14:46:14 +0200 Subject: [PATCH 0051/1618] updated i18n on alexa-sdk --- types/alexa-sdk/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 256d3fee9a..466b8822d4 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -41,7 +41,7 @@ export interface Handler { context: any; name: any; isOverriden: any; - t: (token: string) => void; + t: (token: string, ...args: any[]) => void; } export interface Context { From 2b74ee5cdbc378eda36f88be536b7ba54b39bf73 Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Thu, 29 Jun 2017 14:51:40 +0200 Subject: [PATCH 0052/1618] fix: LaunchRequest OR IntentRequest OR SessionEndedRequest --- types/alexa-sdk/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 466b8822d4..10348e0332 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -58,7 +58,7 @@ export interface Context { export interface RequestBody { version: string; session: Session; - request: LaunchRequest | IntentRequest | SessionEndedRequest; + request: LaunchRequest & IntentRequest & SessionEndedRequest; } export interface Session { From cbdf74e0df7c2d785664d2e716da439fcba16b1c Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Thu, 29 Jun 2017 15:04:34 +0200 Subject: [PATCH 0053/1618] alexa-sdk: added locale property and optionalized accessToken is optional, e.g. doesn't get sent on every request --- types/alexa-sdk/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 10348e0332..3ced78ffed 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -75,7 +75,7 @@ export interface SessionApplication { export interface SessionUser { userId: string; - accessToken: string; + accessToken?: string; } export interface LaunchRequest extends Request { } @@ -105,6 +105,7 @@ export interface Request { type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; requestId: string; timeStamp: string; + locale: string; } export interface ResponseBody { From 8672af4c429eaed9a9991c60d07097d6d423042b Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Thu, 29 Jun 2017 15:07:02 +0200 Subject: [PATCH 0054/1618] made locale optional --- types/alexa-sdk/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 3ced78ffed..335ad64739 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -105,7 +105,7 @@ export interface Request { type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; requestId: string; timeStamp: string; - locale: string; + locale?: string; } export interface ResponseBody { From c8cce22c80b83cb0b10e7698660a97e62de69ece Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Thu, 29 Jun 2017 15:11:27 +0200 Subject: [PATCH 0055/1618] refactor(alexa-sdk): moved Request types together made their properties optional so each of them can be used --- types/alexa-sdk/index.d.ts | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 335ad64739..c3b71258da 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -81,33 +81,34 @@ export interface SessionUser { export interface LaunchRequest extends Request { } export interface IntentRequest extends Request { - dialogState: DialogStates; - intent: Intent; -} - -export interface SlotValue { - confirmationStatus: ConfirmationStatuses; - name: string; - value?: any; -} - -export interface Intent { - confirmationStatus: ConfirmationStatuses; - name: string; - slots: Record; + dialogState?: DialogStates; + intent?: Intent; } export interface SessionEndedRequest extends Request { - reason: string; + reason?: string; } export interface Request { type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; requestId: string; - timeStamp: string; - locale?: string; + timestamp: string; + locale?: string } +export interface SlotValue { + confirmationStatus?: ConfirmationStatuses; + name: string; + value?: any; +} + +export interface Intent { + confirmationStatus?: ConfirmationStatuses; + name: string; + slots: Record; +} + + export interface ResponseBody { version: string; sessionAttributes?: any; @@ -143,3 +144,4 @@ export interface Image { export interface Reprompt { outputSpeech: OutputSpeech; } + From 83185cb5220766286b96b22dfaa0e653487c8c85 Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Thu, 29 Jun 2017 15:17:56 +0200 Subject: [PATCH 0056/1618] made the request use type inference instead --- types/alexa-sdk/index.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index c3b71258da..88e25927d6 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -6,14 +6,14 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void ): AlexaObject; +export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void ): AlexaObject; export function CreateStateHandler(state: string, obj: any): any; export let StateString: string; export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED"; export type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED"; -export interface AlexaObject extends Handler { +export interface AlexaObject extends Handler { _event: any; _context: any; _callback: any; @@ -22,21 +22,21 @@ export interface AlexaObject extends Handler { response: any; dynamoDBTableName: any; saveBeforeResponse: boolean; - registerHandlers: (...handlers: Handlers[]) => any; + registerHandlers: (...handlers: Handlers[]) => any; execute: () => void; } -export interface Handlers { - [intent: string]: (this: Handler) => void; +export interface Handlers { + [intent: string]: (this: Handler) => void; } -export interface Handler { +export interface Handler { on: any; emit(event: string, ...args: any[]): boolean; emitWithState: any; state: any; handler: any; - event: RequestBody; + event: RequestBody; attributes: any; context: any; name: any; @@ -55,10 +55,10 @@ export interface Context { awsRequestId: string; } -export interface RequestBody { +export interface RequestBody { version: string; session: Session; - request: LaunchRequest & IntentRequest & SessionEndedRequest; + request: T; } export interface Session { From f48fb58bd26006d0048d1a522c5c35532853aa4d Mon Sep 17 00:00:00 2001 From: Vincas Date: Wed, 28 Jun 2017 22:39:43 +0300 Subject: [PATCH 0057/1618] Update react-fontawesome typedefs according to TS documentation template: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-class-d-ts.html --- types/react-fontawesome/index.d.ts | 55 ++++++++++--------- .../react-fontawesome-tests.tsx | 2 - types/react-fontawesome/tslint.json | 1 + 3 files changed, 29 insertions(+), 29 deletions(-) create mode 100644 types/react-fontawesome/tslint.json diff --git a/types/react-fontawesome/index.d.ts b/types/react-fontawesome/index.d.ts index bc1fa7b3b6..1c7312b6b9 100644 --- a/types/react-fontawesome/index.d.ts +++ b/types/react-fontawesome/index.d.ts @@ -1,35 +1,36 @@ -// Type definitions for react-fontawesome 1.5.0 +// Type definitions for react-fontawesome 1.6 // Project: https://github.com/danawoodman/react-fontawesome -// Definitions by: Timur Rustamov , Anton Kandybo +// Definitions by: Timur Rustamov , +// Anton Kandybo +// Vincas Stonys // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -declare module "react-fontawesome" { +import * as React from 'react'; - import * as React from 'react'; +export = FontAwesome; - type FontAwesomeSize = 'lg' | '2x' | '3x' | '4x' | '5x'; - type FontAwesomeStack = "1x" | "2x"; - type FontAwesomeFlip = "horizontal" | "vertical"; +declare namespace FontAwesome { + type FontAwesomeSize = 'lg' | '2x' | '3x' | '4x' | '5x'; + type FontAwesomeStack = "1x" | "2x"; + type FontAwesomeFlip = "horizontal" | "vertical"; - interface FontAwesomeProps { - ariaLabel?: string, - border?: boolean, - className?: string, - cssModule?: any, - fixedWidth?: boolean, - flip?: FontAwesomeFlip, - inverse?: boolean, - name: string, - pulse?: boolean, - rotate?: number, - size?: FontAwesomeSize, - spin?: boolean, - stack?: FontAwesomeStack, - tag?: string - } - - class FontAwesome extends React.Component {} - - export = FontAwesome; + interface FontAwesomeProps { + ariaLabel?: string; + border?: boolean; + className?: string; + cssModule?: any; + fixedWidth?: boolean; + flip?: FontAwesomeFlip; + inverse?: boolean; + name: string; + pulse?: boolean; + rotate?: number; + size?: FontAwesomeSize; + spin?: boolean; + stack?: FontAwesomeStack; + tag?: string; + } } + +declare class FontAwesome extends React.Component {} diff --git a/types/react-fontawesome/react-fontawesome-tests.tsx b/types/react-fontawesome/react-fontawesome-tests.tsx index 3ec0ded7a2..6c0b51fab7 100644 --- a/types/react-fontawesome/react-fontawesome-tests.tsx +++ b/types/react-fontawesome/react-fontawesome-tests.tsx @@ -3,9 +3,7 @@ import * as ReactDOM from "react-dom"; import FontAwesome = require('react-fontawesome'); class TestComponent extends React.Component { - render() { - return ( Date: Thu, 29 Jun 2017 15:55:00 -0400 Subject: [PATCH 0058/1618] [semantic-ui-accordion] Different weak-type workaround. --- types/semantic-ui-accordion/global.d.ts | 49 +++++++++++++++---- .../semantic-ui-accordion-tests.ts | 40 ++++++++------- 2 files changed, 62 insertions(+), 27 deletions(-) diff --git a/types/semantic-ui-accordion/global.d.ts b/types/semantic-ui-accordion/global.d.ts index 33e3080dfb..4764e88db6 100644 --- a/types/semantic-ui-accordion/global.d.ts +++ b/types/semantic-ui-accordion/global.d.ts @@ -29,17 +29,39 @@ declare namespace SemanticUI { (behavior: 'destroy'): JQuery; (behavior: 'setting', name: K, value?: undefined): AccordionSettings[K]; (behavior: 'setting', name: K, value: AccordionSettings[K]): JQuery; - (behavior: 'setting', value: AccordionSettings.Param): JQuery; - (settings?: AccordionSettings.Param): JQuery; + (behavior: 'setting', value: AccordionSettings): JQuery; + (settings?: AccordionSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/accordion.html#/settings} */ - interface AccordionSettings extends Pick { } + type AccordionSettings = AccordionSettings.Param; namespace AccordionSettings { - type Param = AccordionSettings | object; + type Param = (Pick<_Impl, 'exclusive'> | + Pick<_Impl, 'on'> | + Pick<_Impl, 'animateChildren'> | + Pick<_Impl, 'closeNested'> | + Pick<_Impl, 'collapsible'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'easing'> | + Pick<_Impl, 'observeChanges'> | + Pick<_Impl, 'onOpening'> | + Pick<_Impl, 'onOpen'> | + Pick<_Impl, 'onClosing'> | + Pick<_Impl, 'onClose'> | + Pick<_Impl, 'onChange'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Behavior @@ -181,10 +203,14 @@ declare namespace SemanticUI { } namespace Accordion { - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'accordion'> | + Pick<_Impl, 'title'> | + Pick<_Impl, 'trigger'> | + Pick<_Impl, 'content'>) & + Partial>; interface _Impl { /** @@ -206,10 +232,12 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'animating'>) & + Partial>; interface _Impl { /** @@ -223,10 +251,11 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-accordion/semantic-ui-accordion-tests.ts b/types/semantic-ui-accordion/semantic-ui-accordion-tests.ts index 7ab192f847..87aad211e1 100644 --- a/types/semantic-ui-accordion/semantic-ui-accordion-tests.ts +++ b/types/semantic-ui-accordion/semantic-ui-accordion-tests.ts @@ -9,15 +9,16 @@ function test_static() { function test_accordion() { const selector = '.ui.accordion'; - $(selector).accordion('refresh') === $(); - $(selector).accordion('open', 3) === $(); - $(selector).accordion('close others') === $(); - $(selector).accordion('close', 10) === $(); - $(selector).accordion('toggle', 5) === $(); - $(selector).accordion('destroy') === $(); - $(selector).accordion('setting', 'debug', undefined) === false; - $(selector).accordion('setting', 'debug') === false; - $(selector).accordion('setting', 'debug', true) === $(); + $(selector).accordion('refresh'); // $ExpectType JQuery + $(selector).accordion('open', 3); // $ExpectType JQuery + $(selector).accordion('close others'); // $ExpectType JQuery + $(selector).accordion('close', 10); // $ExpectType JQuery + $(selector).accordion('toggle', 5); // $ExpectType JQuery + $(selector).accordion('destroy'); // $ExpectType JQuery + $(selector).accordion('setting', 'debug', undefined); // $ExpectType boolean + $(selector).accordion('setting', 'debug'); // $ExpectType boolean + $(selector).accordion('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).accordion('setting', { namespace: 'namespace', name: 'name', @@ -25,7 +26,8 @@ function test_accordion() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).accordion({ exclusive: true, on: 'on', @@ -36,19 +38,19 @@ function test_accordion() { easing: 'easeInOutQuint', observeChanges: true, onOpening() { - this === $(); + this; // $ExpectType JQuery }, onOpen() { - this === $(); + this; // $ExpectType JQuery }, onClosing() { - this === $(); + this; // $ExpectType JQuery }, onClose() { - this === $(); + this; // $ExpectType JQuery }, onChange() { - this === $(); + this; // $ExpectType JQuery }, selector: { accordion: 'accordion', @@ -63,12 +65,16 @@ function test_accordion() { error: { method: 'method' } - }) === $(); - $(selector).accordion() === $(); + }); + $(selector).accordion(); // $ExpectType JQuery + + $(selector).accordion('foo'); // $ExpectError + $(selector).accordion({ foo: 'bar' }); // $ExpectError } import accordion = require('semantic-ui-accordion'); function test_module() { + accordion; // $ExpectType Accordion $.fn.accordion = accordion; } From 54711afc67a524ac2f0fdd84ae6241614dea2b77 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 16:44:31 -0400 Subject: [PATCH 0059/1618] [semantic-ui-api] Different weak-type workaround. --- types/semantic-ui-api/global.d.ts | 104 +++++++++++++++--- .../semantic-ui-api/semantic-ui-api-tests.ts | 70 ++++++------ 2 files changed, 129 insertions(+), 45 deletions(-) diff --git a/types/semantic-ui-api/global.d.ts b/types/semantic-ui-api/global.d.ts index 5c644a4d8d..c6e87f2fc7 100644 --- a/types/semantic-ui-api/global.d.ts +++ b/types/semantic-ui-api/global.d.ts @@ -100,16 +100,61 @@ declare namespace SemanticUI { (behavior: 'destroy'): JQuery; (behavior: 'setting', name: K, value?: undefined): ApiSettings[K]; (behavior: 'setting', name: K, value: ApiSettings[K]): JQuery; - (behavior: 'setting', value: ApiSettings | object): JQuery; - (settings?: ApiSettings | object): JQuery; + (behavior: 'setting', value: ApiSettings): JQuery; + (settings?: ApiSettings): JQuery; } /** * @see {@link http://semantic-ui.com/behaviors/api.html#/settings} */ - interface ApiSettings extends Pick { } + type ApiSettings = ApiSettings.Param; namespace ApiSettings { + type Param = (Pick<_Impl, 'on'> | + Pick<_Impl, 'cache'> | + Pick<_Impl, 'stateContext'> | + Pick<_Impl, 'encodeParameters'> | + Pick<_Impl, 'defaultData'> | + Pick<_Impl, 'serializeForm'> | + Pick<_Impl, 'throttle'> | + Pick<_Impl, 'throttleFirstRequest'> | + Pick<_Impl, 'interruptRequests'> | + Pick<_Impl, 'loadingDuration'> | + Pick<_Impl, 'hideError'> | + Pick<_Impl, 'errorDuration'> | + Pick<_Impl, 'action'> | + Pick<_Impl, 'url'> | + Pick<_Impl, 'urlData'> | + Pick<_Impl, 'response'> | + Pick<_Impl, 'responseAsync'> | + Pick<_Impl, 'mockResponse'> | + Pick<_Impl, 'mockResponseAsync'> | + Pick<_Impl, 'method'> | + Pick<_Impl, 'dataType'> | + Pick<_Impl, 'data'> | + Pick<_Impl, 'beforeSend'> | + Pick<_Impl, 'beforeXHR'> | + Pick<_Impl, 'onRequest'> | + Pick<_Impl, 'onResponse'> | + Pick<_Impl, 'successTest'> | + Pick<_Impl, 'onSuccess'> | + Pick<_Impl, 'onComplete'> | + Pick<_Impl, 'onFailure'> | + Pick<_Impl, 'onError'> | + Pick<_Impl, 'onAbort'> | + Pick<_Impl, 'regExp'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; + interface _Impl { // region Behavior @@ -246,11 +291,11 @@ declare namespace SemanticUI { /** * Allows modifying XHR object for request */ - beforeXHR(xhrObject: JQueryXHR): any; + beforeXHR(xhrObject: JQuery.jqXHR): any; /** * Callback that occurs when request is made. Receives both the API success promise and the XHR request promise. */ - onRequest(promise: JQueryDeferred, xhr: JQueryXHR): void; + onRequest(promise: JQuery.Deferred, xhr: JQuery.jqXHR): void; /** * Allows modifying the server's response before parsed by other callbacks to determine API event success */ @@ -264,11 +309,11 @@ declare namespace SemanticUI { /** * Callback after successful response, JSON response must pass successTest */ - onSuccess(response: any, element: JQuery, xhr: JQueryXHR): void; + onSuccess(response: any, element: JQuery, xhr: JQuery.jqXHR): void; /** * Callback on request complete regardless of conditions */ - onComplete(response: any, element: JQuery, xhr: JQueryXHR): void; + onComplete(response: any, element: JQuery, xhr: JQuery.jqXHR): void; /** * Callback on failed response, or JSON response that fails successTest */ @@ -276,11 +321,11 @@ declare namespace SemanticUI { /** * Callback on server error from returned status code, or XHR failure. */ - onError(errorMessage: string, element: JQuery, xhr: JQueryXHR): void; + onError(errorMessage: string, element: JQuery, xhr: JQuery.jqXHR): void; /** * Callback on abort caused by user clicking a link or manually cancelling request. */ - onAbort(errorMessage: string, element: JQuery, xhr: JQueryXHR): void; + onAbort(errorMessage: string, element: JQuery, xhr: JQuery.jqXHR): void; // endregion @@ -352,9 +397,13 @@ declare namespace SemanticUI { } namespace Api { - interface RegExpSettings extends Pick { } + type RegExpSettings = RegExpSettings.Param; namespace RegExpSettings { + type Param = (Pick<_Impl, 'required'> | + Pick<_Impl, 'optional'>) & + Partial>; + interface _Impl { /** * @default /\{\$*[A-z0-9]+\}/g @@ -367,9 +416,13 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { + type Param = (Pick<_Impl, 'disabled'> | + Pick<_Impl, 'form'>) & + Partial>; + interface _Impl { /** * @default '.disabled' @@ -382,9 +435,13 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { + type Param = (Pick<_Impl, 'loading'> | + Pick<_Impl, 'error'>) & + Partial>; + interface _Impl { /** * @default 'loading' @@ -397,9 +454,13 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { + type Param = (Pick<_Impl, 'action'> | + Pick<_Impl, 'url'>) & + Partial>; + interface _Impl { /** * @default 'action' @@ -412,9 +473,24 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { + type Param = (Pick<_Impl, 'beforeSend'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'exitConditions'> | + Pick<_Impl, 'JSONParse'> | + Pick<_Impl, 'legacyParameters'> | + Pick<_Impl, 'missingAction'> | + Pick<_Impl, 'missingSerialize'> | + Pick<_Impl, 'missingURL'> | + Pick<_Impl, 'noReturnedValue'> | + Pick<_Impl, 'parseError'> | + Pick<_Impl, 'requiredParameter'> | + Pick<_Impl, 'statusMessage'> | + Pick<_Impl, 'timeout'>) & + Partial>; + interface _Impl { /** * @default 'The before send function has aborted the request' diff --git a/types/semantic-ui-api/semantic-ui-api-tests.ts b/types/semantic-ui-api/semantic-ui-api-tests.ts index 683c1a35c4..c6605ad60d 100644 --- a/types/semantic-ui-api/semantic-ui-api-tests.ts +++ b/types/semantic-ui-api/semantic-ui-api-tests.ts @@ -1,5 +1,5 @@ function test_api_static() { - $.api.settings.className.error = 'error'; + $.api.settings.className!.error = 'error'; $.api.settings.namespace = 'namespace'; $.api.settings.name = 'name'; $.api.settings.silent = false; @@ -17,10 +17,11 @@ function test_api_static() { function test_api() { const selector = '.ui.api'; - $(selector).api('destroy') === $(); - $(selector).api('setting', 'debug', undefined) === false; + $(selector).api('destroy'); // $ExpectType JQuery + $(selector).api('setting', 'debug', undefined) === true; $(selector).api('setting', 'debug') === false; - $(selector).api('setting', 'debug', true) === $(); + $(selector).api('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).api('setting', { namespace: 'namespace', name: 'name', @@ -28,7 +29,8 @@ function test_api() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).api({ on: 'on', cache: true, @@ -47,56 +49,58 @@ function test_api() { urlData: false, response: false, responseAsync(settings, callback) { - settings === ({} as SemanticUI.ApiSettings); - callback === ((response: any) => { }); + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void }, mockResponse: false, mockResponseAsync(settings, callback) { - settings === ({} as SemanticUI.ApiSettings); - callback === ((response: any) => { }); + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void }, method: 'post', dataType: 'xml', data: {}, beforeSend(settings) { - settings === ({} as SemanticUI.ApiSettings); + settings; // $ExpectType Param }, beforeXHR(xhrObject) { - xhrObject === ({} as JQueryXHR); + xhrObject; // $ExpectType jqXHR }, onRequest(promise, xhr) { - promise === ({} as JQueryDeferred); - xhr === ({} as JQueryXHR); + promise; // $ExpectType Deferred + xhr; // $ExpectType jqXHR }, onResponse(response) { - response === ({} as any); + response; // $ExpectType any }, successTest(response) { - return response === ({} as any); + response; // $ExpectType any + + return false; }, onSuccess(response, element, xhr) { - response === ({} as any); - element === $(); - xhr === ({} as JQueryXHR); + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onComplete(response, element, xhr) { - response === ({} as any); - element === $(); - xhr === ({} as JQueryXHR); + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onFailure(response, element) { - response === ({} as any); - element === $(); + response; // $ExpectType any + element; // $ExpectType JQuery }, onError(errorMessage, element, xhr) { - errorMessage === ''; - element === $(); - xhr === ({} as JQueryXHR); + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onAbort(errorMessage, element, xhr) { - errorMessage === ''; - element === $(); - xhr === ({} as JQueryXHR); + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, regExp: { required: /{\$*[A-z0-9]+}/g, @@ -129,12 +133,16 @@ function test_api() { statusMessage: 'statusMessage', timeout: 'timeout' } - }) === $(); - $(selector).api() === $(); + }); + $(selector).api(); // $ExpectType JQuery + + $(selector).api('foo'); // $ExpectError + $(selector).api({ foo: 'bar' }); // $ExpectError } import api = require('semantic-ui-api'); function test_module() { + api; // $ExpectType Api $.fn.api = api; } From 5ed1a965d0333151629b920e23b307c0ecc6948d Mon Sep 17 00:00:00 2001 From: Jonny Taylor Date: Thu, 29 Jun 2017 22:10:44 +0100 Subject: [PATCH 0060/1618] correct format for UMD module --- types/mainloop.js/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/mainloop.js/index.d.ts b/types/mainloop.js/index.d.ts index e6263218c1..f6162d2316 100644 --- a/types/mainloop.js/index.d.ts +++ b/types/mainloop.js/index.d.ts @@ -3,10 +3,6 @@ // Definitions by: Isaac Sukin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'mainloop.js' { - export default MainLoop; -} - /** * Interface for the MainLoop.js global. * @@ -30,3 +26,7 @@ interface MainLoop { } declare var MainLoop: MainLoop; + +export = MainLoop; +export as namespace MainLoop; + From a94cdc51ca961bcd4fc140cafa65ca5768135163 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 17:14:00 -0400 Subject: [PATCH 0061/1618] [semantic-ui-checkbox] Different weak-type workaround. --- types/semantic-ui-checkbox/global.d.ts | 59 ++++++++++---- .../semantic-ui-checkbox-tests.ts | 76 +++++++++++-------- 2 files changed, 90 insertions(+), 45 deletions(-) diff --git a/types/semantic-ui-checkbox/global.d.ts b/types/semantic-ui-checkbox/global.d.ts index fd3159b5b6..45733f20f6 100644 --- a/types/semantic-ui-checkbox/global.d.ts +++ b/types/semantic-ui-checkbox/global.d.ts @@ -97,17 +97,41 @@ declare namespace SemanticUI { (behavior: 'destroy'): JQuery; (behavior: 'setting', name: K, value?: undefined): CheckboxSettings[K]; (behavior: 'setting', name: K, value: CheckboxSettings[K]): JQuery; - (behavior: 'setting', value: CheckboxSettings.Param): JQuery; - (settings?: CheckboxSettings.Param): JQuery; + (behavior: 'setting', value: CheckboxSettings): JQuery; + (settings?: CheckboxSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/checkbox.html#/settings} */ - interface CheckboxSettings extends Pick { } + type CheckboxSettings = CheckboxSettings.Param; namespace CheckboxSettings { - type Param = CheckboxSettings | object; + type Param = (Pick<_Impl, 'uncheckable'> | + Pick<_Impl, 'fireOnInit'> | + Pick<_Impl, 'onChange'> | + Pick<_Impl, 'onChecked'> | + Pick<_Impl, 'onIndeterminate'> | + Pick<_Impl, 'onDeterminate'> | + Pick<_Impl, 'onUnchecked'> | + Pick<_Impl, 'beforeChecked'> | + Pick<_Impl, 'beforeIndeterminate'> | + Pick<_Impl, 'beforeDeterminate'> | + Pick<_Impl, 'beforeUnchecked'> | + Pick<_Impl, 'onEnable'> | + Pick<_Impl, 'onDisable'> | + Pick<_Impl, 'onEnabled'> | + Pick<_Impl, 'onDisabled'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Behavior @@ -152,19 +176,19 @@ declare namespace SemanticUI { /** * Callback before a checkbox is checked. Can cancel change by returning false */ - beforeChecked(this: HTMLElement): boolean; + beforeChecked(this: HTMLElement): void | false; /** * Callback before a checkbox is set to undeterminate. Can cancel change by returning false */ - beforeIndeterminate(this: HTMLElement): boolean; + beforeIndeterminate(this: HTMLElement): void | false; /** * Callback before a checkbox is set to determinate. Can cancel change by returning false */ - beforeDeterminate(this: HTMLElement): boolean; + beforeDeterminate(this: HTMLElement): void | false; /** * Callback before a checkbox is unchecked. Can cancel change by returning false */ - beforeUnchecked(this: HTMLElement): boolean; + beforeUnchecked(this: HTMLElement): void | false; /** * Callback after a checkbox is enabled. */ @@ -248,10 +272,12 @@ declare namespace SemanticUI { } namespace Checkbox { - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'input'> | + Pick<_Impl, 'label'>) & + Partial>; interface _Impl { /** @@ -265,10 +291,14 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'checked'> | + Pick<_Impl, 'disabled'> | + Pick<_Impl, 'radio'> | + Pick<_Impl, 'readOnly'>) & + Partial>; interface _Impl { /** @@ -290,10 +320,11 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts b/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts index 30ff41ebd3..fbb15ca33e 100644 --- a/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts +++ b/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts @@ -1,5 +1,5 @@ function test_checkbox_static() { - $.fn.checkbox.settings.error.method = 'method'; + $.fn.checkbox.settings.error!.method = 'method'; $.fn.checkbox.settings.namespace = 'namespace'; $.fn.checkbox.settings.name = 'name'; $.fn.checkbox.settings.silent = false; @@ -10,19 +10,19 @@ function test_checkbox_static() { function test_checkbox() { const selector = '.ui.checkbox'; - $(selector).checkbox('toggle') === $(); - $(selector).checkbox('check') === $(); - $(selector).checkbox('uncheck') === $(); - $(selector).checkbox('indeterminate') === $(); - $(selector).checkbox('determinate') === $(); - $(selector).checkbox('enable') === $(); - $(selector).checkbox('set checked') === $(); - $(selector).checkbox('set unchecked') === $(); - $(selector).checkbox('set indeterminate') === $(); - $(selector).checkbox('set determinate') === $(); - $(selector).checkbox('set enabled') === $(); - $(selector).checkbox('set disabled') === $(); - $(selector).checkbox('attach events', $(), 'click') === $(); + $(selector).checkbox('toggle'); // $ExpectType JQuery + $(selector).checkbox('check'); // $ExpectType JQuery + $(selector).checkbox('uncheck'); // $ExpectType JQuery + $(selector).checkbox('indeterminate'); // $ExpectType JQuery + $(selector).checkbox('determinate'); // $ExpectType JQuery + $(selector).checkbox('enable'); // $ExpectType JQuery + $(selector).checkbox('set checked'); // $ExpectType JQuery + $(selector).checkbox('set unchecked'); // $ExpectType JQuery + $(selector).checkbox('set indeterminate'); // $ExpectType JQuery + $(selector).checkbox('set determinate'); // $ExpectType JQuery + $(selector).checkbox('set enabled'); // $ExpectType JQuery + $(selector).checkbox('set disabled'); // $ExpectType JQuery + $(selector).checkbox('attach events', $(), 'click'); // $ExpectType JQuery $(selector).checkbox('is radio') === true; $(selector).checkbox('is checked') === true; $(selector).checkbox('is unchecked') === true; @@ -34,7 +34,8 @@ function test_checkbox() { $(selector).checkbox('can uncheck') === true; $(selector).checkbox('setting', 'debug', undefined) === false; $(selector).checkbox('setting', 'debug') === false; - $(selector).checkbox('setting', 'debug', true) === $(); + $(selector).checkbox('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).checkbox('setting', { namespace: 'namespace', name: 'name', @@ -42,48 +43,57 @@ function test_checkbox() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).checkbox({ uncheckable: false, fireOnInit: true, onChange() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, onChecked() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, onIndeterminate() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, onDeterminate() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, onUnchecked() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, beforeChecked() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement + + return false; }, beforeIndeterminate() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement + + return false; }, beforeDeterminate() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement + + return false; }, beforeUnchecked() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement + + return false; }, onEnable() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, onDisable() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, onEnabled() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, onDisabled() { - this === new HTMLElement(); + this; // $ExpectType HTMLElement }, selector: { input: 'input', @@ -98,12 +108,16 @@ function test_checkbox() { error: { method: 'method' } - }) === $(); - $(selector).checkbox() === $(); + }); + $(selector).checkbox(); // $ExpectType JQuery + + $(selector).checkbox('foo'); // $ExpectError + $(selector).checkbox({ foo: 'bar' }); // $ExpectError } import checkbox = require('semantic-ui-checkbox'); function test_module() { + checkbox; // $ExpectType Checkbox $.fn.checkbox = checkbox; } From 210fb742394434a18a79e5596ebc5cf7c142864c Mon Sep 17 00:00:00 2001 From: Jonny Taylor Date: Thu, 29 Jun 2017 22:24:27 +0100 Subject: [PATCH 0062/1618] remove extra line --- types/mainloop.js/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/mainloop.js/index.d.ts b/types/mainloop.js/index.d.ts index f6162d2316..98c916d354 100644 --- a/types/mainloop.js/index.d.ts +++ b/types/mainloop.js/index.d.ts @@ -29,4 +29,3 @@ declare var MainLoop: MainLoop; export = MainLoop; export as namespace MainLoop; - From 2dcde50e7b516c3454aa54189b3273d344e3c2e3 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 17:25:49 -0400 Subject: [PATCH 0063/1618] [semantic-ui-checkbox] this in callbacks can be HTMLInputElement. --- types/semantic-ui-checkbox/global.d.ts | 26 +++++++++---------- .../semantic-ui-checkbox-tests.ts | 26 +++++++++---------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/types/semantic-ui-checkbox/global.d.ts b/types/semantic-ui-checkbox/global.d.ts index 45733f20f6..c92feb00ec 100644 --- a/types/semantic-ui-checkbox/global.d.ts +++ b/types/semantic-ui-checkbox/global.d.ts @@ -156,59 +156,59 @@ declare namespace SemanticUI { /** * Callback after a checkbox is either checked or unchecked. */ - onChange(this: HTMLElement): void; + onChange(this: HTMLInputElement): void; /** * Callback after a checkbox is checked. */ - onChecked(this: HTMLElement): void; + onChecked(this: HTMLInputElement): void; /** * Callback after a checkbox is set to undeterminate. */ - onIndeterminate(this: HTMLElement): void; + onIndeterminate(this: HTMLInputElement): void; /** * Callback after a checkbox is set to determinate. */ - onDeterminate(this: HTMLElement): void; + onDeterminate(this: HTMLInputElement): void; /** * Callback after a checkbox is unchecked. */ - onUnchecked(this: HTMLElement): void; + onUnchecked(this: HTMLInputElement): void; /** * Callback before a checkbox is checked. Can cancel change by returning false */ - beforeChecked(this: HTMLElement): void | false; + beforeChecked(this: HTMLInputElement): void | false; /** * Callback before a checkbox is set to undeterminate. Can cancel change by returning false */ - beforeIndeterminate(this: HTMLElement): void | false; + beforeIndeterminate(this: HTMLInputElement): void | false; /** * Callback before a checkbox is set to determinate. Can cancel change by returning false */ - beforeDeterminate(this: HTMLElement): void | false; + beforeDeterminate(this: HTMLInputElement): void | false; /** * Callback before a checkbox is unchecked. Can cancel change by returning false */ - beforeUnchecked(this: HTMLElement): void | false; + beforeUnchecked(this: HTMLInputElement): void | false; /** * Callback after a checkbox is enabled. */ - onEnable(this: HTMLElement): void; + onEnable(this: HTMLInputElement): void; /** * Callback after a checkbox is disabled. */ - onDisable(this: HTMLElement): void; + onDisable(this: HTMLInputElement): void; /** * Callback after a checkbox is enabled. * * @deprecated */ - onEnabled(this: HTMLElement): void; + onEnabled(this: HTMLInputElement): void; /** * Callback after a checkbox is disabled. * * @deprecated */ - onDisabled(this: HTMLElement): void; + onDisabled(this: HTMLInputElement): void; // endregion diff --git a/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts b/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts index fbb15ca33e..82ef101f77 100644 --- a/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts +++ b/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts @@ -49,51 +49,51 @@ function test_checkbox() { uncheckable: false, fireOnInit: true, onChange() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, onChecked() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, onIndeterminate() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, onDeterminate() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, onUnchecked() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, beforeChecked() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement return false; }, beforeIndeterminate() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement return false; }, beforeDeterminate() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement return false; }, beforeUnchecked() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement return false; }, onEnable() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, onDisable() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, onEnabled() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, onDisabled() { - this; // $ExpectType HTMLElement + this; // $ExpectType HTMLInputElement }, selector: { input: 'input', From 18c03e9b4baf30295acbf2ca3faedd5322ae7bfe Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 17:38:18 -0400 Subject: [PATCH 0064/1618] [semantic-ui-accordion] Fix setting behavior return type. --- types/semantic-ui-accordion/global.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/semantic-ui-accordion/global.d.ts b/types/semantic-ui-accordion/global.d.ts index 4764e88db6..5578714096 100644 --- a/types/semantic-ui-accordion/global.d.ts +++ b/types/semantic-ui-accordion/global.d.ts @@ -27,8 +27,8 @@ declare namespace SemanticUI { */ (behavior: 'toggle', index: number): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): AccordionSettings[K]; - (behavior: 'setting', name: K, value: AccordionSettings[K]): JQuery; + (behavior: 'setting', name: K, value?: undefined): AccordionSettings._Impl[K]; + (behavior: 'setting', name: K, value: AccordionSettings._Impl[K]): JQuery; (behavior: 'setting', value: AccordionSettings): JQuery; (settings?: AccordionSettings): JQuery; } From e1ceafbaa4c68eb70add605bddb9c8ed1c58d031 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 17:41:30 -0400 Subject: [PATCH 0065/1618] [semantic-ui-api] Fix setting behavior return type. --- types/semantic-ui-api/global.d.ts | 4 ++-- types/semantic-ui-api/semantic-ui-api-tests.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/semantic-ui-api/global.d.ts b/types/semantic-ui-api/global.d.ts index c6e87f2fc7..a9799bad44 100644 --- a/types/semantic-ui-api/global.d.ts +++ b/types/semantic-ui-api/global.d.ts @@ -98,8 +98,8 @@ declare namespace SemanticUI { * Removes API settings from the page and all events */ (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ApiSettings[K]; - (behavior: 'setting', name: K, value: ApiSettings[K]): JQuery; + (behavior: 'setting', name: K, value?: undefined): ApiSettings._Impl[K]; + (behavior: 'setting', name: K, value: ApiSettings._Impl[K]): JQuery; (behavior: 'setting', value: ApiSettings): JQuery; (settings?: ApiSettings): JQuery; } diff --git a/types/semantic-ui-api/semantic-ui-api-tests.ts b/types/semantic-ui-api/semantic-ui-api-tests.ts index c6605ad60d..ca8107d8ec 100644 --- a/types/semantic-ui-api/semantic-ui-api-tests.ts +++ b/types/semantic-ui-api/semantic-ui-api-tests.ts @@ -18,8 +18,8 @@ function test_api_static() { function test_api() { const selector = '.ui.api'; $(selector).api('destroy'); // $ExpectType JQuery - $(selector).api('setting', 'debug', undefined) === true; - $(selector).api('setting', 'debug') === false; + $(selector).api('setting', 'debug', undefined); // $ExpectType boolean + $(selector).api('setting', 'debug'); // $ExpectType boolean $(selector).api('setting', 'debug', true); // $ExpectType JQuery // $ExpectType JQuery $(selector).api('setting', { From 9e8b31603a4076a21feea1b121d7d69078e4b18a Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 17:43:11 -0400 Subject: [PATCH 0066/1618] [semantic-ui-checkbox] Fix setting behavior return type. --- types/semantic-ui-checkbox/global.d.ts | 4 ++-- .../semantic-ui-checkbox-tests.ts | 22 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/types/semantic-ui-checkbox/global.d.ts b/types/semantic-ui-checkbox/global.d.ts index c92feb00ec..5493498b41 100644 --- a/types/semantic-ui-checkbox/global.d.ts +++ b/types/semantic-ui-checkbox/global.d.ts @@ -95,8 +95,8 @@ declare namespace SemanticUI { */ (behavior: 'can uncheck'): boolean; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): CheckboxSettings[K]; - (behavior: 'setting', name: K, value: CheckboxSettings[K]): JQuery; + (behavior: 'setting', name: K, value?: undefined): CheckboxSettings._Impl[K]; + (behavior: 'setting', name: K, value: CheckboxSettings._Impl[K]): JQuery; (behavior: 'setting', value: CheckboxSettings): JQuery; (settings?: CheckboxSettings): JQuery; } diff --git a/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts b/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts index 82ef101f77..3e0e574eb1 100644 --- a/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts +++ b/types/semantic-ui-checkbox/semantic-ui-checkbox-tests.ts @@ -23,17 +23,17 @@ function test_checkbox() { $(selector).checkbox('set enabled'); // $ExpectType JQuery $(selector).checkbox('set disabled'); // $ExpectType JQuery $(selector).checkbox('attach events', $(), 'click'); // $ExpectType JQuery - $(selector).checkbox('is radio') === true; - $(selector).checkbox('is checked') === true; - $(selector).checkbox('is unchecked') === true; - $(selector).checkbox('can change') === true; - $(selector).checkbox('should allow check') === true; - $(selector).checkbox('should allow uncheck') === true; - $(selector).checkbox('should allow determinate') === true; - $(selector).checkbox('should allow indeterminate') === true; - $(selector).checkbox('can uncheck') === true; - $(selector).checkbox('setting', 'debug', undefined) === false; - $(selector).checkbox('setting', 'debug') === false; + $(selector).checkbox('is radio'); // $ExpectType boolean + $(selector).checkbox('is checked'); // $ExpectType boolean + $(selector).checkbox('is unchecked'); // $ExpectType boolean + $(selector).checkbox('can change'); // $ExpectType boolean + $(selector).checkbox('should allow check'); // $ExpectType boolean + $(selector).checkbox('should allow uncheck'); // $ExpectType boolean + $(selector).checkbox('should allow determinate'); // $ExpectType boolean + $(selector).checkbox('should allow indeterminate'); // $ExpectType boolean + $(selector).checkbox('can uncheck'); // $ExpectType boolean + $(selector).checkbox('setting', 'debug', undefined); // $ExpectType boolean + $(selector).checkbox('setting', 'debug'); // $ExpectType boolean $(selector).checkbox('setting', 'debug', true); // $ExpectType JQuery // $ExpectType JQuery $(selector).checkbox('setting', { From 2637c2c6e4ada1251e49e2945c3d93118ad837e3 Mon Sep 17 00:00:00 2001 From: dpapad Date: Fri, 23 Jun 2017 11:20:34 -0700 Subject: [PATCH 0067/1618] Update lovefield definitions to v2.1.12. Fixes https://github.com/google/lovefield/issues/212. --- types/lovefield/index.d.ts | 269 +++++++++++++++-------------- types/lovefield/lovefield-tests.ts | 64 ++++--- types/lovefield/tslint.json | 12 ++ 3 files changed, 179 insertions(+), 166 deletions(-) create mode 100644 types/lovefield/tslint.json diff --git a/types/lovefield/index.d.ts b/types/lovefield/index.d.ts index 14c010dc4f..3f18bcb6b8 100644 --- a/types/lovefield/index.d.ts +++ b/types/lovefield/index.d.ts @@ -1,12 +1,12 @@ -// Type definitions for Lovefield v2.0.62 +// Type definitions for Lovefield 2.1 // Project: http://google.github.io/lovefield/ // Definitions by: freshp86 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace lf { - export enum Order { ASC, DESC } + enum Order { ASC, DESC } - export enum Type { + enum Type { ARRAY_BUFFER, BOOLEAN, DATE_TIME, @@ -16,218 +16,221 @@ declare namespace lf { STRING } - export enum ConstraintAction { + enum ConstraintAction { RESTRICT, CASCADE } - export enum ConstraintTiming { + enum ConstraintTiming { IMMEDIATE, DEFERRABLE } - export interface Binder { - getIndex(): number + interface Binder { + getIndex(): number; } - export interface Predicate {} - export interface Row {} + interface Predicate {} + interface Row {} type ValueLiteral = string|number|boolean|Date; - export interface PredicateProvider { - eq(operand: ValueLiteral|schema.Column|Binder): Predicate - neq(operand: ValueLiteral|schema.Column|Binder): Predicate - lt(operand: ValueLiteral|schema.Column|Binder): Predicate - lte(operand: ValueLiteral|schema.Column|Binder): Predicate - gt(operand: ValueLiteral|schema.Column|Binder): Predicate - gte(operand: ValueLiteral|schema.Column|Binder): Predicate - match(operand: RegExp|Binder): Predicate - between(from: ValueLiteral|Binder, to: ValueLiteral|Binder): Predicate - in(values: Binder|Array): Predicate - isNull(): Predicate - isNotNull(): Predicate + interface PredicateProvider { + eq(operand: ValueLiteral|schema.Column|Binder): Predicate; + neq(operand: ValueLiteral|schema.Column|Binder): Predicate; + lt(operand: ValueLiteral|schema.Column|Binder): Predicate; + lte(operand: ValueLiteral|schema.Column|Binder): Predicate; + gt(operand: ValueLiteral|schema.Column|Binder): Predicate; + gte(operand: ValueLiteral|schema.Column|Binder): Predicate; + match(operand: RegExp|Binder): Predicate; + between(from: ValueLiteral|Binder, to: ValueLiteral|Binder): Predicate; + in(values: Binder|ValueLiteral[]): Predicate; + isNull(): Predicate; + isNotNull(): Predicate; } function bind(index: number): Binder; - export interface Transaction { - attach(query: query.Builder): Promise> - begin(scope: Array): Promise - commit(): Promise - exec(queries: Array): Promise>> - rollback(): Promise + interface TransactionStats { + success(): boolean; + insertedRowCount(): number; + updatedRowCount(): number; + deletedRowCount(): number; + changedTableCount(): number; } - export enum TransactionType { READ_ONLY, READ_WRITE } + interface Transaction { + attach(query: query.Builder): Promise; + begin(scope: schema.Table[]): Promise; + commit(): Promise; + exec(queries: query.Builder[]): Promise; + rollback(): Promise; + stats(): TransactionStats; + } - export interface Database { - close(): void - createTransaction(type?: TransactionType): Transaction - delete(): query.Delete - export(): Promise - getSchema(): schema.Database - import(data: Object): Promise - insertOrReplace(): query.Insert - insert(): query.Insert - observe(query: query.Select, callback: Function): void - select(...columns: schema.Column[]): query.Select - unobserve(query: query.Select, callback: Function): void - update(table: schema.Table): query.Update + enum TransactionType { READ_ONLY, READ_WRITE } + + interface Database { + close(): void; + createTransaction(type?: TransactionType): Transaction; + delete(): query.Delete; + export(): Promise; + getSchema(): schema.Database; + import(data: Object): Promise; + insertOrReplace(): query.Insert; + insert(): query.Insert; + observe(query: query.Select, callback: Function): void; + select(...columns: schema.Column[]): query.Select; + unobserve(query: query.Select, callback: Function): void; + update(table: schema.Table): query.Update; } namespace query { - export interface Builder { - bind(...values: any[]): Builder - exec(): Promise> - explain(): string - toSql(): string + interface Builder { + bind(...values: any[]): Builder; + exec(): Promise; + explain(): string; + toSql(): string; } - export interface Delete extends Builder { - from(table: schema.Table): Delete - where(predicate: Predicate): Delete + interface Delete extends Builder { + from(table: schema.Table): Delete; + where(predicate: Predicate): Delete; } - export interface Insert extends Builder { - into(table: schema.Table): Insert - values(rows: Array|Binder|Array): Insert + interface Insert extends Builder { + into(table: schema.Table): Insert; + values(rows: Row[]|Binder|Binder[]): Insert; } - export interface Select extends Builder { - from(...tables: schema.Table[]): Select - groupBy(...columns: schema.Column[]): Select - innerJoin(table: schema.Table, predicate: Predicate): Select - leftOuterJoin(table: schema.Table, predicate: Predicate): Select - limit(numberOfRows: Binder|number): Select - orderBy(column: schema.Column, order?: Order): Select - skip(numberOfRows: Binder|number): Select - where(predicate: Predicate): Select + interface Select extends Builder { + from(...tables: schema.Table[]): Select; + groupBy(...columns: schema.Column[]): Select; + innerJoin(table: schema.Table, predicate: Predicate): Select; + leftOuterJoin(table: schema.Table, predicate: Predicate): Select; + limit(numberOfRows: Binder|number): Select; + orderBy(column: schema.Column, order?: Order): Select; + skip(numberOfRows: Binder|number): Select; + where(predicate: Predicate): Select; } - export interface Update extends Builder { - set(column: schema.Column, value: any): Update - where(predicate: Predicate): Update + interface Update extends Builder { + set(column: schema.Column, value: any): Update; + where(predicate: Predicate): Update; } - } // module query - namespace raw { - export interface BackStore { - getRawDBInstance(): any - getRawTransaction(): any - dropTable(tableName: string): Promise + interface BackStore { + getRawDBInstance(): any; + getRawTransaction(): any; + dropTable(tableName: string): Promise; addTableColumn( tableName: string, columnName: string, - defaultValue: string|boolean|number|Date|ArrayBuffer): Promise - dropTableColumn(tableName: string, columnName:string): Promise + defaultValue: string|boolean|number|Date|ArrayBuffer): Promise; + dropTableColumn(tableName: string, columnName: string): Promise; renameTableColumn( tableName: string, oldColumnName: string, - newColumnName:string) : Promise - createRow(payload: Object): Row - getVersion(): number - dump(): Array + newColumnName: string): Promise; + createRow(payload: Object): Row; + getVersion(): number; + dump(): Object[]; } } // module raw - namespace schema { - export enum DataStoreType { - FIREBASE, + enum DataStoreType { INDEXED_DB, - LOCAL_STORAGE, MEMORY, + LOCAL_STORAGE, + FIREBASE, WEB_SQL } - export interface DatabasePragma { - enableBundledMode: boolean + interface DatabasePragma { + enableBundledMode: boolean; } - export interface Database { - name(): string - pragma(): DatabasePragma - tables(): Array - table(tableName: string): schema.Table - version(): number + interface Database { + name(): string; + pragma(): DatabasePragma; + tables(): schema.Table[]; + table(tableName: string): schema.Table; + version(): number; } - export interface Column extends PredicateProvider { - as(name: string): Column - getName(): string - getNormalizedName(): string + interface Column extends PredicateProvider { + as(name: string): Column; + getName(): string; + getNormalizedName(): string; } interface ITable { - as(name: string): Table - createRow(value: Object): Row - getName(): string + as(name: string): Table; + createRow(value: Object): Row; + getName(): string; } - export type Table = ITable & { [index: string]: Column } + type Table = ITable & { [index: string]: Column }; - export interface ConnectOptions { - onUpgrade?: (rawDb: raw.BackStore) => Promise - storeType?: DataStoreType - webSqlDbSize?: number + interface ConnectOptions { + onUpgrade?: (rawDb: raw.BackStore) => Promise; + storeType?: DataStoreType; + webSqlDbSize?: number; // TODO(dpapad): firebase? } - export interface Builder { - connect(options: ConnectOptions): Promise - createTable(tableName: string): TableBuilder - getSchema(): Database - setPragma(pragma: DatabasePragma): void + interface Builder { + connect(options?: ConnectOptions): Promise; + createTable(tableName: string): TableBuilder; + getSchema(): Database; + setPragma(pragma: DatabasePragma): void; } - export interface IndexedColumn { - autoIncrement: boolean - name: string - order: Order + interface IndexedColumn { + autoIncrement: boolean; + name: string; + order: Order; } type RawForeignKeySpec = { local: string ref: string - action: lf.ConstraintAction - timing: lf.ConstraintTiming - } + action?: lf.ConstraintAction + timing?: lf.ConstraintTiming + }; - export interface TableBuilder { - addColumn(name: string, type: lf.Type): TableBuilder - addForeignKey(name: string, spec: RawForeignKeySpec): TableBuilder + interface TableBuilder { + addColumn(name: string, type: lf.Type): TableBuilder; + addForeignKey(name: string, spec: RawForeignKeySpec): TableBuilder; addIndex( - name: string, columns: Array|Array, - unique?: boolean, order?: Order): TableBuilder - addNullable(columns: Array): TableBuilder + name: string, columns: string[]|IndexedColumn[], + unique?: boolean, order?: Order): TableBuilder; + addNullable(columns: string[]): TableBuilder; addPrimaryKey( - columns: Array|Array, - autoInc?: boolean): TableBuilder - addUnique(name: string, columns: Array): TableBuilder + columns: string[]|IndexedColumn[], + autoInc?: boolean): TableBuilder; + addUnique(name: string, columns: string[]): TableBuilder; } - function create(dbName: string, dbVersion: number): Builder + function create(dbName: string, dbVersion: number): Builder; } // module schema - namespace op { function and(...args: Predicate[]): Predicate; function not(operand: Predicate): Predicate; function or(...args: Predicate[]): Predicate; } // module op - namespace fn { - function avg(column: schema.Column): schema.Column - function count(column?: schema.Column): schema.Column - function distinct(column: schema.Column): schema.Column - function geomean(column: schema.Column): schema.Column - function max(column: schema.Column): schema.Column - function min(column: schema.Column): schema.Column - function stddev(column: schema.Column): schema.Column - function sum(column: schema.Column): schema.Column + function avg(column: schema.Column): schema.Column; + function count(column?: schema.Column): schema.Column; + function distinct(column: schema.Column): schema.Column; + function geomean(column: schema.Column): schema.Column; + function max(column: schema.Column): schema.Column; + function min(column: schema.Column): schema.Column; + function stddev(column: schema.Column): schema.Column; + function sum(column: schema.Column): schema.Column; } // module fn - } // module lf export = lf; diff --git a/types/lovefield/lovefield-tests.ts b/types/lovefield/lovefield-tests.ts index 3535775d1b..12ce92c843 100644 --- a/types/lovefield/lovefield-tests.ts +++ b/types/lovefield/lovefield-tests.ts @@ -1,6 +1,6 @@ import lf = require("lovefield"); function main(): void { - var schemaBuilder: lf.schema.Builder = lf.schema.create('todo', 1); + const schemaBuilder: lf.schema.Builder = lf.schema.create('todo', 1); schemaBuilder.createTable('Item'). addColumn('id', lf.Type.INTEGER). @@ -12,40 +12,38 @@ function main(): void { addNullable(['deadline']). addUnique('uq_description', ['description']); - var todoDb: lf.Database = null; - var itemSchema: lf.schema.Table = null; - var connectOptions: lf.schema.ConnectOptions = { + let todoDb: lf.Database = null; + let itemSchema: lf.schema.Table = null; + const connectOptions: lf.schema.ConnectOptions = { storeType: lf.schema.DataStoreType.MEMORY - } - schemaBuilder.connect(connectOptions).then( - function(db) { - todoDb = db; - itemSchema = db.getSchema().table('Item'); - var row = itemSchema.createRow({ - 'id': 1, - 'description': 'Get a cup of coffee', - 'deadline': new Date(), - 'done': false - }); - return db.insertOrReplace().into(itemSchema).values([row]).exec(); - }).then( - function() { - var column = itemSchema['done']; - return todoDb.select().from(itemSchema).where(column.eq(false)).exec(); - }).then( - function(results) { - results.forEach(function(row) { - document.body.textContent = - (row).description + ' before ' + (row).deadline; - }); + }; + schemaBuilder.connect(connectOptions).then((db) => { + todoDb = db; + itemSchema = db.getSchema().table('Item'); + let row = itemSchema.createRow({ + id: 1, + description: 'Get a cup of coffee', + deadline: new Date(), + done: false, + }); + return db.insertOrReplace().into(itemSchema).values([row]).exec(); + }).then(() => { + let column = itemSchema['done']; + return todoDb.select().from(itemSchema).where(column.eq(false)).exec(); + }).then((results) => { + results.forEach((row) => { + document.body.textContent = (row as any).description + ' before ' + + (row as any).deadline; + }); - return todoDb.delete().from(itemSchema); - }).then( - function() { - return todoDb.select(lf.fn.count()).from(itemSchema).exec(); - }).then(function() { - return todoDb.export(); - }); + return todoDb.delete().from(itemSchema); + }).then(() => { + return todoDb.select(lf.fn.count()).from(itemSchema).exec(); + }).then(() => { + return todoDb.export(); + }).then(() => { + todoDb.createTransaction().stats(); + }); } main(); diff --git a/types/lovefield/tslint.json b/types/lovefield/tslint.json new file mode 100644 index 0000000000..99735cffcf --- /dev/null +++ b/types/lovefield/tslint.json @@ -0,0 +1,12 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "export-just-namespace": false, + "interface-name": false, + "interface-over-type-literal": false, + "no-empty-interface": false, + "no-var": false, + "prefer-method-signature": false + } +} From b56aa308166c8449671d11752381277731fa2e47 Mon Sep 17 00:00:00 2001 From: Selkin Vitaly Date: Fri, 30 Jun 2017 01:25:22 +0300 Subject: [PATCH 0068/1618] bem-cn: ability to import interfaces --- types/bem-cn/bem-cn-tests.ts | 8 +++++ types/bem-cn/index.d.ts | 66 ++++++++++++++++++------------------ 2 files changed, 41 insertions(+), 33 deletions(-) diff --git a/types/bem-cn/bem-cn-tests.ts b/types/bem-cn/bem-cn-tests.ts index d57e138777..97b3bae8c5 100644 --- a/types/bem-cn/bem-cn-tests.ts +++ b/types/bem-cn/bem-cn-tests.ts @@ -1,4 +1,5 @@ import * as block from "bem-cn"; +import { Settings } from "bem-cn"; // expected 'block' block("block")(); @@ -44,3 +45,10 @@ block("block")("elem"); // expected 'block block--mod-value' block("block")({ mod: "value"}); + +// I can use bem-cn interfaces +const customSettings: Settings = { + ns: 'prefix' +}; + +block.setup(customSettings); diff --git a/types/bem-cn/index.d.ts b/types/bem-cn/index.d.ts index 5a78df4435..068298f0f7 100644 --- a/types/bem-cn/index.d.ts +++ b/types/bem-cn/index.d.ts @@ -3,39 +3,39 @@ // Definitions by: Vitaly Selkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -type StateFn = (states: { [key: string]: boolean }) => Inner; +type StateFn = (states: { [key: string]: boolean }) => BemCn.Inner; +declare function BemCn(name: string): BemCn.Inner; -interface Modifications { - [key: string]: (string | boolean); +declare namespace BemCn { + function reset(): void; + function setup(settings?: Settings): void; + + interface Modifications { + [key: string]: (string | boolean); + } + + interface Inner { + (elem: string | Modifications): Inner; + (elem: string, mods: Modifications): Inner; + (): string; + + mix(mixes: string | string[]): Inner; + has: StateFn; + state: StateFn; + is: StateFn; + toString(): string; + valueOf(): string; + split(separator: string, limit?: number): string[]; + } + + interface Settings { + ns?: string; + el?: string; + mod?: string; + modValue?: string; + classMap?: { [className: string]: string } | null; + } } -interface Block { - (name: string): Inner; - - reset(): void; - setup(settings?: Settings): void; -} - -interface Inner { - (elem: string | Modifications): Inner; - (elem: string, mods: Modifications): Inner; - (): string; - - mix(mixes: string | string[]): Inner; - has: StateFn; - state: StateFn; - is: StateFn; - toString(): string; - split(separator: string, limit?: number): string[]; -} - -interface Settings { - ns?: string; - el?: string; - mod?: string; - modValue?: string; - classMap?: { [className: string]: string } | null; -} - -declare const block: Block; -export = block; +export as namespace BemCn; +export = BemCn; From 8e5aae5f342e16b0d6ca5add1125a90c63dece67 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 29 Jun 2017 18:38:57 -0400 Subject: [PATCH 0069/1618] [semantic-ui-dimmer] Different weak-type workaround. --- types/semantic-ui-dimmer/global.d.ts | 68 +++++++++++++++--- .../semantic-ui-dimmer-tests.ts | 72 ++++++++++--------- 2 files changed, 97 insertions(+), 43 deletions(-) diff --git a/types/semantic-ui-dimmer/global.d.ts b/types/semantic-ui-dimmer/global.d.ts index 86ac3dc056..4b06951be9 100644 --- a/types/semantic-ui-dimmer/global.d.ts +++ b/types/semantic-ui-dimmer/global.d.ts @@ -95,18 +95,41 @@ declare namespace SemanticUI { */ (behavior: 'set disabled'): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): DimmerSettings[K]; - (behavior: 'setting', name: K, value: DimmerSettings[K]): JQuery; - (behavior: 'setting', value: DimmerSettings | object): JQuery; - (settings?: DimmerSettings | object): JQuery; + (behavior: 'setting', name: K, value?: undefined): DimmerSettings._Impl[K]; + (behavior: 'setting', name: K, value: DimmerSettings._Impl[K]): JQuery; + (behavior: 'setting', value: DimmerSettings): JQuery; + (settings?: DimmerSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/dimmer.html#/settings} */ - interface DimmerSettings extends Pick { } + type DimmerSettings = DimmerSettings.Param; namespace DimmerSettings { + type Param = (Pick<_Impl, 'opacity'> | + Pick<_Impl, 'variation'> | + Pick<_Impl, 'dimmerName'> | + Pick<_Impl, 'closable'> | + Pick<_Impl, 'on'> | + Pick<_Impl, 'useCSS'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'onShow'> | + Pick<_Impl, 'onHide'> | + Pick<_Impl, 'onChange'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'template'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; + interface _Impl { // region Behavior @@ -244,9 +267,13 @@ declare namespace SemanticUI { } namespace Dimmer { - interface DurationSettings extends Pick { } + type DurationSettings = DurationSettings.Param; namespace DurationSettings { + type Param = (Pick<_Impl, 'show'> | + Pick<_Impl, 'hide'>) & + Partial>; + interface _Impl { /** * @default 500 @@ -259,9 +286,14 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { + type Param = (Pick<_Impl, 'dimmable'> | + Pick<_Impl, 'dimmer'> | + Pick<_Impl, 'content'>) & + Partial>; + interface _Impl { /** * @default '.dimmable' @@ -278,17 +310,30 @@ declare namespace SemanticUI { } } - interface TemplateSettings extends Pick { } + type TemplateSettings = TemplateSettings.Param; namespace TemplateSettings { + type Param = (Pick<_Impl, 'dimmer'>) & + Partial>; + interface _Impl { dimmer(): JQuery; } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'dimmable'> | + Pick<_Impl, 'dimmed'> | + Pick<_Impl, 'disabled'> | + Pick<_Impl, 'pageDimmer'> | + Pick<_Impl, 'hide'> | + Pick<_Impl, 'show'> | + Pick<_Impl, 'transition'>) & + Partial>; + interface _Impl { /** * @default 'active' @@ -325,9 +370,12 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { + type Param = (Pick<_Impl, 'method'>) & + Partial>; + interface _Impl { /** * @default 'The method you called is not defined.' diff --git a/types/semantic-ui-dimmer/semantic-ui-dimmer-tests.ts b/types/semantic-ui-dimmer/semantic-ui-dimmer-tests.ts index 68aa418a7d..ef6701f8c1 100644 --- a/types/semantic-ui-dimmer/semantic-ui-dimmer-tests.ts +++ b/types/semantic-ui-dimmer/semantic-ui-dimmer-tests.ts @@ -1,5 +1,5 @@ function test_dimmer_settings() { - $.fn.dimmer.settings.error.method = 'method'; + $.fn.dimmer.settings.error!.method = 'method'; $.fn.dimmer.settings.namespace = 'namespace'; $.fn.dimmer.settings.name = 'name'; $.fn.dimmer.settings.silent = false; @@ -10,32 +10,33 @@ function test_dimmer_settings() { function test_dimmer() { const selector = '.ui.dimmer'; - $(selector).dimmer('add content', $()) === $(); - $(selector).dimmer('show') === $(); - $(selector).dimmer('hide') === $(); - $(selector).dimmer('toggle') === $(); - $(selector).dimmer('set opacity', 1) === $(); - $(selector).dimmer('create') === $(); - $(selector).dimmer('get duration') === 10; - $(selector).dimmer('get dimmer') === $(); - $(selector).dimmer('has dimmer') === true; - $(selector).dimmer('is active') === true; - $(selector).dimmer('is animating') === true; - $(selector).dimmer('is dimmer') === true; - $(selector).dimmer('is dimmable') === true; - $(selector).dimmer('is disabled') === true; - $(selector).dimmer('is enabled') === true; - $(selector).dimmer('is page') === true; - $(selector).dimmer('is page dimmer') === true; - $(selector).dimmer('set active') === $(); - $(selector).dimmer('set dimmable') === $(); - $(selector).dimmer('set dimmed') === $(); - $(selector).dimmer('set page dimmer') === $(); - $(selector).dimmer('set disabled') === $(); - $(selector).dimmer('destroy') === $(); - $(selector).dimmer('setting', 'debug', undefined) === false; - $(selector).dimmer('setting', 'debug') === false; - $(selector).dimmer('setting', 'debug', true) === $(); + $(selector).dimmer('add content', $()); // $ExpectType JQuery + $(selector).dimmer('show'); // $ExpectType JQuery + $(selector).dimmer('hide'); // $ExpectType JQuery + $(selector).dimmer('toggle'); // $ExpectType JQuery + $(selector).dimmer('set opacity', 1); // $ExpectType JQuery + $(selector).dimmer('create'); // $ExpectType JQuery + $(selector).dimmer('get duration'); // $ExpectType number + $(selector).dimmer('get dimmer'); // $ExpectType JQuery + $(selector).dimmer('has dimmer'); // $ExpectType boolean + $(selector).dimmer('is active'); // $ExpectType boolean + $(selector).dimmer('is animating'); // $ExpectType boolean + $(selector).dimmer('is dimmer'); // $ExpectType boolean + $(selector).dimmer('is dimmable'); // $ExpectType boolean + $(selector).dimmer('is disabled'); // $ExpectType boolean + $(selector).dimmer('is enabled'); // $ExpectType boolean + $(selector).dimmer('is page'); // $ExpectType boolean + $(selector).dimmer('is page dimmer'); // $ExpectType boolean + $(selector).dimmer('set active'); // $ExpectType JQuery + $(selector).dimmer('set dimmable'); // $ExpectType JQuery + $(selector).dimmer('set dimmed'); // $ExpectType JQuery + $(selector).dimmer('set page dimmer'); // $ExpectType JQuery + $(selector).dimmer('set disabled'); // $ExpectType JQuery + $(selector).dimmer('destroy'); // $ExpectType JQuery + $(selector).dimmer('setting', 'debug', undefined); // $ExpectType boolean + $(selector).dimmer('setting', 'debug'); // $ExpectType boolean + $(selector).dimmer('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).dimmer('setting', { namespace: 'namespace', name: 'name', @@ -43,7 +44,8 @@ function test_dimmer() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).dimmer({ opacity: 1, variation: 'variation', @@ -57,13 +59,13 @@ function test_dimmer() { }, transition: 'fade', onShow() { - this === $(); + this; // $ExpectType JQuery }, onHide() { - this === $(); + this; // $ExpectType JQuery }, onChange() { - this === $(); + this; // $ExpectType JQuery }, selector: { dimmable: '.dimmable', @@ -88,12 +90,16 @@ function test_dimmer() { error: { method: 'method' } - }) === $(); - $(selector).dimmer() === $(); + }); + $(selector).dimmer(); // $ExpectType JQuery + + $(selector).dimmer('foo'); // $ExpectError + $(selector).dimmer({ foo: 'bar' }); // $ExpectError } import dimmer = require('semantic-ui-dimmer'); function test_module() { + dimmer; // $ExpectType Dimmer $.fn.dimmer = dimmer; } From 0c01f43b08e353da2b43211a8a71ddff98bc8407 Mon Sep 17 00:00:00 2001 From: Jack Moore Date: Fri, 30 Jun 2017 00:28:37 -0500 Subject: [PATCH 0070/1618] Updated yargs command to take array of strings --- types/yargs/index.d.ts | 12 ++++++------ types/yargs/yargs-tests.ts | 6 ++++++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/types/yargs/index.d.ts b/types/yargs/index.d.ts index faf26b3fa8..fe8f4ea6c2 100644 --- a/types/yargs/index.d.ts +++ b/types/yargs/index.d.ts @@ -87,12 +87,12 @@ declare namespace yargs { 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, builder: (args: Argv) => Argv): Argv; - command(command: string, description: string, builder: { [optionName: string]: Options }): Argv; - command(command: string, description: string, builder: { [optionName: string]: Options }, handler: (args: Arguments) => void): Argv; - command(command: string, description: string, builder: (args: Argv) => Argv, handler: (args: Arguments) => void): Argv; - command(command: string, description: string, module: CommandModule): Argv; + command(command: string | string[], description: string): Argv; + command(command: string | string[], description: string, builder: (args: Argv) => Argv): Argv; + command(command: string | string[], description: string, builder: { [optionName: string]: Options }): Argv; + command(command: string | string[], description: string, builder: { [optionName: string]: Options }, handler: (args: Arguments) => void): Argv; + command(command: string | string[], description: string, builder: (args: Argv) => Argv, handler: (args: Arguments) => void): Argv; + command(command: string | string[], description: string, module: CommandModule): Argv; command(module: CommandModule): Argv; commandDir(dir: string, opts?: RequireDirectoryOptions): Argv; diff --git a/types/yargs/yargs-tests.ts b/types/yargs/yargs-tests.ts index 2c0756d427..3773d03ea5 100644 --- a/types/yargs/yargs-tests.ts +++ b/types/yargs/yargs-tests.ts @@ -620,3 +620,9 @@ function Argv$conflicts() { }) .argv; } + +function Argv$commandArray() { + let ya = yargs + .command(['commandName', 'commandAlias'], 'command description') + .argv; +} From 47dc2f3fb561fd59c063abb1af14589dbb51a257 Mon Sep 17 00:00:00 2001 From: Jack Moore Date: Fri, 30 Jun 2017 00:49:17 -0500 Subject: [PATCH 0071/1618] Added isDeprecated to GraphQLEnumValue --- types/graphql/type/definition.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index cf077ad5ba..eb64172f40 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -456,6 +456,7 @@ export interface GraphQLEnumValueConfig { export interface GraphQLEnumValue { name: string; description: string; + isDeprecated?: boolean; deprecationReason: string; value: any; } From bda681f3dc061bf8f32b330ad730466da7c3df3d Mon Sep 17 00:00:00 2001 From: sixinli Date: Fri, 30 Jun 2017 02:17:56 -0400 Subject: [PATCH 0072/1618] add destroy() to keypress typing this function exist in the api mentioned in https://dmauro.github.io/Keypress/ --- types/keypress/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/keypress/index.d.ts b/types/keypress/index.d.ts index edb05ee583..122095cd09 100644 --- a/types/keypress/index.d.ts +++ b/types/keypress/index.d.ts @@ -46,6 +46,7 @@ declare namespace Keypress { unregister_many(combos: Combo[]): void; unregister_many(keys: string[]): void; get_registered_combos(): Combo[]; + destroy(): void; reset(): void; listen(): void; stop_listening(): void; From 0dd15bce72bdcbcafc1315a4d3690a75c32ef22e Mon Sep 17 00:00:00 2001 From: Andrey Kyrdyumov Date: Fri, 30 Jun 2017 12:43:51 +0600 Subject: [PATCH 0073/1618] Make SnapSVG accessible from WebPack I have to add export = Snap to make project accessible from projects which using webpack, mina object was not accessibly now, but in runtime it was still perfectly fine to have it in the code. Thus I extract mina package as separate global dependency. For code which use SnapSVG as global dependency this will work as earlier, but for those who want to use SnapSVG with WebPack it will reflect how mina available after importing SnapSVG --- types/mina/index.d.ts | 50 +++++++++++++++++++++++++++++++++++++ types/mina/tsconfig.json | 21 ++++++++++++++++ types/mina/tslint.json | 1 + types/snapsvg/index.d.ts | 50 +++---------------------------------- types/snapsvg/tsconfig.json | 2 +- 5 files changed, 77 insertions(+), 47 deletions(-) create mode 100644 types/mina/index.d.ts create mode 100644 types/mina/tsconfig.json create mode 100644 types/mina/tslint.json diff --git a/types/mina/index.d.ts b/types/mina/index.d.ts new file mode 100644 index 0000000000..7a2d37e9cb --- /dev/null +++ b/types/mina/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for mina Snap-SVG 0.4.1 +// Project: https://github.com/adobe-webplatform/Snap.svg +// Definitions by: Lars Klein , Mattanja Kern , Andrey Kurdyumov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function mina(a:number, A:number, b:number, B:number, get:Function, set:Function, easing?:(num:number)=>number):mina.AnimationDescriptor; +declare namespace mina { + export interface MinaAnimation { + id: string; + duration: Function; + easing: Function; + speed: Function; + status: Function; + stop: Function; + } + + export interface AnimationDescriptor { + id: string; + start: number; + end: number; + b: number; + s: number; + dur: number; + spd: number; + get(): number; + set(slave: number): number; + easing(input: number): number; + status(): number; + status(newStatus: number): void; + speed(): number; + speed(newSpeed: number): void; + duration(): number; + duration(newDuration: number): void; + stop(): void; + pause(): void; + resume(): void; + update(): void; + } + + export function backin(n:number):number; + export function backout(n:number):number; + export function bounce(n:number):number; + export function easein(n:number):number; + export function easeinout(n:number):number; + export function easeout(n:number):number; + export function elastic(n:number):number; + export function getById(id:string):AnimationDescriptor; + export function linear(n:number):number; + export function time():number; +} diff --git a/types/mina/tsconfig.json b/types/mina/tsconfig.json new file mode 100644 index 0000000000..a2cbd4e379 --- /dev/null +++ b/types/mina/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} diff --git a/types/mina/tslint.json b/types/mina/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mina/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/snapsvg/index.d.ts b/types/snapsvg/index.d.ts index b58c938d74..ff0e9d09a9 100644 --- a/types/snapsvg/index.d.ts +++ b/types/snapsvg/index.d.ts @@ -1,53 +1,11 @@ // Type definitions for Snap-SVG 0.4.1 // Project: https://github.com/adobe-webplatform/Snap.svg -// Definitions by: Lars Klein , Mattanja Kern +// Definitions by: Lars Klein , Mattanja Kern , Andrey Kurdyumov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// -declare function mina(a:number, A:number, b:number, B:number, get:Function, set:Function, easing?:(num:number)=>number):mina.AnimationDescriptor; -declare namespace mina { - export interface MinaAnimation { - id: string; - duration: Function; - easing: Function; - speed: Function; - status: Function; - stop: Function; - } - - export interface AnimationDescriptor { - id: string; - start: number; - end: number; - b: number; - s: number; - dur: number; - spd: number; - get(): number; - set(slave: number): number; - easing(input: number): number; - status(): number; - status(newStatus: number): void; - speed(): number; - speed(newSpeed: number): void; - duration(): number; - duration(newDuration: number): void; - stop(): void; - pause(): void; - resume(): void; - update(): void; - } - - export function backin(n:number):number; - export function backout(n:number):number; - export function bounce(n:number):number; - export function easein(n:number):number; - export function easeinout(n:number):number; - export function easeout(n:number):number; - export function elastic(n:number):number; - export function getById(id:string):AnimationDescriptor; - export function linear(n:number):number; - export function time():number; -} +export = Snap; +export as namespace Snap; declare function Snap(width:number|string,height:number|string):Snap.Paper; declare function Snap(query:string):Snap.Paper; diff --git a/types/snapsvg/tsconfig.json b/types/snapsvg/tsconfig.json index 9e42ed48a9..0f4b962e7f 100644 --- a/types/snapsvg/tsconfig.json +++ b/types/snapsvg/tsconfig.json @@ -22,4 +22,4 @@ "test/2.ts", "test/3.ts" ] -} \ No newline at end of file +} From da620a35a358dfdbe28bd7119609a748db87d40e Mon Sep 17 00:00:00 2001 From: atothek1 Date: Fri, 30 Jun 2017 08:45:06 +0200 Subject: [PATCH 0074/1618] Update index.d.ts Fixing compile errors that needs a a value for the generic State property in React.Component --- types/enzyme/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 2a7142d9b3..01ecfa90d8 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -15,7 +15,7 @@ import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttr export type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; -export class ElementClass extends Component { +export class ElementClass extends Component { } /* These are purposefully stripped down versions of React.ComponentClass and React.StatelessComponent. @@ -23,7 +23,7 @@ export class ElementClass extends Component { * all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics */ export interface ComponentClass { - new (props?: Props, context?: any): Component; + new (props?: Props, context?: any): Component; } export type StatelessComponent = (props: Props, context?: any) => JSX.Element; From 422bcbc894989de746f542e0e60e961af0701a53 Mon Sep 17 00:00:00 2001 From: Andrey Kyrdyumov Date: Fri, 30 Jun 2017 13:14:56 +0600 Subject: [PATCH 0075/1618] Fix lint warning for mina --- types/mina/index.d.ts | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/types/mina/index.d.ts b/types/mina/index.d.ts index 7a2d37e9cb..1fb55924c0 100644 --- a/types/mina/index.d.ts +++ b/types/mina/index.d.ts @@ -1,20 +1,20 @@ -// Type definitions for mina Snap-SVG 0.4.1 +// Type definitions for mina Snap-SVG 0.4 // Project: https://github.com/adobe-webplatform/Snap.svg // Definitions by: Lars Klein , Mattanja Kern , Andrey Kurdyumov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function mina(a:number, A:number, b:number, B:number, get:Function, set:Function, easing?:(num:number)=>number):mina.AnimationDescriptor; +declare function mina(a: number, A: number, b: number, B: number, get: () => number, set: (time: number) => void, easing?: (num: number) => number): mina.AnimationDescriptor; declare namespace mina { - export interface MinaAnimation { + interface MinaAnimation { id: string; - duration: Function; - easing: Function; - speed: Function; - status: Function; - stop: Function; + duration(): number; + easing(): number; + speed(): number; + status(): number; + stop(): void; } - export interface AnimationDescriptor { + interface AnimationDescriptor { id: string; start: number; end: number; @@ -37,14 +37,14 @@ declare namespace mina { update(): void; } - export function backin(n:number):number; - export function backout(n:number):number; - export function bounce(n:number):number; - export function easein(n:number):number; - export function easeinout(n:number):number; - export function easeout(n:number):number; - export function elastic(n:number):number; - export function getById(id:string):AnimationDescriptor; - export function linear(n:number):number; - export function time():number; + function backin(n: number): number; + function backout(n: number): number; + function bounce(n: number): number; + function easein(n: number): number; + function easeinout(n: number): number; + function easeout(n: number): number; + function elastic(n: number): number; + function getById(id: string): AnimationDescriptor; + function linear(n: number): number; + function time(): number; } From 0be3316701cd58db2c5c30f23837ea8f6e5dc675 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 10:40:23 +0200 Subject: [PATCH 0076/1618] Type Definiton for Frozen Mountain WebSync 3 --- types/fm-websync/fm-websync-tests.ts | 19 ++ types/fm-websync/index.d.ts | 484 +++++++++++++++++++++++++++ types/fm-websync/package.json | 11 + types/fm-websync/tsconfig.json | 19 ++ types/fm-websync/tslint.json | 1 + 5 files changed, 534 insertions(+) create mode 100644 types/fm-websync/fm-websync-tests.ts create mode 100644 types/fm-websync/index.d.ts create mode 100644 types/fm-websync/package.json create mode 100644 types/fm-websync/tsconfig.json create mode 100644 types/fm-websync/tslint.json diff --git a/types/fm-websync/fm-websync-tests.ts b/types/fm-websync/fm-websync-tests.ts new file mode 100644 index 0000000000..aeb665e5ae --- /dev/null +++ b/types/fm-websync/fm-websync-tests.ts @@ -0,0 +1,19 @@ +const client = fm.websync.client.initialize( { + requestUrl: "", + onSuccess: args => console.log( `Init success: {args.clientId}` ), + onFailure: args => console.log( `Init failure: {args.clientId}` ), + onComplete: args => console.log( `Init complete: {args.clientId}` ) +} ); + +client.subscribe( { + channel: "/my/channel", + onReceive: args => console.log( `Receive data: {args.data}` ), + onFailure: args => console.log( `Subscribe failure: {args.data}` ), + onComplete: args => console.log( `Subscribe complete` ) +} ); + +client.disconnect( { + onSuccess: args => console.log( `Disconnect success: {args.clientId}` ), + onFailure: args => console.log( `Disconnect failure: {args.clientId}` ), + onComplete: args => console.log( `Disconnect complete: {args.clientId}` ) +} ); \ No newline at end of file diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts new file mode 100644 index 0000000000..ae3677b986 --- /dev/null +++ b/types/fm-websync/index.d.ts @@ -0,0 +1,484 @@ +// Type definitions for fm-websync 3 +// Project: https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: Markus Mauch +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace fm +{ + export namespace websync + { + interface initializeConfig + { + /** + * If set to true, an asynchronous disconnect request will be launched when the page unloads. If set to false, no automatic disconnection will be attempted. If set to an object, then a disconnect request will be launched when the page unloads using the object as the disconnect configuration. (See disconnectConfig for details.) Note that automatic disconnects are a best-effort. The only way to guarantee success is to execute the disconnect synchronously and target a request URL on the same domain as the page ({ sync: true, requestUrl: '...relative path.../request.ashx' }). Defaults to false. + */ + autoDisconnect?: boolean; + + /** + * The amount of time in milliseconds to add to the delay between each reconnect attempt in the event of network failure. Defaults to 3000 (3 seconds). + */ + + backoffInterval?: number; + + /** + * The URL of the HTML frame to be used with HTML5 postMessage for cross-domain environments. Must have the same domain as requestUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server ClientHandler registered in web.config with "frame" added to the query. + */ + clientFrameUrl?: string; + + /** + * The domain key to send with each request. If using WebSync On-Demand, this should be set to the public or private API key specified in the Frozen Mountain Portal. If using WebSync Server, this should be used only if grouping connections. Defaults to "11111111-1111-1111-1111-111111111111". + */ + key?: string; + + /** + * The callback to invoke after onSuccess or onFailure. See initializeCompleteArgs for callback argument details. + */ + onComplete?: ( args: initializeCompleteArgs ) => void; + + /** + * The callback to invoke if the initialize fails. Defaults to an alert of the error. See initializeFailureArgs for callback argument details. + */ + onFailure?: ( args: initializeFailureArgs ) => void; + + /** + * The callback to invoke if the initialize succeeds. See initializeSuccessArgs for callback argument details. + */ + onSuccess?: ( args: initializeSuccessArgs ) => void; + + /** + * Whether or not to suppress the alerting of a failure if the client is already initialized. + */ + quiet?: boolean; + + /** + * The URL of the WebSync request handler. This URL typically ends with request.ashx. Must have the same domain as clientFrameUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server RequestHandler registered in web.config. + */ + requestUrl?: string; + + /** + * The number of times to retry a request in the event of network failure before considering it failed and invoking the corresponding OnFailure callback. Defaults to 3. + */ + retries?: number; + + /** + * The URLs to use for streaming connections. Three properties are available: + * + * requestUrl: string + * Same as the root requestUrl parameter, but used for streaming connections. Must have the same domain as stream.clientFrameUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the streamHost web.config attribute, if specified) and the path to the WebSync Server RequestHandler registered in web.config. + * clientFrameUrl: string + * Same as the root clientFrameUrl parameter, but used for streaming connections. Must have the same domain as stream.requestUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the streamHost web.config attribute, if specified) and the path to the WebSync Server ClientHandler registered in web.config with "frame" added to the query. + * timeout: number + * Same as the root timeout parameter, but used for streaming connections. Defaults to the root timeout + 25000 (25 seconds). + */ + stream? : any; + + /** + * The number of milliseconds to wait for a standard request to return a response before it is cancelled and a new attempt is made. Defaults to 15000 (15 seconds). + */ + timeout?: number; + + /** + * The token sent with every client request identifying it for query-based load balancing. Defaults to the current timestamp. + */ + + token?: string; + + /** + * An object specifying URLs to be used for specific client methods. Overrides initializeConfig.requestUrl for the specified method type, but can be overridden by the requestUrl specified in individual method configurations. + * + * connect: string + * The URL to use for all client.connect requests. + * + * bind: string + * The URL to use for all client.bind requests. + * + * unbind: string + * The URL to use for all client.unbind requests. + * + * subscribe: string + * The URL to use for all client.subscribe requests. + * + * unsubscribe: string + * The URL to use for all client.unsubscribe requests. + * + * publish: string + * The URL to use for all client.publish requests. + * + * disconnect: string + * The URL to use for all client.disconnect requests. + */ + urls?: any; + } + + interface baseArgs + {} + + interface baseRequestConfig + { + /** + * Extra meta data to associate with the request/response. + */ + meta?: any; + + /** + * The URL of the proxy to use for this request. + */ + requestUrl?: string; + + /** + * Whether to ignore errors when parsing the server response. If true, any errors thrown while parsing the JSON response received from the server will be ignored. Defaults to false. + */ + suppressErrors?: boolean; + + /** + * Whether the request should be executed asynchronously. If true, the request will be executed synchronously if supported by the browser; otherwise, it will be executed asynchronously. All browsers support synchronous requests if the request URL is the same domain as the page. Synchronous requests are not supported in IE6 and IE7 for cross-domain environments. Defaults to false. + */ + sync?: boolean; + } + + interface connectConfig extends baseRequestConfig + { + /** + * The callback to invoke after onSuccess or onFailure. See connectCompleteArgs for callback argument details. + */ + onComplete?: ( args: connectCompleteArgs ) => void; + + /** + * The callback to invoke if the connect fails. Defaults to an alert of the error. See connectFailureArgs for callback argument details. + */ + onFailure?: ( args: connectFailureArgs ) => void; + + /** + * The callback to invoke if the streaming connection fails. See streamFailureArgs for callback argument details. + * This method will be invoked if (a) the connection was lost, automatic retries succeeded, but the client had idled on the server (and so needs to reconnect), or (b) the connection was lost and automatic retries failed. In the former case, willReconnect is true, and in the latter case, willReconnect is false. + * See client for more details on these two scenarios. + * If willReconnect is true, the client will automatically reconnect. If the reconnect succeeds, the callback specified by onSuccess will be invoked with isReconnect set to true. If the reconnect fails, the callback specified by onFailure will be invoked with isReconnect set to false. + * With the exception of UI updates, invocations of this callback with willReconnect set to true can be ignored. + */ + onStreamFailure?: ( args: streamFailureArgs ) => void; + + /** + * The callback to invoke if the connect succeeds. See connectSuccessArgs for callback argument details. + */ + onSuccess?: ( args: connectSuccessArgs ) => void; + + /** + * The callback to invoke when a message is received on a channel that has no local callback specified to handle it. See receiveArgs for callback argument details. + * This can occur if (a) a client is manually subscribed to a channel by the server or (b) a client subscribed to a channel and then manually removed the local callback using client.unsetHandler. + */ + onUnhandledReceive?: Function; + + /** + * Whether to always attempt to stay connected in the event of network failure. If true, the client will continually reconnect, even after exhausting the specified number of retries specified by initializeConfig.retries. If false, the client will stop reconnecting if all retry attempts fail. + */ + stayConnected?: boolean; + } + + interface subscribeConfig extends baseRequestConfig + { + /** + * The channel to which the client should be subscribed. Must start with a forward slash (/). Overrides channels. + */ + channel?: String; + + /** + * The channels to which the client should be subscribed. Each must start with a forward slash (/). Overrides channel. + */ + channels?: String[]; + + /** + * The callback to invoke after onSuccess or onFailure. See subscribeCompleteArgs for callback argument details. + */ + onComplete?: ( args: subscribeCompleteArgs ) => void; + + /** + * (OptionalThe callback to invoke if the subscribe fails. See subscribeFailureArgs for callback argument details. + */ + onFailure?: ( args: subscribeFailureArgs ) => void; + + /** + * The callback to invoke when data is received on the channel(s). See receiveArgs for callback argument details. + */ + onReceive?: ( args: receiveArgs ) => void; + + /** + * Subscribers extension. The callback to invoke when a subscribers change notification is received (i.e. when a client subscribes to or unsubscribes from the channel(s)). + * The current subscribe request will trigger this callback. See subscribersChangeArgs for callback argument details. + */ + onSubscribersChange?: ( args: subscribersChangeArgs ) => void; + + /** + * The callback to invoke if the subscribe succeeds. See subscribeSuccessArgs for callback argument details. + */ + onSuccess?: ( args: subscribeSuccessArgs ) => void; + } + + interface baseCompleteArgs extends baseResponseArgs + { + } + + interface initializeCompleteArgs extends baseArgs + { + } + + interface initializeFailureArgs extends baseArgs + { + } + + interface initializeSuccessArgs extends baseArgs + { + } + + interface subscribeSuccessArgs extends baseSuccessArgs + { + /** + * The channel to which the client was subscribed. Must start with a forward slash (/). + */ + channel: string; + + /** + * The channels to which the client was subscribed. Each must start with a forward slash (/). + */ + channels: string[]; + + /** + * Whether the call to client.subscribe was triggered by a reconnection after network failure. + */ + isResubscribe: boolean; + + /** + * Subscribers extension. The active subscribed clients on the just-subscribed channel(s). + */ + subscribedClients: fm.websync.subscribedClient[]; + } + + interface subscribeCompleteArgs extends baseCompleteArgs + { + /** + * Whether the call to client.subscribe was triggered by a reconnection after network failure. + */ + isResubscribe: boolean; + } + + interface subscribeFailureArgs extends baseFailureArgs + { + /** + * Whether the call to client.subscribe was triggered by a reconnection after network failure. + */ + isResubscribe: boolean; + } + + interface baseFailureArgs extends baseResponseArgs + { + /** + * The error generated while completing the request. + */ + error: string; + } + + interface baseResponseArgs extends baseArgs + { + /** + * The singleton client. + */ + client: fm.websync.client; + + /** + * The ID of the singleton client. + */ + clientId: string; + + /** + * Extra meta data associated with the request/response. + */ + meta: any; + + /** + * The date/time the message was processed on the server. + */ + timestamp: Date; + } + + interface baseSuccessArgs extends baseResponseArgs + { + + } + + interface connectSuccessArgs extends baseResponseArgs + { + /** + * Whether the call to client.connect was triggered by a reconnection after network failure. + */ + isReconnect: boolean; + } + + interface connectFailureArgs extends baseResponseArgs + { + /** + * The error generated while completing the request. + */ + error: string; + + /** + * Whether the call to client.connect was triggered by a reconnection after network failure. + */ + isReconnect: boolean; + + /** + * Whether or not to reconnect automatically after this callback has finished execution. + */ + reconnect: boolean; + } + + interface streamFailureArgs extends baseResponseArgs + { + /** + * The error generated while completing the request. + */ + error: string; + + /** + * Whether the client will automatically reconnect after the callback returns. + */ + willReconnect: boolean; + } + + interface connectCompleteArgs extends baseResponseArgs + { + /** + * Whether the call to client.connect was triggered by a reconnection after network failure. + */ + isReconnect: boolean; + } + + interface receiveArgs extends baseResponseArgs + { + /** + * The channel over which the data was published. + */ + channel: string; + + /** + * The published data. + */ + data: any; + + /** + * Details about the client publishing the data. + */ + publishingClient: fm.websync.publishingClient; + } + + interface subscribersChangeArgs extends baseSuccessArgs + { + /** + * The details of the change that occurred. + */ + change?: fm.websync.subscribersChange + + /** + * The channel on which the change occurred. + */ + channel?: string; + } + + interface publishingClient + { + /** + * The publishing client's bound records. + */ + boundRecords: any; + + /** + * The publishing client's unique identifier. + */ + id: string; + } + + interface subscribersChange + { + /** + * The clients who subscribed to or unsubscribed from the channel. + */ + clients : fm.websync.subscribedClient[]; + + /** + * The type of the change, either "subscribe" or "unsubscribe". + */ + type: string; + } + + interface subscribedClient + { + /** + * The subscribed client's bound records. + */ + boundRecords: any; + + /** + * The subscribed client's unique identifier. + */ + id: string; + } + + interface disconnectConfig extends baseRequestConfig + { + /** + * The callback to invoke after onSuccess or onFailure. See disconnectCompleteArgs for callback argument details. + */ + onComplete: ( args: disconnectCompleteArgs ) => void; + + /** + * The callback to invoke if the disconnect fails. See disconnectFailureArgs for callback argument details. + */ + onFailure: ( args: disconnectFailureArgs ) => void; + + /** + * The callback to invoke if the disconnect succeeds. See disconnectSuccessArgs for callback argument details. + */ + onSuccess: ( args: disconnectSuccessArgs ) => void; + } + + interface disconnectCompleteArgs extends baseCompleteArgs + { + } + + interface disconnectFailureArgs extends baseFailureArgs + { + } + + interface disconnectSuccessArgs extends baseSuccessArgs + { + } + + export class client + { + /** + * Sets up and maintains a streaming connection to the server. + * While this method will typically run asychronously, the WebSync client is designed to be used without (much) consideration for its asynchronous nature. To that end, any calls to methods that require an active connection, like bind, subscribe and publish, will be queued automatically and executed once this method has completed successfully. + * + * @param connectConfig + */ + public connect( config: connectConfig ): client; + + /** + * + * @param config Takes down a streaming connection to the server and unsubscribes the client. + * After the disconnect completes successfully, any further calls to methods that require an active connection, like bind, subscribe and publish, will be queued automatically and executed only if/when the client reconnects. + */ + public disconnect( config: disconnectConfig ): client; + + /** + * Initializes the client according to the specified configuration. + * This method must always be called first. While is always executes synchronously, callbacks are allowed for the purposes of method chaining. + */ + public static initialize( config: initializeConfig ): client; + + /** + * Subscribes the client to receive messages on one or more channels. + * When the subscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the subscribed channel(s), including any modifications made on the server. + */ + public subscribe( config: subscribeConfig ): client; + } + } +} diff --git a/types/fm-websync/package.json b/types/fm-websync/package.json new file mode 100644 index 0000000000..6843239469 --- /dev/null +++ b/types/fm-websync/package.json @@ -0,0 +1,11 @@ +{ + "name": "fm-websync", + "version": "1.0.0", + "description": "Type definitions for Frozen Mountain WebSync 3", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "Markus Mauch", + "license": "ISC" +} diff --git a/types/fm-websync/tsconfig.json b/types/fm-websync/tsconfig.json new file mode 100644 index 0000000000..76193744be --- /dev/null +++ b/types/fm-websync/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "none", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fm-websync-tests.ts" + ] +} diff --git a/types/fm-websync/tslint.json b/types/fm-websync/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fm-websync/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d2dc473186e861ff7461a62a94ee09fc6bf992d2 Mon Sep 17 00:00:00 2001 From: taoqiufeng Date: Fri, 30 Jun 2017 16:53:15 +0800 Subject: [PATCH 0077/1618] upgrade plotly.js version to 1.28 --- types/plotly.js/index.d.ts | 655 ++++++++++++++++------------- types/plotly.js/plotly.js-tests.ts | 352 +++++++++++++++- 2 files changed, 709 insertions(+), 298 deletions(-) diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 04de340c22..82b7e622da 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -1,298 +1,373 @@ -// Type definitions for plotly.js 1.27 +// Type definitions for plotly.js 1.28 // Project: https://plot.ly/javascript/ -// Definitions by: Chris Gervang , Martin Duparc +// Definitions by: Chris Gervang , Martin Duparc , taoqf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -declare namespace Plots { - interface StaticPlots { - resize(root: Plotly.Root): void; - } +/// +export as namespace Plotly; + +export interface StaticPlots { + resize(root: Root): void; } -declare namespace Plotly { - type Root = string | HTMLElement; - - interface PlotlyStatic { - Plots: Plots.StaticPlots; - newPlot(root: Root, data: Array>, layout?: Partial, config?: Partial): void; - relayout(root: Root, layout: Partial): void; - redraw(root: Root): void; - purge(root: Root): void; - d3: any; - } - - // Layout - - interface Layout { - autosize: boolean; - showlegend: boolean; - xaxis: Partial; - yaxis: Partial; - margin: Partial; - height: number; - width: number; - hovermode: "closest" | "x" | "y" | false; - 'xaxis.range': [Datum, Datum]; - 'yaxis.range': [Datum, Datum]; - 'yaxis.type': AxisType; - 'xaxis.type': AxisType; - 'xaxis.autorange': boolean; - 'yaxis.autorange': boolean; - shapes: Array>; - legend: Partial; - } - - interface Legend { - traceorder: "grouped" | "normal" | "reversed"; - x: number; - y: number; - font: Partial; - bgcolor: string; - bordercolor: string; - borderwidth: number; - orientation: "v" | "h"; - tracegroupgap: number; - xanchor: 'auto' | 'left' | 'center' | 'right'; - yanchor: 'auto' | 'top' | 'middle' | 'bottom'; - } - - type AxisType = "date" | "log" | "linear"; - - interface Axis { - title: string; - showgrid: boolean; - fixedrange: boolean; - rangemode: "tozero" | 'normal' | 'nonnegative'; - type: AxisType; - tickformat: string; - hoverformat: string; - rangeslider: Partial; - rangeselector: Partial; - range: [Datum, Datum]; - showticklabels: boolean; - autotick: boolean; - zeroline: boolean; - autorange: boolean | 'reversed'; - } - - interface ShapeLine { - color: string; - width: number; - dash: Dash; - } - - interface Shape { - visible: boolean; - layer: 'below' | 'above'; - type: 'rect' | 'circle' | 'line' | 'path'; - path: string; - // x-reference is assigned to the x-values - xref: 'x' | 'paper'; - // y-reference is assigned to the plot paper [0,1] - yref: 'paper' | 'y'; - x0: Datum; - y0: Datum; - x1: Datum; - y1: Datum; - fillcolor: string; - opacity: number; - line: Partial; - } - - interface Margin { - t: number; - b: number; - l: number; - r: number; - } - - type ModeBarButtons = 'lasso2d' | 'select2d' | 'sendDataToCloud' | 'autoScale2d' | - 'zoom2d' | 'pan2d' | 'zoomIn2d' | 'zoomOut2d' | 'autoScale2d' | 'resetScale2d' | - 'hoverClosestCartesian' | 'hoverCompareCartesian' | 'zoom3d' | 'pan3d' | 'orbitRotation' | - 'tableRotation' | 'resetCameraDefault3d' | 'resetCameraLastSave3d' | 'hoverClosest3d' | - 'zoomInGeo' | 'zoomOutGeo' | 'resetGeo' | 'hoverClosestGeo' | 'hoverClosestGl2d' | - 'hoverClosestPie' | 'toggleHover' | 'resetViews'; - - // Data - - type Datum = string | number | Date; - - type Dash = 'solid' | 'dot' | 'dash' | 'longdash' | 'dashdot' | 'longdashdot'; - - type Data = Partial | Partial; - - // Bar - interface BarData { - type: 'bar'; - x: Datum[]; - y: Datum[]; - } - - // Scatter - interface ScatterData { - type: 'scatter' | 'scattergl'; - x: Datum[]; - y: Datum[]; - text: string | string[]; - line: Partial; - marker: Partial; - mode: "lines" | "markers" | "text" | "lines+markers" | "text+markers" | "text+lines" | "text+lines+markers" | "none"; - hoveron: "points" | "fills"; - hoverinfo: "text"; - fill: 'none' | 'tozeroy' | 'tozerox' | 'tonexty' | 'tonextx' | 'toself' | 'tonext'; - fillcolor: string; - legendgroup: string; - name: string; - connectgaps: boolean; - } - - interface ScatterMarker { - symbol: string | string[]; // Drawing.symbolList - color: string | string[]; - opacity: number | number[]; - size: number | number[]; - maxdisplayed: number; - sizeref: number; - sizemin: number; - sizemode: "diameter" | "area"; - showscale: boolean; - line: {}; // TODO - colorbar: {}; // TODO - } - - interface ScatterLine { - color: string; - width: number; - dash: Dash; - shape: 'linear' | 'spline' | 'hv' | 'vh' | 'hvh' | 'vhv'; - smoothing: number; - simplify: boolean; - } - - interface Font { - family: string; - size: number; - color: string; - } - - interface Config { - // no interactivity, for export or image generation - staticPlot: boolean; - - // we can edit titles, move annotations, etc - editable: boolean; - - // DO autosize once regardless of layout.autosize - // (use default width or height values otherwise) - autosizable: boolean; - - // set the length of the undo/redo queue - queueLength: number; - - // if we DO autosize, do we fill the container or the screen? - fillFrame: boolean; - - // if we DO autosize, set the frame margins in percents of plot size - frameMargins: number; - - // mousewheel or two-finger scroll zooms the plot - scrollZoom: boolean; - - // double click interaction (false, 'reset', 'autosize' or 'reset+autosize') - doubleClick: 'reset+autosize' | 'reset' | 'autosize' | false; - - // new users see some hints about interactivity - showTips: boolean; - - // link to open this plot in plotly - showLink: boolean; - - // if we show a link, does it contain data or just link to a plotly file? - sendData: boolean; - - // text appearing in the sendData link - linkText: string; - - // false or function adding source(s) to linkText - showSources: boolean; - - // display the mode bar (true, false, or 'hover') - displayModeBar: 'hover' | boolean; - - // remove mode bar button by name - // (see ./components/modebar/buttons.js for the list of names) - modeBarButtonsToRemove: ModeBarButtons[]; - - // add mode bar button using config objects - // (see ./components/modebar/buttons.js for list of arguments) - modeBarButtonsToAdd: ModeBarButtons[]; - - // fully custom mode bar buttons as nested array, - // where the outer arrays represents button groups, and - // the inner arrays have buttons config objects or names of default buttons - // (see ./components/modebar/buttons.js for more info) - modeBarButtons: boolean; - - // add the plotly logo on the end of the mode bar - displaylogo: boolean; - - // increase the pixel ratio for Gl plot images - plotGlPixelRatio: number; - - // function to add the background color to a different container - // or 'opaque' to ensure there's white behind it - setBackground: string | 'opaque'; - - // URL to topojson files used in geo charts - topojsonURL: string; - - // Mapbox access token (required to plot mapbox trace types) - // If using an Mapbox Atlas server, set this option to '', - // so that plotly.js won't attempt to authenticate to the public Mapbox server. - mapboxAccessToken: string; - - // Turn all console logging on or off (errors will be thrown) - // This should ONLY be set via Plotly.setPlotConfig - logging: boolean; - - // Set global transform to be applied to all traces with no - // specification needed - globalTransforms: any[]; - } - - // Components - - interface RangeSlider { - visible: boolean; - thickness: number; - range: [Datum, Datum]; - borderwidth: number; - bordercolor: string; - bgcolor: string; - } - - interface RangeSelectorButton { - step: 'second' | 'minute' | 'hour' | 'day' | 'month' | 'year' | 'all'; - stepmode: 'backward' | 'todate'; - count: number; - label: string; - } - - interface RangeSelector { - buttons: Array>; - visible: boolean; - x: number; - xanchor: 'auto' | 'left' | 'center' | 'right'; - y: number; - yanchor: 'auto' | 'top' | 'middle' | 'bottom'; - bgcolor: string; - activecolor: string; - bordercolor: string; - borderwidth: number; - font: Partial; - } +export interface Point { + x: number; + y: number; + z: number; } -declare var Plotly: Plotly.PlotlyStatic; -export = Plotly; +export interface PlotlyHTMLElement extends HTMLElement { + on(event: 'plotly_click' | 'plotly_hover' | 'plotly_unhover', callback: (data: { + points: Array<{ + pointNumber: number; + curveNumber: number; + data: ScatterData; + }>; + }) => void): void; + on(event: 'plotly_selecting' | 'plotly_selected', callback: (data: { + points: Array<{ + x: number; + y: number; + pointNumber: number; + }>; + }) => void): void; + on(event: 'plotly_restyle', callback: (data: [ + any, // update object -- attribute updated: new value + number[] // array of traces updated + ]) => void): void; + on(event: 'plotly_relayout', callback: (data: { + xaxis: { + range: [number, number]; + autorange: boolean; + }; + yaxis: { + range: [number, number]; + autorange: boolean; + }; + scene: { + center: Point; + eye: Point; + up: Point; + }; + }) => void): void; + on(event: 'plotly_event', callback: (data: any) => void): void; + on(event: 'plotly_afterplot' | 'plotly_autosize' | 'plotly_deselect' | 'plotly_doubleclick' | 'plotly_redraw' | 'plotly_animated', callback: () => void): void; +} + +export interface ToImgopts { + format: 'jpeg' | 'png' | 'webp' | 'svg'; + width: number; + height: number; +} + +export interface DownloadImgopts { + format: 'jpeg' | 'png' | 'webp' | 'svg'; + width: number; + height: number; + filename: string; +} + +export type Root = string | HTMLElement; + +export function newPlot(root: Root, data: Array>, layout?: Partial, config?: Partial): Promise; +export function plot(root: Root, data: Array>, layout?: Partial, config?: Partial): Promise; +export function relayout(root: Root, layout: Partial): Promise; +export function redraw(root: Root): Promise; +export function purge(root: Root): PlotlyHTMLElement; +export const d3: any; +export function restyle(root: Root, aobj: Partial, traces?: number[] | number): Promise; +export function update(root: Root, traceUpdate: Partial, layoutUpdate: Partial, traces?: number[] | number): Promise; +export function addTraces(root: Root, traces: Partial | Array>, newIndices?: number[] | number): Promise; +export function deleteTraces(root: Root, indices: number[] | number): Promise; +export function moveTraces(root: Root, currentIndices: number[] | number, newIndices?: number[] | number): Promise; +export function extendTraces(root: Root, update: Partial | Array>, indices: number | number[]): Promise; +export function prependTraces(root: Root, update: Partial | Array>, indices: number | number[]): Promise; +export function toImage(root: Root, opts: ToImgopts): Promise; +export function downloadImage(root: Root, opts: DownloadImgopts): Promise; + +// Layout +export interface Layout { + title: string; + autosize: boolean; + showlegend: boolean; + xaxis: Partial; + yaxis: Partial; + margin: Partial; + height: number; + width: number; + hovermode: "closest" | "x" | "y" | false; + 'xaxis.range': [Datum, Datum]; + 'xaxis.range[0]': Datum; + 'xaxis.range[1]': Datum; + 'yaxis.range': [Datum, Datum]; + 'yaxis.range[0]': Datum; + 'yaxis.range[1]': Datum; + 'yaxis.type': AxisType; + 'xaxis.type': AxisType; + 'xaxis.autorange': boolean; + 'yaxis.autorange': boolean; + shapes: Array>; + legend: Partial; +} + +export interface Legend { + traceorder: "grouped" | "normal" | "reversed"; + x: number; + y: number; + font: Partial; + bgcolor: string; + bordercolor: string; + borderwidth: number; + orientation: "v" | "h"; + tracegroupgap: number; + xanchor: 'auto' | 'left' | 'center' | 'right'; + yanchor: 'auto' | 'top' | 'middle' | 'bottom'; +} + +export type AxisType = "date" | "log" | "linear"; + +export interface Axis { + title: string; + showgrid: boolean; + fixedrange: boolean; + rangemode: "tozero" | 'normal' | 'nonnegative'; + type: AxisType; + tickformat: string; + hoverformat: string; + rangeslider: Partial; + rangeselector: Partial; + range: [Datum, Datum]; + showticklabels: boolean; + autotick: boolean; + zeroline: boolean; + autorange: boolean | 'reversed'; +} + +export interface ShapeLine { + color: string; + width: number; + dash: Dash; +} + +export interface Shape { + visible: boolean; + layer: 'below' | 'above'; + type: 'rect' | 'circle' | 'line' | 'path'; + path: string; + // x-reference is assigned to the x-values + xref: 'x' | 'paper'; + // y-reference is assigned to the plot paper [0,1] + yref: 'paper' | 'y'; + x0: Datum; + y0: Datum; + x1: Datum; + y1: Datum; + fillcolor: string; + opacity: number; + line: Partial; +} + +export interface Margin { + t: number; + b: number; + l: number; + r: number; +} + +export type ModeBarButtons = 'lasso2d' | 'select2d' | 'sendDataToCloud' | 'autoScale2d' | + 'zoom2d' | 'pan2d' | 'zoomIn2d' | 'zoomOut2d' | 'autoScale2d' | 'resetScale2d' | + 'hoverClosestCartesian' | 'hoverCompareCartesian' | 'zoom3d' | 'pan3d' | 'orbitRotation' | + 'tableRotation' | 'resetCameraDefault3d' | 'resetCameraLastSave3d' | 'hoverClosest3d' | + 'zoomInGeo' | 'zoomOutGeo' | 'resetGeo' | 'hoverClosestGeo' | 'hoverClosestGl2d' | + 'hoverClosestPie' | 'toggleHover' | 'resetViews'; + +// Data + +export type Datum = string | number | Date; + +export type Dash = 'solid' | 'dot' | 'dash' | 'longdash' | 'dashdot' | 'longdashdot'; + +export type Data = Partial; +export type Color = string | Array | Array>; + +// Bar Scatter +export interface ScatterData { + type: 'bar' | 'scatter' | 'scattergl'; + x: Datum[] | Datum[][]; + y: Datum[] | Datum[][]; + text: string | string[]; + line: Partial; + 'line.color': Color; + 'line.width': number; + 'line.dash': Dash; + 'line.shape': 'linear' | 'spline' | 'hv' | 'vh' | 'hvh' | 'vhv'; + 'line.smoothing': number; + 'line.simplify': boolean; + marker: Partial; + 'marker.symbol': string | string[]; // Drawing.symbolList + 'marker.color': Color; + 'marker.opacity': number | number[]; + 'marker.size': number | number[]; + 'marker.maxdisplayed': number; + 'marker.sizeref': number; + 'marker.sizemin': number; + 'marker.sizemode': "diameter" | "area"; + 'marker.showscale': boolean; + 'marker.line': {}; // TODO + 'marker.colorbar': {}; // TODO + mode: "lines" | "markers" | "text" | "lines+markers" | "text+markers" | "text+lines" | "text+lines+markers" | "none"; + hoveron: "points" | "fills"; + hoverinfo: "text"; + fill: 'none' | 'tozeroy' | 'tozerox' | 'tonexty' | 'tonextx' | 'toself' | 'tonext'; + fillcolor: string; + legendgroup: string; + name: string; + connectgaps: boolean; +} + +export interface ScatterMarker { + symbol: string | string[]; // Drawing.symbolList + color: Color; + opacity: number | number[]; + size: number | number[]; + maxdisplayed: number; + sizeref: number; + sizemin: number; + sizemode: "diameter" | "area"; + showscale: boolean; + line: {}; // TODO + colorbar: {}; // TODO +} + +export interface ScatterLine { + color: Color; + width: number; + dash: Dash; + shape: 'linear' | 'spline' | 'hv' | 'vh' | 'hvh' | 'vhv'; + smoothing: number; + simplify: boolean; +} + +export interface Font { + family: string; + size: number; + color: string; +} + +export interface Config { + // no interactivity, for export or image generation + staticPlot: boolean; + + // we can edit titles, move annotations, etc + editable: boolean; + + // DO autosize once regardless of layout.autosize + // (use default width or height values otherwise) + autosizable: boolean; + + // set the length of the undo/redo queue + queueLength: number; + + // if we DO autosize, do we fill the container or the screen? + fillFrame: boolean; + + // if we DO autosize, set the frame margins in percents of plot size + frameMargins: number; + + // mousewheel or two-finger scroll zooms the plot + scrollZoom: boolean; + + // double click interaction (false, 'reset', 'autosize' or 'reset+autosize') + doubleClick: 'reset+autosize' | 'reset' | 'autosize' | false; + + // new users see some hints about interactivity + showTips: boolean; + + // link to open this plot in plotly + showLink: boolean; + + // if we show a link, does it contain data or just link to a plotly file? + sendData: boolean; + + // text appearing in the sendData link + linkText: string; + + // false or function adding source(s) to linkText + showSources: boolean; + + // display the mode bar (true, false, or 'hover') + displayModeBar: 'hover' | boolean; + + // remove mode bar button by name + // (see ./components/modebar/buttons.js for the list of names) + modeBarButtonsToRemove: ModeBarButtons[]; + + // add mode bar button using config objects + // (see ./components/modebar/buttons.js for list of arguments) + modeBarButtonsToAdd: ModeBarButtons[]; + + // fully custom mode bar buttons as nested array, + // where the outer arrays represents button groups, and + // the inner arrays have buttons config objects or names of default buttons + // (see ./components/modebar/buttons.js for more info) + modeBarButtons: boolean; + + // add the plotly logo on the end of the mode bar + displaylogo: boolean; + + // increase the pixel ratio for Gl plot images + plotGlPixelRatio: number; + + // function to add the background color to a different container + // or 'opaque' to ensure there's white behind it + setBackground: string | 'opaque'; + + // URL to topojson files used in geo charts + topojsonURL: string; + + // Mapbox access token (required to plot mapbox trace types) + // If using an Mapbox Atlas server, set this option to '', + // so that plotly.js won't attempt to authenticate to the public Mapbox server. + mapboxAccessToken: string; + + // Turn all console logging on or off (errors will be thrown) + // This should ONLY be set via Plotly.setPlotConfig + logging: boolean; + + // Set global transform to be applied to all traces with no + // specification needed + globalTransforms: any[]; +} + +// Components + +export interface RangeSlider { + visible: boolean; + thickness: number; + range: [Datum, Datum]; + borderwidth: number; + bordercolor: string; + bgcolor: string; +} + +export interface RangeSelectorButton { + step: 'second' | 'minute' | 'hour' | 'day' | 'month' | 'year' | 'all'; + stepmode: 'backward' | 'todate'; + count: number; + label: string; +} + +export interface RangeSelector { + buttons: Array>; + visible: boolean; + x: number; + xanchor: 'auto' | 'left' | 'center' | 'right'; + y: number; + yanchor: 'auto' | 'top' | 'middle' | 'bottom'; + bgcolor: string; + activecolor: string; + bordercolor: string; + borderwidth: number; + font: Partial; +} diff --git a/types/plotly.js/plotly.js-tests.ts b/types/plotly.js/plotly.js-tests.ts index ab71c73e7d..f33886d841 100644 --- a/types/plotly.js/plotly.js-tests.ts +++ b/types/plotly.js/plotly.js-tests.ts @@ -1,11 +1,347 @@ import * as Plotly from 'plotly.js'; +import { ScatterData, Layout, PlotlyHTMLElement, newPlot } from 'plotly.js'; -const data: Plotly.BarData[] = [ - { - x: ['giraffes', 'orangutans', 'monkeys'], - y: [20, 14, 23], - type: 'bar' - } -]; +const graphDiv = '#test'; -Plotly.newPlot('test', data); +////////////////////////////////////////////////////////////////////// +// Plotly.newPlot +(() => { + const trace1 = { + x: [1999, 2000, 2001, 2002], + y: [10, 15, 13, 17], + type: 'scatter' + } as ScatterData; + const trace2 = { + x: [1999, 2000, 2001, 2002], + y: [16, 5, 11, 9], + type: 'scatter' + } as ScatterData; + const data = [trace1, trace2]; + const layout = { + title: 'Sales Growth', + xaxis: { + title: 'Year', + showgrid: false, + zeroline: false + }, + yaxis: { + title: 'Percent', + showline: false + } + }; + Plotly.newPlot(graphDiv, data, layout); +})(); +(() => { + // deprecated: calling plot again will add new trace(s) to the plot, + // but will ignore new layout. + const data2 = [{ + x: [1999, 2000, 2001, 2002], + y: [10, 9, 8, 7], + type: 'scatter' + } as ScatterData]; + const layout2 = { title: 'Revenue' }; + Plotly.newPlot(graphDiv, data2, layout2); +})(); + +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.restyle +// restyle a single trace using attribute strings +(() => { + const update = { + opacity: 0.4, + 'marker.color': 'red' + }; + Plotly.restyle(graphDiv, update, 0); +})(); + +// restyle all traces using attribute strings +(() => { + const update = { + opacity: 0.4, + 'marker.color': 'red' + }; + Plotly.restyle(graphDiv, update); +})(); +// restyle the first trace's marker color 'red' and the second's 'green' +(() => { + const update = { + 'marker.color': ['red', 'green'] + }; + Plotly.restyle(graphDiv, update, [0, 1]); +})(); + +// alternate between red and green for all traces (note omission of traces) +(() => { + const update = { + 'marker.color': ['red', 'green'] + }; + Plotly.restyle(graphDiv, update); +})(); + +// restyle two traces using attribute strings +(() => { + const update = { + opacity: 0.4, + 'marker.color': 'red' + }; + Plotly.restyle(graphDiv, update, [1, 2]); +})(); + +// update the color attribute of the first trace so that the markers within the same trace +// have different colors +(() => { + const update = { + 'marker.color': [['red', 'green']] + }; + Plotly.restyle(graphDiv, update, [0]); +})(); + +// update two traces with new z data +(() => { + const update = { z: [[[1, 2, 3], [2, 1, 2], [1, 1, 1]], [[0, 1, 1], [0, 2, 1], [3, 2, 1]]] }; + Plotly.restyle(graphDiv, update, [1, 2]); +})(); + +// replace the entire marker object with the one provided +(() => { + const update = { + marker: { color: 'red' } + }; + Plotly.restyle(graphDiv, update, [0]); +})(); + +// Set the first trace's line to red, the second to the default, and ignore the third +(() => { + Plotly.restyle(graphDiv, { + 'line.color': ['red', null, undefined] + }, [0, 1, 2]); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.relayout +// update only values within nested objects +(() => { + const update = { + title: 'some new title', // updates the title + 'xaxis.range': [0, 5], // updates the xaxis range + 'yaxis.range[1]': 15 // updates the end of the yaxis range + } as Layout; + Plotly.relayout(graphDiv, update); +})(); + +(() => { + const data_update = { + marker: { color: 'red' } + }; + const layout_update = { + title: 'some new title', // updates the title + }; + Plotly.update(graphDiv, data_update, layout_update); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.update +(() => { + const data_update = { + marker: { color: 'red' } + }; + const layout_update = { + title: 'some new title', // updates the title + }; + Plotly.update(graphDiv, data_update, layout_update); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.addTraces +(() => { + // add a single trace to an existing graphDiv + Plotly.addTraces(graphDiv, { y: [2, 1, 2] }); + + // add two traces + Plotly.addTraces(graphDiv, [{ y: [2, 1, 2] }, { y: [4, 5, 7] }]); + + // add a trace at the beginning of the data array + Plotly.addTraces(graphDiv, { y: [1, 5, 7] }, 0); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.deleteTraces +(() => { + // remove the first trace + Plotly.deleteTraces(graphDiv, 0); + + // remove the last two traces + Plotly.deleteTraces(graphDiv, [-2, -1]); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.moveTraces +(() => { + // move the first trace (at index 0) the the end of the data array + Plotly.moveTraces(graphDiv, 0); + + // move selected traces (at indices [0, 3, 5]) to the end of the data array + Plotly.moveTraces(graphDiv, [0, 3, 5]); + + // move last trace (at index -1) to the beginning of the data array (index 0) + Plotly.moveTraces(graphDiv, -1, 0); + + // move selected traces (at indices [1, 4, 5]) to new indices [0, 3, 2] + Plotly.moveTraces(graphDiv, [1, 4, 5], [0, 3, 2]); +})(); +////////////////////////////////////////////////////////////////////// + +function rand() { + return Math.random(); +} + +////////////////////////////////////////////////////////////////////// +// Plotly.extendTraces +(() => { + // extend one trace + Plotly.extendTraces(graphDiv, { y: [[rand()]] }, [0]); + + // extend multiple traces + Plotly.extendTraces(graphDiv, { y: [[rand()], [rand()]] }, [0, 1]); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.prependTraces +(() => { + // prepend one trace + Plotly.prependTraces(graphDiv, { y: [[rand()]] }, [0]); + + // prepend multiple traces + Plotly.prependTraces(graphDiv, { y: [[rand()], [rand()]] }, [0, 1]); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.purge +(() => { + // purge will be used on the div that you wish clear of Plotly plots + Plotly.purge(graphDiv); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.toImage +(() => { + // Plotly.toImage will turn the plot in the given div into a data URL string + // toImage takes the div as the first argument and an object specifying image properties as the other + Plotly.toImage(graphDiv, { format: 'png', width: 800, height: 600 }).then((dataUrl) => { + // use the dataUrl + }); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Plotly.downloadImage +(() => { + // downloadImage will accept the div as the first argument and an object specifying image properties as the other + Plotly.downloadImage(graphDiv, { format: 'png', width: 800, height: 600, filename: 'newplot' }); +})(); +////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////// +// Using events +(async () => { + const myPlot = await newPlot(graphDiv, [{ + x: [1999, 2000, 2001, 2002], + y: [10, 9, 8, 7], + type: 'scatter' + }]); + myPlot.on('plotly_click', (data) => { + let pn = 0; + let tn = 0; + let colors = [] as string[]; + for (const pt of data.points) { + pn = pt.pointNumber; + tn = pt.curveNumber; + colors = pt.data.marker.color as string[]; + } + colors[pn] = '#C54C82'; + + const update = { marker: { color: colors, size: 16 } }; + Plotly.restyle('myDiv', update, [tn]); + }); + + myPlot.on('plotly_hover', (data) => { + let pn = 0; + let tn = 0; + let colors = [] as string[]; + for (const pt of data.points) { + pn = pt.pointNumber; + tn = pt.curveNumber; + colors = pt.data.marker.color as string[]; + } + colors[pn] = '#C54C82'; + + const update = { marker: { color: colors, size: 16 } }; + Plotly.restyle('myDiv', update, [tn]); + }); + + myPlot.on('plotly_unhover', (data) => { + let pn = 0; + let tn = 0; + let colors = [] as string[]; + for (const pt of data.points) { + pn = pt.pointNumber; + tn = pt.curveNumber; + colors = pt.data.marker.color as string[]; + } + colors[pn] = '#00000'; + + const update = { marker: { color: colors, size: 16 } }; + Plotly.restyle('myDiv', update, [tn]); + }); + + myPlot.on('plotly_selected', (data) => { + const x = [] as number[]; + const y = [] as number[]; + const N = 1000; + const color1 = '#7b3294'; + const color1Light = '#c2a5cf'; + + const colors = [] as string[]; + for (let i = 0; i < N; i++) colors.push(color1Light); + + data.points.forEach((pt) => { + x.push(pt.x); + y.push(pt.y); + colors[pt.pointNumber] = color1; + }); + + Plotly.restyle(myPlot, { + x: [x, y] + }, [1, 2]); + + Plotly.restyle(myPlot, { + 'marker.color': [colors] + }, [0]); + }); + + myPlot.on('plotly_restyle', (data) => { + console.log('restyling'); + }); + + myPlot.on('plotly_doubleclick', () => { + const orgColors = ['#00000', '#00000', '#00000', + '#00000', '#00000', '#00000']; + const update = { marker: { color: orgColors, size: 16 } }; + Plotly.restyle('myDiv', update); + }); + + myPlot.on('plotly_afterplot', () => { + console.log('done plotting'); + }); +})(); +////////////////////////////////////////////////////////////////////// From 2cef5f24fff8f9e8a5204d71e118435ac34adcbb Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 11:08:30 +0200 Subject: [PATCH 0078/1618] remove package.json --- types/fm-websync/package.json | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 types/fm-websync/package.json diff --git a/types/fm-websync/package.json b/types/fm-websync/package.json deleted file mode 100644 index 6843239469..0000000000 --- a/types/fm-websync/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "fm-websync", - "version": "1.0.0", - "description": "Type definitions for Frozen Mountain WebSync 3", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Markus Mauch", - "license": "ISC" -} From 67156299739bf7094811cad6b97bca234cc96e7e Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 11:26:09 +0200 Subject: [PATCH 0079/1618] changed module system to commonjs --- types/fm-websync/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/fm-websync/tsconfig.json b/types/fm-websync/tsconfig.json index 76193744be..7d22ec59f0 100644 --- a/types/fm-websync/tsconfig.json +++ b/types/fm-websync/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "module": "none", + "module": "commonjs", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, From 79deb2bdefe2100fc3f3c7188ba6547ed79bbe5d Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 11:30:13 +0200 Subject: [PATCH 0080/1618] added es6, dom to lib --- types/fm-websync/tsconfig.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/fm-websync/tsconfig.json b/types/fm-websync/tsconfig.json index 7d22ec59f0..1ec64935da 100644 --- a/types/fm-websync/tsconfig.json +++ b/types/fm-websync/tsconfig.json @@ -8,6 +8,9 @@ "typeRoots": [ "../" ], + "lib": [ + "es6", "dom" + ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true From 9b2f23ba782376b1ea0559800c39bc292a7fd8f4 Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Fri, 30 Jun 2017 11:32:58 +0200 Subject: [PATCH 0081/1618] fixing travis errors --- types/alexa-sdk/alexa-sdk-tests.ts | 4 ++-- types/alexa-sdk/index.d.ts | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/types/alexa-sdk/alexa-sdk-tests.ts b/types/alexa-sdk/alexa-sdk-tests.ts index cbf1ba70a3..1454309b93 100644 --- a/types/alexa-sdk/alexa-sdk-tests.ts +++ b/types/alexa-sdk/alexa-sdk-tests.ts @@ -1,12 +1,12 @@ import * as Alexa from "alexa-sdk"; -const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => { +const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => { let alexa = Alexa.handler(event, context); alexa.registerHandlers(handlers); alexa.execute(); }; -let handlers: Alexa.Handlers = { +let handlers: Alexa.Handlers = { 'LaunchRequest': function() { this.emit('SayHello'); }, diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 88e25927d6..0a1a5fcec0 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -22,7 +22,7 @@ export interface AlexaObject extends Handler { response: any; dynamoDBTableName: any; saveBeforeResponse: boolean; - registerHandlers: (...handlers: Handlers[]) => any; + registerHandlers: (...handlers: Array>) => any; execute: () => void; } @@ -108,7 +108,6 @@ export interface Intent { slots: Record; } - export interface ResponseBody { version: string; sessionAttributes?: any; @@ -144,4 +143,3 @@ export interface Image { export interface Reprompt { outputSpeech: OutputSpeech; } - From 63cc0df9e503c76731e62f60bea295c48a4ec383 Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Fri, 30 Jun 2017 11:38:17 +0200 Subject: [PATCH 0082/1618] allowing any in tslint.json --- types/alexa-sdk/tslint.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/alexa-sdk/tslint.json b/types/alexa-sdk/tslint.json index 0c1ca3b5b4..78f1939ba2 100644 --- a/types/alexa-sdk/tslint.json +++ b/types/alexa-sdk/tslint.json @@ -4,6 +4,7 @@ "object-literal-key-quote": false, "no-empty-interface": false, "prefer-method-signature": false, - "object-literal-key-quotes": false + "object-literal-key-quotes": false, + "no-any": false } } From c2ab4891c4abef81fd6a3ae011f87a0c59462ec5 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 11:38:30 +0200 Subject: [PATCH 0083/1618] file ends with newline now --- types/fm-websync/fm-websync-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/fm-websync/fm-websync-tests.ts b/types/fm-websync/fm-websync-tests.ts index aeb665e5ae..6bdfd5de95 100644 --- a/types/fm-websync/fm-websync-tests.ts +++ b/types/fm-websync/fm-websync-tests.ts @@ -16,4 +16,4 @@ client.disconnect( { onSuccess: args => console.log( `Disconnect success: {args.clientId}` ), onFailure: args => console.log( `Disconnect failure: {args.clientId}` ), onComplete: args => console.log( `Disconnect complete: {args.clientId}` ) -} ); \ No newline at end of file +} ); From b6f0d2ac47d5d0a4b2b319359c4861208e0e66af Mon Sep 17 00:00:00 2001 From: Pascal Brokmeier Date: Fri, 30 Jun 2017 11:39:21 +0200 Subject: [PATCH 0084/1618] fix missing semicolon --- types/alexa-sdk/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 0a1a5fcec0..24baccf484 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -93,7 +93,7 @@ export interface Request { type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; requestId: string; timestamp: string; - locale?: string + locale?: string; } export interface SlotValue { From effd1ecd56b1753cc2f232aea5cf3ecda8a57d50 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 11:47:59 +0200 Subject: [PATCH 0085/1618] Changed replaced Function and String Comply with max line length --- types/fm-websync/index.d.ts | 61 +++++++++++++++++++++++++------------ 1 file changed, 42 insertions(+), 19 deletions(-) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index ae3677b986..f118ebe051 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -10,7 +10,10 @@ declare namespace fm interface initializeConfig { /** - * If set to true, an asynchronous disconnect request will be launched when the page unloads. If set to false, no automatic disconnection will be attempted. If set to an object, then a disconnect request will be launched when the page unloads using the object as the disconnect configuration. (See disconnectConfig for details.) Note that automatic disconnects are a best-effort. The only way to guarantee success is to execute the disconnect synchronously and target a request URL on the same domain as the page ({ sync: true, requestUrl: '...relative path.../request.ashx' }). Defaults to false. + * If set to true, an asynchronous disconnect request will be launched when the page unloads. If set to false, no automatic disconnection will be attempted. + * If set to an object, then a disconnect request will be launched when the page unloads using the object as the disconnect configuration. + * (See disconnectConfig for details.) Note that automatic disconnects are a best-effort. The only way to guarantee success is to execute the disconnect synchronously + * and target a request URL on the same domain as the page ({ sync: true, requestUrl: '...relative path.../request.ashx' }). Defaults to false. */ autoDisconnect?: boolean; @@ -21,12 +24,15 @@ declare namespace fm backoffInterval?: number; /** - * The URL of the HTML frame to be used with HTML5 postMessage for cross-domain environments. Must have the same domain as requestUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server ClientHandler registered in web.config with "frame" added to the query. + * The URL of the HTML frame to be used with HTML5 postMessage for cross-domain environments. Must have the same domain as requestUrl. + * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server + * ClientHandler registered in web.config with "frame" added to the query. */ clientFrameUrl?: string; /** - * The domain key to send with each request. If using WebSync On-Demand, this should be set to the public or private API key specified in the Frozen Mountain Portal. If using WebSync Server, this should be used only if grouping connections. Defaults to "11111111-1111-1111-1111-111111111111". + * The domain key to send with each request. If using WebSync On-Demand, this should be set to the public or private API key specified in the Frozen Mountain Portal. + * If using WebSync Server, this should be used only if grouping connections. Defaults to "11111111-1111-1111-1111-111111111111". */ key?: string; @@ -51,7 +57,9 @@ declare namespace fm quiet?: boolean; /** - * The URL of the WebSync request handler. This URL typically ends with request.ashx. Must have the same domain as clientFrameUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server RequestHandler registered in web.config. + * The URL of the WebSync request handler. This URL typically ends with request.ashx. Must have the same domain as clientFrameUrl. + * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the + * WebSync Server RequestHandler registered in web.config. */ requestUrl?: string; @@ -64,9 +72,13 @@ declare namespace fm * The URLs to use for streaming connections. Three properties are available: * * requestUrl: string - * Same as the root requestUrl parameter, but used for streaming connections. Must have the same domain as stream.clientFrameUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the streamHost web.config attribute, if specified) and the path to the WebSync Server RequestHandler registered in web.config. + * Same as the root requestUrl parameter, but used for streaming connections. Must have the same domain as stream.clientFrameUrl. + * Defaults to a dynamically generated URL based on the host of the client script URL (or the streamHost web.config attribute, if specified) and the path to the + * WebSync Server RequestHandler registered in web.config. * clientFrameUrl: string - * Same as the root clientFrameUrl parameter, but used for streaming connections. Must have the same domain as stream.requestUrl. Defaults to a dynamically generated URL based on the host of the client script URL (or the streamHost web.config attribute, if specified) and the path to the WebSync Server ClientHandler registered in web.config with "frame" added to the query. + * Same as the root clientFrameUrl parameter, but used for streaming connections. Must have the same domain as stream.requestUrl. + * Defaults to a dynamically generated URL based on the host of the client script URL (or the streamHost web.config attribute, if specified) and the path to the + * WebSync Server ClientHandler registered in web.config with "frame" added to the query. * timeout: number * Same as the root timeout parameter, but used for streaming connections. Defaults to the root timeout + 25000 (25 seconds). */ @@ -84,7 +96,8 @@ declare namespace fm token?: string; /** - * An object specifying URLs to be used for specific client methods. Overrides initializeConfig.requestUrl for the specified method type, but can be overridden by the requestUrl specified in individual method configurations. + * An object specifying URLs to be used for specific client methods. Overrides initializeConfig.requestUrl for the specified method type, but can be overridden + * by the requestUrl specified in individual method configurations. * * connect: string * The URL to use for all client.connect requests. @@ -126,12 +139,15 @@ declare namespace fm requestUrl?: string; /** - * Whether to ignore errors when parsing the server response. If true, any errors thrown while parsing the JSON response received from the server will be ignored. Defaults to false. + * Whether to ignore errors when parsing the server response. If true, any errors thrown while parsing the JSON response received from the server will be ignored. + * Defaults to false. */ suppressErrors?: boolean; /** - * Whether the request should be executed asynchronously. If true, the request will be executed synchronously if supported by the browser; otherwise, it will be executed asynchronously. All browsers support synchronous requests if the request URL is the same domain as the page. Synchronous requests are not supported in IE6 and IE7 for cross-domain environments. Defaults to false. + * Whether the request should be executed asynchronously. If true, the request will be executed synchronously if supported by the browser; otherwise, + * it will be executed asynchronously. All browsers support synchronous requests if the request URL is the same domain as the page. Synchronous requests + * are not supported in IE6 and IE7 for cross-domain environments. Defaults to false. */ sync?: boolean; } @@ -150,9 +166,11 @@ declare namespace fm /** * The callback to invoke if the streaming connection fails. See streamFailureArgs for callback argument details. - * This method will be invoked if (a) the connection was lost, automatic retries succeeded, but the client had idled on the server (and so needs to reconnect), or (b) the connection was lost and automatic retries failed. In the former case, willReconnect is true, and in the latter case, willReconnect is false. + * This method will be invoked if (a) the connection was lost, automatic retries succeeded, but the client had idled on the server (and so needs to reconnect), + * or (b) the connection was lost and automatic retries failed. In the former case, willReconnect is true, and in the latter case, willReconnect is false. * See client for more details on these two scenarios. - * If willReconnect is true, the client will automatically reconnect. If the reconnect succeeds, the callback specified by onSuccess will be invoked with isReconnect set to true. If the reconnect fails, the callback specified by onFailure will be invoked with isReconnect set to false. + * If willReconnect is true, the client will automatically reconnect. If the reconnect succeeds, the callback specified by onSuccess will be invoked with isReconnect set to true. + * If the reconnect fails, the callback specified by onFailure will be invoked with isReconnect set to false. * With the exception of UI updates, invocations of this callback with willReconnect set to true can be ignored. */ onStreamFailure?: ( args: streamFailureArgs ) => void; @@ -164,12 +182,13 @@ declare namespace fm /** * The callback to invoke when a message is received on a channel that has no local callback specified to handle it. See receiveArgs for callback argument details. - * This can occur if (a) a client is manually subscribed to a channel by the server or (b) a client subscribed to a channel and then manually removed the local callback using client.unsetHandler. + * This can occur if (a) a client is manually subscribed to a channel by the server or (b) a client subscribed to a channel and then manually removed the local callback using client. */ - onUnhandledReceive?: Function; + onUnhandledReceive?: ( args: receiveArgs ) => void; /** - * Whether to always attempt to stay connected in the event of network failure. If true, the client will continually reconnect, even after exhausting the specified number of retries specified by initializeConfig.retries. If false, the client will stop reconnecting if all retry attempts fail. + * Whether to always attempt to stay connected in the event of network failure. If true, the client will continually reconnect, even after exhausting the specified number + * of retries specified by initializeConfig.retries. If false, the client will stop reconnecting if all retry attempts fail. */ stayConnected?: boolean; } @@ -179,12 +198,12 @@ declare namespace fm /** * The channel to which the client should be subscribed. Must start with a forward slash (/). Overrides channels. */ - channel?: String; + channel?: string; /** * The channels to which the client should be subscribed. Each must start with a forward slash (/). Overrides channel. */ - channels?: String[]; + channels?: string[]; /** * The callback to invoke after onSuccess or onFailure. See subscribeCompleteArgs for callback argument details. @@ -455,7 +474,9 @@ declare namespace fm { /** * Sets up and maintains a streaming connection to the server. - * While this method will typically run asychronously, the WebSync client is designed to be used without (much) consideration for its asynchronous nature. To that end, any calls to methods that require an active connection, like bind, subscribe and publish, will be queued automatically and executed once this method has completed successfully. + * While this method will typically run asychronously, the WebSync client is designed to be used without (much) consideration for its asynchronous nature. + * To that end, any calls to methods that require an active connection, like bind, subscribe and publish, will be queued automatically and executed once this + * method has completed successfully. * * @param connectConfig */ @@ -464,7 +485,8 @@ declare namespace fm /** * * @param config Takes down a streaming connection to the server and unsubscribes the client. - * After the disconnect completes successfully, any further calls to methods that require an active connection, like bind, subscribe and publish, will be queued automatically and executed only if/when the client reconnects. + * After the disconnect completes successfully, any further calls to methods that require an active connection, like bind, subscribe and publish, will be queued + * automatically and executed only if/when the client reconnects. */ public disconnect( config: disconnectConfig ): client; @@ -476,7 +498,8 @@ declare namespace fm /** * Subscribes the client to receive messages on one or more channels. - * When the subscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the subscribed channel(s), including any modifications made on the server. + * When the subscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the subscribed channel(s), + * including any modifications made on the server. */ public subscribe( config: subscribeConfig ): client; } From 94ef450a22604098cea52b7e1b8089b136e080ef Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 11:58:23 +0200 Subject: [PATCH 0086/1618] removed iplicit public --- types/fm-websync/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index f118ebe051..887d63039f 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -480,7 +480,7 @@ declare namespace fm * * @param connectConfig */ - public connect( config: connectConfig ): client; + connect( config: connectConfig ): client; /** * @@ -488,20 +488,20 @@ declare namespace fm * After the disconnect completes successfully, any further calls to methods that require an active connection, like bind, subscribe and publish, will be queued * automatically and executed only if/when the client reconnects. */ - public disconnect( config: disconnectConfig ): client; + disconnect( config: disconnectConfig ): client; /** * Initializes the client according to the specified configuration. * This method must always be called first. While is always executes synchronously, callbacks are allowed for the purposes of method chaining. */ - public static initialize( config: initializeConfig ): client; + static initialize( config: initializeConfig ): client; /** * Subscribes the client to receive messages on one or more channels. * When the subscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the subscribed channel(s), * including any modifications made on the server. */ - public subscribe( config: subscribeConfig ): client; + subscribe( config: subscribeConfig ): client; } } } From 94cf810b99b77321166096b873cc9b4dfabdae02 Mon Sep 17 00:00:00 2001 From: Hussein Shabbir Date: Fri, 30 Jun 2017 14:32:30 +0400 Subject: [PATCH 0087/1618] Fixed definitions to handle FieldArray errors. --- types/redux-form/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index acf1dcc857..8a51117530 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -19,12 +19,12 @@ export interface DataShape { } export type FormErrors = { - [P in keyof FormData]?: ReactElement | string; -} & { _error?: string }; + [P in keyof FormData]?: ReactElement | string | { _error?: string }; +}; export type FormWarnings = { - [P in keyof FormData]?: ReactElement | string; -} & { _warning?: string }; + [P in keyof FormData]?: ReactElement | string | { _warning?: string }; +}; /** * A component class or stateless function component. From 6f9745c427f49d1e25e00326cc7e23b7066cc17d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pap=20L=C5=91rinc?= Date: Fri, 30 Jun 2017 12:53:38 +0300 Subject: [PATCH 0088/1618] Unified superagent-tests.ts's formatting --- types/superagent/superagent-tests.ts | 84 ++++++++++++---------------- 1 file changed, 37 insertions(+), 47 deletions(-) diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index f38dcb31ea..63ccd70f0e 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -12,7 +12,7 @@ const httpsAgent: Agent = new Agent(); request .post('/api/pet') - .send({name: 'Manny', species: 'cat'}) + .send({ name: 'Manny', species: 'cat' }) .set('X-API-Key', 'foobar') .set('Accept', 'application/json') .agent(httpsAgent) @@ -27,7 +27,7 @@ request const agent = request.agent(); agent .post('/api/pet') - .send({name: 'Manny', species: 'cat'}) + .send({ name: 'Manny', species: 'cat' }) .set('X-API-Key', 'foobar') .set('Accept', 'application/json') .end((err, res) => { @@ -81,20 +81,20 @@ request request .get('/search') - .set({'API-Key': 'foobar', Accept: 'application/json'}) + .set({ 'API-Key': 'foobar', Accept: 'application/json' }) .end(callback); // GET requests request .get('/search') - .query({query: 'Manny'}) - .query({range: '1..5'}) - .query({order: 'desc'}) + .query({ query: 'Manny' }) + .query({ range: '1..5' }) + .query({ order: 'desc' }) .end(callback); request .get('/search') - .query({query: 'Manny', range: '1..5', order: 'desc'}) + .query({ query: 'Manny', range: '1..5', order: 'desc' }) .end(callback); request @@ -111,7 +111,7 @@ request // HEAD requests request .head('/users') - .query({email: 'joe@smith.com'}) + .query({ email: 'joe@smith.com' }) .end(callback); // POST / PUT requests @@ -121,12 +121,12 @@ request.post('/user') .end(callback); request.post('/user') - .send({name: 'tj', pet: 'tobi'}) + .send({ name: 'tj', pet: 'tobi' }) .end(callback); request.post('/user') - .send({name: 'tj'}) - .send({pet: 'tobi'}) + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) .end(callback); request.post('/user') @@ -136,8 +136,8 @@ request.post('/user') request.post('/user') .type('form') - .send({name: 'tj'}) - .send({pet: 'tobi'}) + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) .end(callback); // Setting the Content-Type @@ -166,22 +166,22 @@ request.get('/user') // Query strings request .post('/') - .query({format: 'json'}) - .query({dest: '/login'}) - .send({post: 'data', here: 'wahoo'}) + .query({ format: 'json' }) + .query({ dest: '/login' }) + .send({ post: 'data', here: 'wahoo' }) .end(callback); // Custom request serializer function testParser(data: any) { - return JSON.stringify(data); + return JSON.stringify(data); } request - .post('/user') - .serialize(testParser) - .type('json') - .send({ foo: 123 }) - .end(callback); + .post('/user') + .serialize(testParser) + .type('json') + .send({ foo: 123 }) + .end(callback); // Default serialization map @@ -189,15 +189,15 @@ request.serialize['application/xml'] = (obj: any) => 'generated xml here'; // Parsing response bodies request('/search') - .end((res: request.Response) => { - const status: number = res.status; - const body = res.body; - const files: object = res.files; - const text: string = res.text; - const contentLength = res.header['content-length']; - const contentType: string = res.type; - const charset: string = res.charset; - }); + .end((res: request.Response) => { + const status: number = res.status; + const body = res.body; + const files: object = res.files; + const text: string = res.text; + const contentLength = res.header['content-length']; + const contentType: string = res.type; + const charset: string = res.charset; + }); // Custom parsers request @@ -244,16 +244,6 @@ request .redirects(2) .end(callback); -// Piping data -/* -(() => { -const stream = fs.createReadStream('path/to/my.json'); -const req = request.post('/somewhere'); -req.type('json'); -stream.pipe(req); -})(); -*/ - (() => { const stream = fs.createWriteStream('path/to/my.json'); const req = request.get('/some.json'); @@ -339,9 +329,9 @@ request // Requesting binary data. // adapted from: https://github.com/visionmedia/superagent/blob/v2.0.0/test/client/request.js#L110 request - .get('/blob') - .responseType('blob') - .end((err, res) => { - assert(res.xhr instanceof XMLHttpRequest); - assert(res.xhr.response instanceof Blob); - }); + .get('/blob') + .responseType('blob') + .end((err, res) => { + assert(res.xhr instanceof XMLHttpRequest); + assert(res.xhr.response instanceof Blob); + }); From fff58149314ce6abc4b1a4a78ee66934419fc01e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pap=20L=C5=91rinc?= Date: Fri, 30 Jun 2017 12:57:42 +0300 Subject: [PATCH 0089/1618] Sorted superagent type definition fields --- types/superagent/index.d.ts | 88 ++++++++++++++++++------------------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index df3a7e709f..2a48f26ee4 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -21,9 +21,9 @@ declare namespace request { interface SuperAgentRequest extends Request { agent(agent?: https.Agent): this; + cookies: string; method: string; url: string; - cookies: string; } interface SuperAgentStatic extends SuperAgent { (url: string): SuperAgentRequest; @@ -35,66 +35,64 @@ declare namespace request { } interface SuperAgent extends stream.Stream { - get(url: string, callback?: CallbackHandler): Req; - post(url: string, callback?: CallbackHandler): Req; - put(url: string, callback?: CallbackHandler): Req; - head(url: string, callback?: CallbackHandler): Req; + attachCookies(req: Req): void; + checkout(url: string, callback?: CallbackHandler): Req; + connect(url: string, callback?: CallbackHandler): Req; + copy(url: string, callback?: CallbackHandler): Req; del(url: string, callback?: CallbackHandler): Req; delete(url: string, callback?: CallbackHandler): Req; - options(url: string, callback?: CallbackHandler): Req; - trace(url: string, callback?: CallbackHandler): Req; - copy(url: string, callback?: CallbackHandler): Req; + get(url: string, callback?: CallbackHandler): Req; + head(url: string, callback?: CallbackHandler): Req; lock(url: string, callback?: CallbackHandler): Req; + merge(url: string, callback?: CallbackHandler): Req; + mkactivity(url: string, callback?: CallbackHandler): Req; mkcol(url: string, callback?: CallbackHandler): Req; move(url: string, callback?: CallbackHandler): Req; - purge(url: string, callback?: CallbackHandler): Req; + notify(url: string, callback?: CallbackHandler): Req; + options(url: string, callback?: CallbackHandler): Req; + parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; + patch(url: string, callback?: CallbackHandler): Req; + post(url: string, callback?: CallbackHandler): Req; propfind(url: string, callback?: CallbackHandler): Req; proppatch(url: string, callback?: CallbackHandler): Req; - unlock(url: string, callback?: CallbackHandler): Req; + purge(url: string, callback?: CallbackHandler): Req; + put(url: string, callback?: CallbackHandler): Req; report(url: string, callback?: CallbackHandler): Req; - mkactivity(url: string, callback?: CallbackHandler): Req; - checkout(url: string, callback?: CallbackHandler): Req; - merge(url: string, callback?: CallbackHandler): Req; - // m-search(url: string, callback?: CallbackHandler): Req; - notify(url: string, callback?: CallbackHandler): Req; - subscribe(url: string, callback?: CallbackHandler): Req; - unsubscribe(url: string, callback?: CallbackHandler): Req; - patch(url: string, callback?: CallbackHandler): Req; - search(url: string, callback?: CallbackHandler): Req; - connect(url: string, callback?: CallbackHandler): Req; - - parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; saveCookies(res: Response): void; - attachCookies(req: Req): void; + search(url: string, callback?: CallbackHandler): Req; + subscribe(url: string, callback?: CallbackHandler): Req; + trace(url: string, callback?: CallbackHandler): Req; + unlock(url: string, callback?: CallbackHandler): Req; + unsubscribe(url: string, callback?: CallbackHandler): Req; } interface Response extends NodeJS.ReadableStream { - text: string; - body: any; - files: any; - header: any; - type: string; - charset: string; - status: number; - statusType: number; - info: boolean; - ok: boolean; - redirect: boolean; - clientError: boolean; - serverError: boolean; - error: Error; accepted: boolean; - noContent: boolean; badRequest: boolean; - unauthorized: boolean; + body: any; + charset: string; + clientError: boolean; + error: Error; + files: any; + forbidden: boolean; + get(header: string): string; + header: any; + info: boolean; + noContent: boolean; notAcceptable: boolean; notFound: boolean; - forbidden: boolean; + ok: boolean; + redirect: boolean; + serverError: boolean; + status: number; + statusType: number; + text: string; + type: string; + unauthorized: boolean; xhr: XMLHttpRequest; - get(header: string): string; } - interface Request extends Promise /* extends NodeJS.WritableStream */ { + interface Request extends Promise { abort(): void; accept(type: string): this; attach(field: string, file: Blob | Buffer | fs.ReadStream | string, filename?: string): this; @@ -104,9 +102,10 @@ declare namespace request { end(callback?: CallbackHandler): this; field(name: string, val: string): this; get(field: string): string; - on(name: string, handler: (event: any) => void): this; on(name: 'error', handler: (err: any) => void): this; on(name: 'progress', handler: (event: ProgressEvent) => void): this; + on(name: string, handler: (event: any) => void): this; + parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; part(): this; pipe(stream: NodeJS.WritableStream, options?: object): stream.Writable; query(val: object | string): this; @@ -114,15 +113,14 @@ declare namespace request { responseType(type: string): this; send(data?: string | object): this; serialize(serializer: Serializer): this; - set(field: string, val: string): this; set(field: object): this; + set(field: string, val: string): this; timeout(ms: number | { deadline?: number, response?: number }): this; type(val: string): this; unset(field: string): this; use(fn: Plugin): this; withCredentials(): this; write(data: string | Buffer, encoding?: string): this; - parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; } type Plugin = (req: Request) => void; From c9b1f2158ee30a17a7bb1a7b49ecdb7650242a54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pap=20L=C5=91rinc?= Date: Fri, 30 Jun 2017 12:59:16 +0300 Subject: [PATCH 0090/1618] Fixed SuperAgentRequest methods' return type --- types/promisify-supertest/index.d.ts | 2 +- types/superagent/index.d.ts | 2 +- types/superagent/v2/index.d.ts | 2 +- types/supertest/index.d.ts | 6 +++--- types/supertest/supertest-tests.ts | 18 +++++++++--------- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/types/promisify-supertest/index.d.ts b/types/promisify-supertest/index.d.ts index 9f59afdb89..e887c6c915 100644 --- a/types/promisify-supertest/index.d.ts +++ b/types/promisify-supertest/index.d.ts @@ -19,7 +19,7 @@ declare namespace supertest { interface SuperTest extends superagent.SuperAgent { } - interface Test extends superagent.Request { + interface Test extends superagent.SuperAgentRequest { url: string; serverAddress(app: any, path: string): string; expect(status: number, callback?: CallbackHandler): this; diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index 2a48f26ee4..53ff034595 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -34,7 +34,7 @@ declare namespace request { serialize: { [type: string]: Serializer }; } - interface SuperAgent extends stream.Stream { + interface SuperAgent extends stream.Stream { attachCookies(req: Req): void; checkout(url: string, callback?: CallbackHandler): Req; connect(url: string, callback?: CallbackHandler): Req; diff --git a/types/superagent/v2/index.d.ts b/types/superagent/v2/index.d.ts index f598bbd4fe..626d3fb468 100644 --- a/types/superagent/v2/index.d.ts +++ b/types/superagent/v2/index.d.ts @@ -31,7 +31,7 @@ declare namespace request { agent(): SuperAgent; } - interface SuperAgent extends stream.Stream { + interface SuperAgent extends stream.Stream { get(url: string, callback?: CallbackHandler): Req; post(url: string, callback?: CallbackHandler): Req; put(url: string, callback?: CallbackHandler): Req; diff --git a/types/supertest/index.d.ts b/types/supertest/index.d.ts index 206c70defd..4607dd55f1 100644 --- a/types/supertest/index.d.ts +++ b/types/supertest/index.d.ts @@ -13,11 +13,11 @@ declare namespace supertest { interface Response extends superagent.Response { } - interface Request extends superagent.Request { + interface Request extends superagent.SuperAgentRequest { } type CallbackHandler = (err: any, res: Response) => void; - interface Test extends Request { + interface Test extends superagent.SuperAgentRequest { app?: any; url: string; serverAddress(app: any, path: string): string; @@ -34,7 +34,7 @@ declare namespace supertest { function agent(app?: any): SuperTest; - interface SuperTest extends superagent.SuperAgent { + interface SuperTest extends superagent.SuperAgent { } } diff --git a/types/supertest/supertest-tests.ts b/types/supertest/supertest-tests.ts index 5be5558e46..7241aac5c3 100644 --- a/types/supertest/supertest-tests.ts +++ b/types/supertest/supertest-tests.ts @@ -3,9 +3,10 @@ import * as supertest from 'supertest'; import * as express from 'express'; const app = express(); +const request: supertest.SuperTest = supertest(app); -supertest(app) - .get('/user') +(request + .get('/user') as supertest.Test) .expect('Content-Type', /json/) .expect('Content-Length', '20') .expect(201) @@ -14,7 +15,6 @@ supertest(app) }); // cookie scenario -const request = supertest(app); const agent = supertest.agent(); request .post('/login') @@ -22,7 +22,7 @@ request if (err) throw err; agent.saveCookies(res); - const req = request.get('/admin'); + const req = request.get('/admin') as supertest.Test; agent.attachCookies(req); req.expect(200, (err: any, res: supertest.Response) => { if (err) throw err; @@ -36,15 +36,15 @@ client .end((err: any, res: supertest.Response) => { if (err) throw err; - client.get('/admin') + (client.get('/admin') as supertest.Test) .expect(200, (err: any, res: supertest.Response) => { if (err) throw err; }); }); // functional expect -supertest(app) - .get('/') +(request + .get('/') as supertest.Test) .expect(hasPreviousAndNextKeys) .end((err: any, res: supertest.Response) => { if (err) throw err; @@ -56,8 +56,8 @@ function hasPreviousAndNextKeys(res: supertest.Response) { } // object expect -supertest(app) - .get('/') +(request + .get('/') as supertest.Test) .expect(200, { foo: 'bar' }) .end((err: any, res: supertest.Response) => { if (err) throw err; From 5d810e4179c2638a38d72419aac3986f43542992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pap=20L=C5=91rinc?= Date: Fri, 30 Jun 2017 13:02:32 +0300 Subject: [PATCH 0091/1618] Added retry method for superagent's Request --- types/superagent/index.d.ts | 1 + types/superagent/superagent-tests.ts | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index 53ff034595..a386894bfb 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -111,6 +111,7 @@ declare namespace request { query(val: object | string): this; redirects(n: number): this; responseType(type: string): this; + retry(count?: number): this; send(data?: string | object): this; serialize(serializer: Serializer): this; set(field: object): this; diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index 63ccd70f0e..ea4cbc503e 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -244,6 +244,16 @@ request .redirects(2) .end(callback); +// Retries, from https://github.com/visionmedia/superagent/commit/765de565c505abd221e7aa0765c5dd883a987ef1 +request + .get('/some.png') + .retry() + .timeout({ response: 9000, deadline: 10000 }); +request + .get('http://example.com/search') + .retry(2) + .end(callback); + (() => { const stream = fs.createWriteStream('path/to/my.json'); const req = request.get('/some.json'); From 49002c7cee2c0c9aada4968c8c0219ecf2814b8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pap=20L=C5=91rinc?= Date: Fri, 30 Jun 2017 13:06:26 +0300 Subject: [PATCH 0092/1618] Added https methods for superagent's Request --- types/superagent/index.d.ts | 4 ++++ types/superagent/superagent-tests.ts | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index a386894bfb..aa8d737f60 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -98,15 +98,19 @@ declare namespace request { attach(field: string, file: Blob | Buffer | fs.ReadStream | string, filename?: string): this; auth(user: string, name: string): this; buffer(val?: boolean): this; + ca(cert: Buffer): this; + cert(cert: Buffer | string): this; clearTimeout(): this; end(callback?: CallbackHandler): this; field(name: string, val: string): this; get(field: string): string; + key(cert: Buffer | string): this; on(name: 'error', handler: (err: any) => void): this; on(name: 'progress', handler: (event: ProgressEvent) => void): this; on(name: string, handler: (event: any) => void): this; parse(fn: (res: Response, callback: (err: Error | null, body: any) => void) => void): this; part(): this; + pfx(cert: Buffer | string): this; pipe(stream: NodeJS.WritableStream, options?: object): stream.Writable; query(val: object | string): this; redirects(n: number): this; diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index ea4cbc503e..e6fb27c078 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -345,3 +345,20 @@ request assert(res.xhr instanceof XMLHttpRequest); assert(res.xhr.response instanceof Blob); }); + +// HTTPS request, from: https://github.com/visionmedia/superagent/commit/6158efbf42cb93d77c1a70887284be783dd7dabe +const ca = fs.readFileSync('ca.cert.pem'); +const key = fs.readFileSync('key.pem'); +const cert = fs.readFileSync('cert.pem'); +request + .post('/secure') + .ca(ca) + .key(key) + .cert(cert) + .end(callback); + +const pfx = fs.readFileSync('cert.pfx'); +request + .post('/secure') + .pfx(pfx) + .end(callback); From 2a0c82d6c369cee0f355c8081bad9e534cf42c75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pap=20L=C5=91rinc?= Date: Fri, 30 Jun 2017 13:09:01 +0300 Subject: [PATCH 0093/1618] Added ok method for superagent's Request --- types/superagent/index.d.ts | 1 + types/superagent/superagent-tests.ts | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index aa8d737f60..c5da939daa 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -105,6 +105,7 @@ declare namespace request { field(name: string, val: string): this; get(field: string): string; key(cert: Buffer | string): this; + ok(callback: (res: Response) => boolean): this; on(name: 'error', handler: (err: any) => void): this; on(name: 'progress', handler: (event: ProgressEvent) => void): this; on(name: string, handler: (event: any) => void): this; diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index e6fb27c078..99214b2ccd 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -362,3 +362,11 @@ request .post('/secure') .pfx(pfx) .end(callback); + +// ok, from: https://github.com/visionmedia/superagent/commit/34533bbc29833889090847c45a82b0ea81b2f06d +request + .get('/404') + .ok(res => res.status < 500) + .then(response => { + // reads 404 page as a successful response + }); From b14503b9bada57e168861a57253a45f1771cbbc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pap=20L=C5=91rinc?= Date: Fri, 30 Jun 2017 13:14:06 +0300 Subject: [PATCH 0094/1618] Added paplorinc to the list of contributors --- types/superagent/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index c5da939daa..4e9cdf4812 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/visionmedia/superagent // Definitions by: Nico Zelaya // Michael Ledin +// Pap Lőrinc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 From c8852512f9e677e2ba1763d728176dbcc8a53926 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 13:48:46 +0200 Subject: [PATCH 0095/1618] removed empty interfaces --- types/fm-websync/index.d.ts | 90 ++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 32 deletions(-) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index 887d63039f..90cf5268e6 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -39,7 +39,7 @@ declare namespace fm /** * The callback to invoke after onSuccess or onFailure. See initializeCompleteArgs for callback argument details. */ - onComplete?: ( args: initializeCompleteArgs ) => void; + onComplete?: ( args: baseArgs ) => void; /** * The callback to invoke if the initialize fails. Defaults to an alert of the error. See initializeFailureArgs for callback argument details. @@ -49,7 +49,7 @@ declare namespace fm /** * The callback to invoke if the initialize succeeds. See initializeSuccessArgs for callback argument details. */ - onSuccess?: ( args: initializeSuccessArgs ) => void; + onSuccess?: ( args: baseArgs ) => void; /** * Whether or not to suppress the alerting of a failure if the client is already initialized. @@ -124,7 +124,9 @@ declare namespace fm } interface baseArgs - {} + { + [key: string]: any; + } interface baseRequestConfig { @@ -231,24 +233,16 @@ declare namespace fm */ onSuccess?: ( args: subscribeSuccessArgs ) => void; } - - interface baseCompleteArgs extends baseResponseArgs - { - } - - interface initializeCompleteArgs extends baseArgs - { - } interface initializeFailureArgs extends baseArgs { - } - - interface initializeSuccessArgs extends baseArgs - { + /** + * The error generated while initializing. + */ + error: string; } - interface subscribeSuccessArgs extends baseSuccessArgs + interface subscribeSuccessArgs extends baseResponseArgs { /** * The channel to which the client was subscribed. Must start with a forward slash (/). @@ -271,7 +265,7 @@ declare namespace fm subscribedClients: fm.websync.subscribedClient[]; } - interface subscribeCompleteArgs extends baseCompleteArgs + interface subscribeCompleteArgs extends baseResponseArgs { /** * Whether the call to client.subscribe was triggered by a reconnection after network failure. @@ -318,11 +312,6 @@ declare namespace fm timestamp: Date; } - interface baseSuccessArgs extends baseResponseArgs - { - - } - interface connectSuccessArgs extends baseResponseArgs { /** @@ -388,7 +377,7 @@ declare namespace fm publishingClient: fm.websync.publishingClient; } - interface subscribersChangeArgs extends baseSuccessArgs + interface subscribersChangeArgs extends baseResponseArgs { /** * The details of the change that occurred. @@ -445,29 +434,58 @@ declare namespace fm /** * The callback to invoke after onSuccess or onFailure. See disconnectCompleteArgs for callback argument details. */ - onComplete: ( args: disconnectCompleteArgs ) => void; + onComplete?: ( args: baseResponseArgs ) => void; /** * The callback to invoke if the disconnect fails. See disconnectFailureArgs for callback argument details. */ - onFailure: ( args: disconnectFailureArgs ) => void; + onFailure?: ( args: baseFailureArgs ) => void; /** * The callback to invoke if the disconnect succeeds. See disconnectSuccessArgs for callback argument details. */ - onSuccess: ( args: disconnectSuccessArgs ) => void; + onSuccess?: ( args: baseResponseArgs ) => void; } - interface disconnectCompleteArgs extends baseCompleteArgs + interface unsubscribeSuccessArgs extends baseResponseArgs { + /** + * The channel from which the client was unsubscribed. Must start with a forward slash (/). + */ + channel: string; + + /** + * The channels from which the client was unsubscribed. Each must start with a forward slash (/). + */ + channels: string[]; } - interface disconnectFailureArgs extends baseFailureArgs - { - } - - interface disconnectSuccessArgs extends baseSuccessArgs + interface unsubscribeConfig extends baseRequestConfig { + /** + * The channel from which the client should be unsubscribed. Must start with a forward slash (/). Overrides channels. + */ + channel: string; + + /** + * The channels from which the client should be unsubscribed. Each must start with a forward slash (/). Overrides channel. + */ + channels: String[]; + + /** + * The callback to invoke after onSuccess or onFailure. See unsubscribeCompleteArgs for callback argument details. + */ + onComplete: ( args: baseResponseArgs ) => void; + + /** + * The callback to invoke if the unsubscribe fails. See unsubscribeFailureArgs for callback argument details. + */ + onFailure: ( args: baseFailureArgs ) => void; + + /** + * The callback to invoke if the unsubscribe succeeds. See unsubscribeSuccessArgs for callback argument details. + */ + onSuccess: ( args: unsubscribeSuccessArgs ) => void; } export class client @@ -502,6 +520,14 @@ declare namespace fm * including any modifications made on the server. */ subscribe( config: subscribeConfig ): client; + + /** + * Unsubscribes the client from receiving messages on one or more channels. + * When the unsubscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the unsubscribed channel(s), + * including any modifications made on the server. + * @param config + */ + unsubscribe( config: unsubscribeConfig ): client; } } } From 780b002919ba79572c308f063378d498c2b02c60 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 14:26:21 +0200 Subject: [PATCH 0096/1618] trimmed trailing whitespaces --- types/fm-websync/index.d.ts | 132 ++++++++++++++++++------------------ 1 file changed, 66 insertions(+), 66 deletions(-) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index 90cf5268e6..686554d62e 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -19,58 +19,58 @@ declare namespace fm /** * The amount of time in milliseconds to add to the delay between each reconnect attempt in the event of network failure. Defaults to 3000 (3 seconds). - */ - + */ + backoffInterval?: number; - + /** * The URL of the HTML frame to be used with HTML5 postMessage for cross-domain environments. Must have the same domain as requestUrl. * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server * ClientHandler registered in web.config with "frame" added to the query. */ clientFrameUrl?: string; - + /** * The domain key to send with each request. If using WebSync On-Demand, this should be set to the public or private API key specified in the Frozen Mountain Portal. * If using WebSync Server, this should be used only if grouping connections. Defaults to "11111111-1111-1111-1111-111111111111". - */ + */ key?: string; - + /** * The callback to invoke after onSuccess or onFailure. See initializeCompleteArgs for callback argument details. */ onComplete?: ( args: baseArgs ) => void; - + /** * The callback to invoke if the initialize fails. Defaults to an alert of the error. See initializeFailureArgs for callback argument details. - */ + */ onFailure?: ( args: initializeFailureArgs ) => void; - + /** * The callback to invoke if the initialize succeeds. See initializeSuccessArgs for callback argument details. */ onSuccess?: ( args: baseArgs ) => void; - + /** * Whether or not to suppress the alerting of a failure if the client is already initialized. */ quiet?: boolean; - + /** * The URL of the WebSync request handler. This URL typically ends with request.ashx. Must have the same domain as clientFrameUrl. * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the * WebSync Server RequestHandler registered in web.config. */ requestUrl?: string; - + /** * The number of times to retry a request in the event of network failure before considering it failed and invoking the corresponding OnFailure callback. Defaults to 3. */ retries?: number; - + /** * The URLs to use for streaming connections. Three properties are available: - * + * * requestUrl: string * Same as the root requestUrl parameter, but used for streaming connections. Must have the same domain as stream.clientFrameUrl. * Defaults to a dynamically generated URL based on the host of the client script URL (or the streamHost web.config attribute, if specified) and the path to the @@ -83,25 +83,25 @@ declare namespace fm * Same as the root timeout parameter, but used for streaming connections. Defaults to the root timeout + 25000 (25 seconds). */ stream? : any; - + /** * The number of milliseconds to wait for a standard request to return a response before it is cancelled and a new attempt is made. Defaults to 15000 (15 seconds). */ timeout?: number; - + /** * The token sent with every client request identifying it for query-based load balancing. Defaults to the current timestamp. */ - + token?: string; - + /** * An object specifying URLs to be used for specific client methods. Overrides initializeConfig.requestUrl for the specified method type, but can be overridden * by the requestUrl specified in individual method configurations. - * + * * connect: string * The URL to use for all client.connect requests. - * + * * bind: string * The URL to use for all client.bind requests. * @@ -122,7 +122,7 @@ declare namespace fm */ urls?: any; } - + interface baseArgs { [key: string]: any; @@ -134,18 +134,18 @@ declare namespace fm * Extra meta data to associate with the request/response. */ meta?: any; - + /** * The URL of the proxy to use for this request. */ requestUrl?: string; - + /** * Whether to ignore errors when parsing the server response. If true, any errors thrown while parsing the JSON response received from the server will be ignored. * Defaults to false. */ suppressErrors?: boolean; - + /** * Whether the request should be executed asynchronously. If true, the request will be executed synchronously if supported by the browser; otherwise, * it will be executed asynchronously. All browsers support synchronous requests if the request URL is the same domain as the page. Synchronous requests @@ -163,9 +163,9 @@ declare namespace fm /** * The callback to invoke if the connect fails. Defaults to an alert of the error. See connectFailureArgs for callback argument details. - */ + */ onFailure?: ( args: connectFailureArgs ) => void; - + /** * The callback to invoke if the streaming connection fails. See streamFailureArgs for callback argument details. * This method will be invoked if (a) the connection was lost, automatic retries succeeded, but the client had idled on the server (and so needs to reconnect), @@ -176,22 +176,22 @@ declare namespace fm * With the exception of UI updates, invocations of this callback with willReconnect set to true can be ignored. */ onStreamFailure?: ( args: streamFailureArgs ) => void; - + /** * The callback to invoke if the connect succeeds. See connectSuccessArgs for callback argument details. */ onSuccess?: ( args: connectSuccessArgs ) => void; - + /** * The callback to invoke when a message is received on a channel that has no local callback specified to handle it. See receiveArgs for callback argument details. * This can occur if (a) a client is manually subscribed to a channel by the server or (b) a client subscribed to a channel and then manually removed the local callback using client. */ onUnhandledReceive?: ( args: receiveArgs ) => void; - + /** * Whether to always attempt to stay connected in the event of network failure. If true, the client will continually reconnect, even after exhausting the specified number * of retries specified by initializeConfig.retries. If false, the client will stop reconnecting if all retry attempts fail. - */ + */ stayConnected?: boolean; } @@ -201,39 +201,39 @@ declare namespace fm * The channel to which the client should be subscribed. Must start with a forward slash (/). Overrides channels. */ channel?: string; - + /** * The channels to which the client should be subscribed. Each must start with a forward slash (/). Overrides channel. */ channels?: string[]; - + /** * The callback to invoke after onSuccess or onFailure. See subscribeCompleteArgs for callback argument details. */ onComplete?: ( args: subscribeCompleteArgs ) => void; - + /** * (OptionalThe callback to invoke if the subscribe fails. See subscribeFailureArgs for callback argument details. */ onFailure?: ( args: subscribeFailureArgs ) => void; - + /** * The callback to invoke when data is received on the channel(s). See receiveArgs for callback argument details. */ onReceive?: ( args: receiveArgs ) => void; - + /** * Subscribers extension. The callback to invoke when a subscribers change notification is received (i.e. when a client subscribes to or unsubscribes from the channel(s)). * The current subscribe request will trigger this callback. See subscribersChangeArgs for callback argument details. */ onSubscribersChange?: ( args: subscribersChangeArgs ) => void; - + /** * The callback to invoke if the subscribe succeeds. See subscribeSuccessArgs for callback argument details. */ onSuccess?: ( args: subscribeSuccessArgs ) => void; } - + interface initializeFailureArgs extends baseArgs { /** @@ -246,19 +246,19 @@ declare namespace fm { /** * The channel to which the client was subscribed. Must start with a forward slash (/). - */ + */ channel: string; - + /** * The channels to which the client was subscribed. Each must start with a forward slash (/). */ channels: string[]; - + /** * Whether the call to client.subscribe was triggered by a reconnection after network failure. */ isResubscribe: boolean; - + /** * Subscribers extension. The active subscribed clients on the just-subscribed channel(s). */ @@ -295,17 +295,17 @@ declare namespace fm * The singleton client. */ client: fm.websync.client; - + /** * The ID of the singleton client. */ clientId: string; - + /** * Extra meta data associated with the request/response. */ meta: any; - + /** * The date/time the message was processed on the server. */ @@ -331,7 +331,7 @@ declare namespace fm * Whether the call to client.connect was triggered by a reconnection after network failure. */ isReconnect: boolean; - + /** * Whether or not to reconnect automatically after this callback has finished execution. */ @@ -365,12 +365,12 @@ declare namespace fm * The channel over which the data was published. */ channel: string; - + /** * The published data. */ data: any; - + /** * Details about the client publishing the data. */ @@ -383,7 +383,7 @@ declare namespace fm * The details of the change that occurred. */ change?: fm.websync.subscribersChange - + /** * The channel on which the change occurred. */ @@ -396,7 +396,7 @@ declare namespace fm * The publishing client's bound records. */ boundRecords: any; - + /** * The publishing client's unique identifier. */ @@ -422,7 +422,7 @@ declare namespace fm * The subscribed client's bound records. */ boundRecords: any; - + /** * The subscribed client's unique identifier. */ @@ -435,12 +435,12 @@ declare namespace fm * The callback to invoke after onSuccess or onFailure. See disconnectCompleteArgs for callback argument details. */ onComplete?: ( args: baseResponseArgs ) => void; - + /** * The callback to invoke if the disconnect fails. See disconnectFailureArgs for callback argument details. */ onFailure?: ( args: baseFailureArgs ) => void; - + /** * The callback to invoke if the disconnect succeeds. See disconnectSuccessArgs for callback argument details. */ @@ -453,7 +453,7 @@ declare namespace fm * The channel from which the client was unsubscribed. Must start with a forward slash (/). */ channel: string; - + /** * The channels from which the client was unsubscribed. Each must start with a forward slash (/). */ @@ -465,27 +465,27 @@ declare namespace fm /** * The channel from which the client should be unsubscribed. Must start with a forward slash (/). Overrides channels. */ - channel: string; - + channel?: string; + /** * The channels from which the client should be unsubscribed. Each must start with a forward slash (/). Overrides channel. */ - channels: String[]; - + channels?: string[]; + /** * The callback to invoke after onSuccess or onFailure. See unsubscribeCompleteArgs for callback argument details. */ - onComplete: ( args: baseResponseArgs ) => void; - + onComplete?: ( args: baseResponseArgs ) => void; + /** * The callback to invoke if the unsubscribe fails. See unsubscribeFailureArgs for callback argument details. */ - onFailure: ( args: baseFailureArgs ) => void; - + onFailure?: ( args: baseFailureArgs ) => void; + /** * The callback to invoke if the unsubscribe succeeds. See unsubscribeSuccessArgs for callback argument details. */ - onSuccess: ( args: unsubscribeSuccessArgs ) => void; + onSuccess?: ( args: unsubscribeSuccessArgs ) => void; } export class client @@ -495,13 +495,13 @@ declare namespace fm * While this method will typically run asychronously, the WebSync client is designed to be used without (much) consideration for its asynchronous nature. * To that end, any calls to methods that require an active connection, like bind, subscribe and publish, will be queued automatically and executed once this * method has completed successfully. - * - * @param connectConfig + * + * @param connectConfig */ connect( config: connectConfig ): client; /** - * + * * @param config Takes down a streaming connection to the server and unsubscribes the client. * After the disconnect completes successfully, any further calls to methods that require an active connection, like bind, subscribe and publish, will be queued * automatically and executed only if/when the client reconnects. @@ -525,7 +525,7 @@ declare namespace fm * Unsubscribes the client from receiving messages on one or more channels. * When the unsubscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the unsubscribed channel(s), * including any modifications made on the server. - * @param config + * @param config */ unsubscribe( config: unsubscribeConfig ): client; } From 16f0645371f3fa47886c33e89089ba98b164bd9d Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 14:27:11 +0200 Subject: [PATCH 0097/1618] beautifier --- types/fm-websync/index.d.ts | 172 +++++++++++++++--------------------- 1 file changed, 73 insertions(+), 99 deletions(-) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index 686554d62e..c69dea19c4 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -3,70 +3,67 @@ // Definitions by: Markus Mauch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace fm -{ - export namespace websync - { - interface initializeConfig - { +declare namespace fm { + export namespace websync { + interface initializeConfig { /** * If set to true, an asynchronous disconnect request will be launched when the page unloads. If set to false, no automatic disconnection will be attempted. * If set to an object, then a disconnect request will be launched when the page unloads using the object as the disconnect configuration. * (See disconnectConfig for details.) Note that automatic disconnects are a best-effort. The only way to guarantee success is to execute the disconnect synchronously * and target a request URL on the same domain as the page ({ sync: true, requestUrl: '...relative path.../request.ashx' }). Defaults to false. */ - autoDisconnect?: boolean; + autoDisconnect ? : boolean; /** * The amount of time in milliseconds to add to the delay between each reconnect attempt in the event of network failure. Defaults to 3000 (3 seconds). */ - backoffInterval?: number; + backoffInterval ? : number; /** * The URL of the HTML frame to be used with HTML5 postMessage for cross-domain environments. Must have the same domain as requestUrl. * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server * ClientHandler registered in web.config with "frame" added to the query. */ - clientFrameUrl?: string; + clientFrameUrl ? : string; /** * The domain key to send with each request. If using WebSync On-Demand, this should be set to the public or private API key specified in the Frozen Mountain Portal. * If using WebSync Server, this should be used only if grouping connections. Defaults to "11111111-1111-1111-1111-111111111111". */ - key?: string; + key ? : string; /** * The callback to invoke after onSuccess or onFailure. See initializeCompleteArgs for callback argument details. */ - onComplete?: ( args: baseArgs ) => void; + onComplete ? : (args: baseArgs) => void; /** * The callback to invoke if the initialize fails. Defaults to an alert of the error. See initializeFailureArgs for callback argument details. */ - onFailure?: ( args: initializeFailureArgs ) => void; + onFailure ? : (args: initializeFailureArgs) => void; /** * The callback to invoke if the initialize succeeds. See initializeSuccessArgs for callback argument details. */ - onSuccess?: ( args: baseArgs ) => void; + onSuccess ? : (args: baseArgs) => void; /** * Whether or not to suppress the alerting of a failure if the client is already initialized. */ - quiet?: boolean; + quiet ? : boolean; /** * The URL of the WebSync request handler. This URL typically ends with request.ashx. Must have the same domain as clientFrameUrl. * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the * WebSync Server RequestHandler registered in web.config. */ - requestUrl?: string; + requestUrl ? : string; /** * The number of times to retry a request in the event of network failure before considering it failed and invoking the corresponding OnFailure callback. Defaults to 3. */ - retries?: number; + retries ? : number; /** * The URLs to use for streaming connections. Three properties are available: @@ -82,18 +79,18 @@ declare namespace fm * timeout: number * Same as the root timeout parameter, but used for streaming connections. Defaults to the root timeout + 25000 (25 seconds). */ - stream? : any; + stream ? : any; /** * The number of milliseconds to wait for a standard request to return a response before it is cancelled and a new attempt is made. Defaults to 15000 (15 seconds). */ - timeout?: number; + timeout ? : number; /** * The token sent with every client request identifying it for query-based load balancing. Defaults to the current timestamp. */ - token?: string; + token ? : string; /** * An object specifying URLs to be used for specific client methods. Overrides initializeConfig.requestUrl for the specified method type, but can be overridden @@ -120,51 +117,48 @@ declare namespace fm * disconnect: string * The URL to use for all client.disconnect requests. */ - urls?: any; + urls ? : any; } - interface baseArgs - { + interface baseArgs { [key: string]: any; } - interface baseRequestConfig - { + interface baseRequestConfig { /** * Extra meta data to associate with the request/response. */ - meta?: any; + meta ? : any; /** * The URL of the proxy to use for this request. */ - requestUrl?: string; + requestUrl ? : string; /** * Whether to ignore errors when parsing the server response. If true, any errors thrown while parsing the JSON response received from the server will be ignored. * Defaults to false. */ - suppressErrors?: boolean; + suppressErrors ? : boolean; /** * Whether the request should be executed asynchronously. If true, the request will be executed synchronously if supported by the browser; otherwise, * it will be executed asynchronously. All browsers support synchronous requests if the request URL is the same domain as the page. Synchronous requests * are not supported in IE6 and IE7 for cross-domain environments. Defaults to false. */ - sync?: boolean; + sync ? : boolean; } - interface connectConfig extends baseRequestConfig - { + interface connectConfig extends baseRequestConfig { /** * The callback to invoke after onSuccess or onFailure. See connectCompleteArgs for callback argument details. */ - onComplete?: ( args: connectCompleteArgs ) => void; + onComplete ? : (args: connectCompleteArgs) => void; /** * The callback to invoke if the connect fails. Defaults to an alert of the error. See connectFailureArgs for callback argument details. */ - onFailure?: ( args: connectFailureArgs ) => void; + onFailure ? : (args: connectFailureArgs) => void; /** * The callback to invoke if the streaming connection fails. See streamFailureArgs for callback argument details. @@ -175,75 +169,72 @@ declare namespace fm * If the reconnect fails, the callback specified by onFailure will be invoked with isReconnect set to false. * With the exception of UI updates, invocations of this callback with willReconnect set to true can be ignored. */ - onStreamFailure?: ( args: streamFailureArgs ) => void; + onStreamFailure ? : (args: streamFailureArgs) => void; /** * The callback to invoke if the connect succeeds. See connectSuccessArgs for callback argument details. */ - onSuccess?: ( args: connectSuccessArgs ) => void; + onSuccess ? : (args: connectSuccessArgs) => void; /** * The callback to invoke when a message is received on a channel that has no local callback specified to handle it. See receiveArgs for callback argument details. * This can occur if (a) a client is manually subscribed to a channel by the server or (b) a client subscribed to a channel and then manually removed the local callback using client. */ - onUnhandledReceive?: ( args: receiveArgs ) => void; + onUnhandledReceive ? : (args: receiveArgs) => void; /** * Whether to always attempt to stay connected in the event of network failure. If true, the client will continually reconnect, even after exhausting the specified number * of retries specified by initializeConfig.retries. If false, the client will stop reconnecting if all retry attempts fail. */ - stayConnected?: boolean; + stayConnected ? : boolean; } - interface subscribeConfig extends baseRequestConfig - { + interface subscribeConfig extends baseRequestConfig { /** * The channel to which the client should be subscribed. Must start with a forward slash (/). Overrides channels. */ - channel?: string; + channel ? : string; /** * The channels to which the client should be subscribed. Each must start with a forward slash (/). Overrides channel. */ - channels?: string[]; + channels ? : string[]; /** * The callback to invoke after onSuccess or onFailure. See subscribeCompleteArgs for callback argument details. */ - onComplete?: ( args: subscribeCompleteArgs ) => void; + onComplete ? : (args: subscribeCompleteArgs) => void; /** * (OptionalThe callback to invoke if the subscribe fails. See subscribeFailureArgs for callback argument details. */ - onFailure?: ( args: subscribeFailureArgs ) => void; + onFailure ? : (args: subscribeFailureArgs) => void; /** * The callback to invoke when data is received on the channel(s). See receiveArgs for callback argument details. */ - onReceive?: ( args: receiveArgs ) => void; + onReceive ? : (args: receiveArgs) => void; /** * Subscribers extension. The callback to invoke when a subscribers change notification is received (i.e. when a client subscribes to or unsubscribes from the channel(s)). * The current subscribe request will trigger this callback. See subscribersChangeArgs for callback argument details. */ - onSubscribersChange?: ( args: subscribersChangeArgs ) => void; + onSubscribersChange ? : (args: subscribersChangeArgs) => void; /** * The callback to invoke if the subscribe succeeds. See subscribeSuccessArgs for callback argument details. */ - onSuccess?: ( args: subscribeSuccessArgs ) => void; + onSuccess ? : (args: subscribeSuccessArgs) => void; } - interface initializeFailureArgs extends baseArgs - { + interface initializeFailureArgs extends baseArgs { /** * The error generated while initializing. */ error: string; } - interface subscribeSuccessArgs extends baseResponseArgs - { + interface subscribeSuccessArgs extends baseResponseArgs { /** * The channel to which the client was subscribed. Must start with a forward slash (/). */ @@ -265,32 +256,28 @@ declare namespace fm subscribedClients: fm.websync.subscribedClient[]; } - interface subscribeCompleteArgs extends baseResponseArgs - { + interface subscribeCompleteArgs extends baseResponseArgs { /** * Whether the call to client.subscribe was triggered by a reconnection after network failure. */ isResubscribe: boolean; } - interface subscribeFailureArgs extends baseFailureArgs - { + interface subscribeFailureArgs extends baseFailureArgs { /** * Whether the call to client.subscribe was triggered by a reconnection after network failure. */ isResubscribe: boolean; } - interface baseFailureArgs extends baseResponseArgs - { + interface baseFailureArgs extends baseResponseArgs { /** * The error generated while completing the request. */ error: string; } - interface baseResponseArgs extends baseArgs - { + interface baseResponseArgs extends baseArgs { /** * The singleton client. */ @@ -312,16 +299,14 @@ declare namespace fm timestamp: Date; } - interface connectSuccessArgs extends baseResponseArgs - { + interface connectSuccessArgs extends baseResponseArgs { /** * Whether the call to client.connect was triggered by a reconnection after network failure. */ isReconnect: boolean; } - interface connectFailureArgs extends baseResponseArgs - { + interface connectFailureArgs extends baseResponseArgs { /** * The error generated while completing the request. */ @@ -338,8 +323,7 @@ declare namespace fm reconnect: boolean; } - interface streamFailureArgs extends baseResponseArgs - { + interface streamFailureArgs extends baseResponseArgs { /** * The error generated while completing the request. */ @@ -351,16 +335,14 @@ declare namespace fm willReconnect: boolean; } - interface connectCompleteArgs extends baseResponseArgs - { + interface connectCompleteArgs extends baseResponseArgs { /** * Whether the call to client.connect was triggered by a reconnection after network failure. */ isReconnect: boolean; } - interface receiveArgs extends baseResponseArgs - { + interface receiveArgs extends baseResponseArgs { /** * The channel over which the data was published. */ @@ -377,21 +359,19 @@ declare namespace fm publishingClient: fm.websync.publishingClient; } - interface subscribersChangeArgs extends baseResponseArgs - { + interface subscribersChangeArgs extends baseResponseArgs { /** * The details of the change that occurred. */ - change?: fm.websync.subscribersChange + change ? : fm.websync.subscribersChange /** * The channel on which the change occurred. */ - channel?: string; + channel ? : string; } - interface publishingClient - { + interface publishingClient { /** * The publishing client's bound records. */ @@ -403,12 +383,11 @@ declare namespace fm id: string; } - interface subscribersChange - { + interface subscribersChange { /** * The clients who subscribed to or unsubscribed from the channel. */ - clients : fm.websync.subscribedClient[]; + clients: fm.websync.subscribedClient[]; /** * The type of the change, either "subscribe" or "unsubscribe". @@ -416,8 +395,7 @@ declare namespace fm type: string; } - interface subscribedClient - { + interface subscribedClient { /** * The subscribed client's bound records. */ @@ -429,26 +407,24 @@ declare namespace fm id: string; } - interface disconnectConfig extends baseRequestConfig - { + interface disconnectConfig extends baseRequestConfig { /** * The callback to invoke after onSuccess or onFailure. See disconnectCompleteArgs for callback argument details. */ - onComplete?: ( args: baseResponseArgs ) => void; + onComplete ? : (args: baseResponseArgs) => void; /** * The callback to invoke if the disconnect fails. See disconnectFailureArgs for callback argument details. */ - onFailure?: ( args: baseFailureArgs ) => void; + onFailure ? : (args: baseFailureArgs) => void; /** * The callback to invoke if the disconnect succeeds. See disconnectSuccessArgs for callback argument details. */ - onSuccess?: ( args: baseResponseArgs ) => void; + onSuccess ? : (args: baseResponseArgs) => void; } - interface unsubscribeSuccessArgs extends baseResponseArgs - { + interface unsubscribeSuccessArgs extends baseResponseArgs { /** * The channel from which the client was unsubscribed. Must start with a forward slash (/). */ @@ -460,36 +436,34 @@ declare namespace fm channels: string[]; } - interface unsubscribeConfig extends baseRequestConfig - { + interface unsubscribeConfig extends baseRequestConfig { /** * The channel from which the client should be unsubscribed. Must start with a forward slash (/). Overrides channels. */ - channel?: string; + channel ? : string; /** * The channels from which the client should be unsubscribed. Each must start with a forward slash (/). Overrides channel. */ - channels?: string[]; + channels ? : string[]; /** * The callback to invoke after onSuccess or onFailure. See unsubscribeCompleteArgs for callback argument details. */ - onComplete?: ( args: baseResponseArgs ) => void; + onComplete ? : (args: baseResponseArgs) => void; /** * The callback to invoke if the unsubscribe fails. See unsubscribeFailureArgs for callback argument details. */ - onFailure?: ( args: baseFailureArgs ) => void; + onFailure ? : (args: baseFailureArgs) => void; /** * The callback to invoke if the unsubscribe succeeds. See unsubscribeSuccessArgs for callback argument details. */ - onSuccess?: ( args: unsubscribeSuccessArgs ) => void; + onSuccess ? : (args: unsubscribeSuccessArgs) => void; } - export class client - { + export class client { /** * Sets up and maintains a streaming connection to the server. * While this method will typically run asychronously, the WebSync client is designed to be used without (much) consideration for its asynchronous nature. @@ -498,7 +472,7 @@ declare namespace fm * * @param connectConfig */ - connect( config: connectConfig ): client; + connect(config: connectConfig): client; /** * @@ -506,20 +480,20 @@ declare namespace fm * After the disconnect completes successfully, any further calls to methods that require an active connection, like bind, subscribe and publish, will be queued * automatically and executed only if/when the client reconnects. */ - disconnect( config: disconnectConfig ): client; + disconnect(config: disconnectConfig): client; /** * Initializes the client according to the specified configuration. * This method must always be called first. While is always executes synchronously, callbacks are allowed for the purposes of method chaining. */ - static initialize( config: initializeConfig ): client; + static initialize(config: initializeConfig): client; /** * Subscribes the client to receive messages on one or more channels. * When the subscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the subscribed channel(s), * including any modifications made on the server. */ - subscribe( config: subscribeConfig ): client; + subscribe(config: subscribeConfig): client; /** * Unsubscribes the client from receiving messages on one or more channels. @@ -527,7 +501,7 @@ declare namespace fm * including any modifications made on the server. * @param config */ - unsubscribe( config: unsubscribeConfig ): client; + unsubscribe(config: unsubscribeConfig): client; } } } From 721c8f294a9130c9169f2a5ef2bb0ad4f1dd6cd7 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 14:27:54 +0200 Subject: [PATCH 0098/1618] beautify --- types/fm-websync/index.d.ts | 82 ++++++++++++++++++------------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index c69dea19c4..6e3d221ed0 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -12,58 +12,58 @@ declare namespace fm { * (See disconnectConfig for details.) Note that automatic disconnects are a best-effort. The only way to guarantee success is to execute the disconnect synchronously * and target a request URL on the same domain as the page ({ sync: true, requestUrl: '...relative path.../request.ashx' }). Defaults to false. */ - autoDisconnect ? : boolean; + autoDisconnect?: boolean; /** * The amount of time in milliseconds to add to the delay between each reconnect attempt in the event of network failure. Defaults to 3000 (3 seconds). */ - backoffInterval ? : number; + backoffInterval?: number; /** * The URL of the HTML frame to be used with HTML5 postMessage for cross-domain environments. Must have the same domain as requestUrl. * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the WebSync Server * ClientHandler registered in web.config with "frame" added to the query. */ - clientFrameUrl ? : string; + clientFrameUrl?: string; /** * The domain key to send with each request. If using WebSync On-Demand, this should be set to the public or private API key specified in the Frozen Mountain Portal. * If using WebSync Server, this should be used only if grouping connections. Defaults to "11111111-1111-1111-1111-111111111111". */ - key ? : string; + key?: string; /** * The callback to invoke after onSuccess or onFailure. See initializeCompleteArgs for callback argument details. */ - onComplete ? : (args: baseArgs) => void; + onComplete?: (args: baseArgs) => void; /** * The callback to invoke if the initialize fails. Defaults to an alert of the error. See initializeFailureArgs for callback argument details. */ - onFailure ? : (args: initializeFailureArgs) => void; + onFailure?: (args: initializeFailureArgs) => void; /** * The callback to invoke if the initialize succeeds. See initializeSuccessArgs for callback argument details. */ - onSuccess ? : (args: baseArgs) => void; + onSuccess?: (args: baseArgs) => void; /** * Whether or not to suppress the alerting of a failure if the client is already initialized. */ - quiet ? : boolean; + quiet?: boolean; /** * The URL of the WebSync request handler. This URL typically ends with request.ashx. Must have the same domain as clientFrameUrl. * Defaults to a dynamically generated URL based on the host of the client script URL (or the host web.config attribute, if specified) and the path to the * WebSync Server RequestHandler registered in web.config. */ - requestUrl ? : string; + requestUrl?: string; /** * The number of times to retry a request in the event of network failure before considering it failed and invoking the corresponding OnFailure callback. Defaults to 3. */ - retries ? : number; + retries?: number; /** * The URLs to use for streaming connections. Three properties are available: @@ -79,18 +79,18 @@ declare namespace fm { * timeout: number * Same as the root timeout parameter, but used for streaming connections. Defaults to the root timeout + 25000 (25 seconds). */ - stream ? : any; + stream?: any; /** * The number of milliseconds to wait for a standard request to return a response before it is cancelled and a new attempt is made. Defaults to 15000 (15 seconds). */ - timeout ? : number; + timeout?: number; /** * The token sent with every client request identifying it for query-based load balancing. Defaults to the current timestamp. */ - token ? : string; + token?: string; /** * An object specifying URLs to be used for specific client methods. Overrides initializeConfig.requestUrl for the specified method type, but can be overridden @@ -117,7 +117,7 @@ declare namespace fm { * disconnect: string * The URL to use for all client.disconnect requests. */ - urls ? : any; + urls?: any; } interface baseArgs { @@ -128,37 +128,37 @@ declare namespace fm { /** * Extra meta data to associate with the request/response. */ - meta ? : any; + meta?: any; /** * The URL of the proxy to use for this request. */ - requestUrl ? : string; + requestUrl?: string; /** * Whether to ignore errors when parsing the server response. If true, any errors thrown while parsing the JSON response received from the server will be ignored. * Defaults to false. */ - suppressErrors ? : boolean; + suppressErrors?: boolean; /** * Whether the request should be executed asynchronously. If true, the request will be executed synchronously if supported by the browser; otherwise, * it will be executed asynchronously. All browsers support synchronous requests if the request URL is the same domain as the page. Synchronous requests * are not supported in IE6 and IE7 for cross-domain environments. Defaults to false. */ - sync ? : boolean; + sync?: boolean; } interface connectConfig extends baseRequestConfig { /** * The callback to invoke after onSuccess or onFailure. See connectCompleteArgs for callback argument details. */ - onComplete ? : (args: connectCompleteArgs) => void; + onComplete?: (args: connectCompleteArgs) => void; /** * The callback to invoke if the connect fails. Defaults to an alert of the error. See connectFailureArgs for callback argument details. */ - onFailure ? : (args: connectFailureArgs) => void; + onFailure?: (args: connectFailureArgs) => void; /** * The callback to invoke if the streaming connection fails. See streamFailureArgs for callback argument details. @@ -169,62 +169,62 @@ declare namespace fm { * If the reconnect fails, the callback specified by onFailure will be invoked with isReconnect set to false. * With the exception of UI updates, invocations of this callback with willReconnect set to true can be ignored. */ - onStreamFailure ? : (args: streamFailureArgs) => void; + onStreamFailure?: (args: streamFailureArgs) => void; /** * The callback to invoke if the connect succeeds. See connectSuccessArgs for callback argument details. */ - onSuccess ? : (args: connectSuccessArgs) => void; + onSuccess?: (args: connectSuccessArgs) => void; /** * The callback to invoke when a message is received on a channel that has no local callback specified to handle it. See receiveArgs for callback argument details. * This can occur if (a) a client is manually subscribed to a channel by the server or (b) a client subscribed to a channel and then manually removed the local callback using client. */ - onUnhandledReceive ? : (args: receiveArgs) => void; + onUnhandledReceive?: (args: receiveArgs) => void; /** * Whether to always attempt to stay connected in the event of network failure. If true, the client will continually reconnect, even after exhausting the specified number * of retries specified by initializeConfig.retries. If false, the client will stop reconnecting if all retry attempts fail. */ - stayConnected ? : boolean; + stayConnected?: boolean; } interface subscribeConfig extends baseRequestConfig { /** * The channel to which the client should be subscribed. Must start with a forward slash (/). Overrides channels. */ - channel ? : string; + channel?: string; /** * The channels to which the client should be subscribed. Each must start with a forward slash (/). Overrides channel. */ - channels ? : string[]; + channels?: string[]; /** * The callback to invoke after onSuccess or onFailure. See subscribeCompleteArgs for callback argument details. */ - onComplete ? : (args: subscribeCompleteArgs) => void; + onComplete?: (args: subscribeCompleteArgs) => void; /** * (OptionalThe callback to invoke if the subscribe fails. See subscribeFailureArgs for callback argument details. */ - onFailure ? : (args: subscribeFailureArgs) => void; + onFailure?: (args: subscribeFailureArgs) => void; /** * The callback to invoke when data is received on the channel(s). See receiveArgs for callback argument details. */ - onReceive ? : (args: receiveArgs) => void; + onReceive?: (args: receiveArgs) => void; /** * Subscribers extension. The callback to invoke when a subscribers change notification is received (i.e. when a client subscribes to or unsubscribes from the channel(s)). * The current subscribe request will trigger this callback. See subscribersChangeArgs for callback argument details. */ - onSubscribersChange ? : (args: subscribersChangeArgs) => void; + onSubscribersChange?: (args: subscribersChangeArgs) => void; /** * The callback to invoke if the subscribe succeeds. See subscribeSuccessArgs for callback argument details. */ - onSuccess ? : (args: subscribeSuccessArgs) => void; + onSuccess?: (args: subscribeSuccessArgs) => void; } interface initializeFailureArgs extends baseArgs { @@ -363,12 +363,12 @@ declare namespace fm { /** * The details of the change that occurred. */ - change ? : fm.websync.subscribersChange + change?: fm.websync.subscribersChange /** * The channel on which the change occurred. */ - channel ? : string; + channel?: string; } interface publishingClient { @@ -411,17 +411,17 @@ declare namespace fm { /** * The callback to invoke after onSuccess or onFailure. See disconnectCompleteArgs for callback argument details. */ - onComplete ? : (args: baseResponseArgs) => void; + onComplete?: (args: baseResponseArgs) => void; /** * The callback to invoke if the disconnect fails. See disconnectFailureArgs for callback argument details. */ - onFailure ? : (args: baseFailureArgs) => void; + onFailure?: (args: baseFailureArgs) => void; /** * The callback to invoke if the disconnect succeeds. See disconnectSuccessArgs for callback argument details. */ - onSuccess ? : (args: baseResponseArgs) => void; + onSuccess?: (args: baseResponseArgs) => void; } interface unsubscribeSuccessArgs extends baseResponseArgs { @@ -440,27 +440,27 @@ declare namespace fm { /** * The channel from which the client should be unsubscribed. Must start with a forward slash (/). Overrides channels. */ - channel ? : string; + channel?: string; /** * The channels from which the client should be unsubscribed. Each must start with a forward slash (/). Overrides channel. */ - channels ? : string[]; + channels?: string[]; /** * The callback to invoke after onSuccess or onFailure. See unsubscribeCompleteArgs for callback argument details. */ - onComplete ? : (args: baseResponseArgs) => void; + onComplete?: (args: baseResponseArgs) => void; /** * The callback to invoke if the unsubscribe fails. See unsubscribeFailureArgs for callback argument details. */ - onFailure ? : (args: baseFailureArgs) => void; + onFailure?: (args: baseFailureArgs) => void; /** * The callback to invoke if the unsubscribe succeeds. See unsubscribeSuccessArgs for callback argument details. */ - onSuccess ? : (args: unsubscribeSuccessArgs) => void; + onSuccess?: (args: unsubscribeSuccessArgs) => void; } export class client { From f400b97404ff6f01ff6476e0cdd9b6e022670b64 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 30 Jun 2017 14:36:13 +0200 Subject: [PATCH 0099/1618] method signature instead of property signature of function type --- types/fm-websync/index.d.ts | 46 ++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index 6e3d221ed0..14c9cae027 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for fm-websync 3 +// Type definitions for fm-websync 3.0 // Project: https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) // Definitions by: Markus Mauch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace fm { - export namespace websync { + namespace websync { interface initializeConfig { /** * If set to true, an asynchronous disconnect request will be launched when the page unloads. If set to false, no automatic disconnection will be attempted. @@ -36,17 +36,17 @@ declare namespace fm { /** * The callback to invoke after onSuccess or onFailure. See initializeCompleteArgs for callback argument details. */ - onComplete?: (args: baseArgs) => void; + onComplete?(args: baseArgs): void; /** * The callback to invoke if the initialize fails. Defaults to an alert of the error. See initializeFailureArgs for callback argument details. */ - onFailure?: (args: initializeFailureArgs) => void; + onFailure?(args: initializeFailureArgs): void; /** * The callback to invoke if the initialize succeeds. See initializeSuccessArgs for callback argument details. */ - onSuccess?: (args: baseArgs) => void; + onSuccess?(args: baseArgs): void; /** * Whether or not to suppress the alerting of a failure if the client is already initialized. @@ -153,12 +153,12 @@ declare namespace fm { /** * The callback to invoke after onSuccess or onFailure. See connectCompleteArgs for callback argument details. */ - onComplete?: (args: connectCompleteArgs) => void; + onComplete?(args: connectCompleteArgs): void; /** * The callback to invoke if the connect fails. Defaults to an alert of the error. See connectFailureArgs for callback argument details. */ - onFailure?: (args: connectFailureArgs) => void; + onFailure?(args: connectFailureArgs): void; /** * The callback to invoke if the streaming connection fails. See streamFailureArgs for callback argument details. @@ -169,18 +169,18 @@ declare namespace fm { * If the reconnect fails, the callback specified by onFailure will be invoked with isReconnect set to false. * With the exception of UI updates, invocations of this callback with willReconnect set to true can be ignored. */ - onStreamFailure?: (args: streamFailureArgs) => void; + onStreamFailure?(args: streamFailureArgs): void; /** * The callback to invoke if the connect succeeds. See connectSuccessArgs for callback argument details. */ - onSuccess?: (args: connectSuccessArgs) => void; + onSuccess?(args: connectSuccessArgs): void; /** * The callback to invoke when a message is received on a channel that has no local callback specified to handle it. See receiveArgs for callback argument details. * This can occur if (a) a client is manually subscribed to a channel by the server or (b) a client subscribed to a channel and then manually removed the local callback using client. */ - onUnhandledReceive?: (args: receiveArgs) => void; + onUnhandledReceive?(args: receiveArgs): void; /** * Whether to always attempt to stay connected in the event of network failure. If true, the client will continually reconnect, even after exhausting the specified number @@ -203,28 +203,28 @@ declare namespace fm { /** * The callback to invoke after onSuccess or onFailure. See subscribeCompleteArgs for callback argument details. */ - onComplete?: (args: subscribeCompleteArgs) => void; + onComplete?(args: subscribeCompleteArgs): void; /** * (OptionalThe callback to invoke if the subscribe fails. See subscribeFailureArgs for callback argument details. */ - onFailure?: (args: subscribeFailureArgs) => void; + onFailure?(args: subscribeFailureArgs): void; /** * The callback to invoke when data is received on the channel(s). See receiveArgs for callback argument details. */ - onReceive?: (args: receiveArgs) => void; + onReceive?(args: receiveArgs): void; /** * Subscribers extension. The callback to invoke when a subscribers change notification is received (i.e. when a client subscribes to or unsubscribes from the channel(s)). * The current subscribe request will trigger this callback. See subscribersChangeArgs for callback argument details. */ - onSubscribersChange?: (args: subscribersChangeArgs) => void; + onSubscribersChange?(args: subscribersChangeArgs): void; /** * The callback to invoke if the subscribe succeeds. See subscribeSuccessArgs for callback argument details. */ - onSuccess?: (args: subscribeSuccessArgs) => void; + onSuccess?(args: subscribeSuccessArgs): void; } interface initializeFailureArgs extends baseArgs { @@ -363,7 +363,7 @@ declare namespace fm { /** * The details of the change that occurred. */ - change?: fm.websync.subscribersChange + change?: fm.websync.subscribersChange; /** * The channel on which the change occurred. @@ -411,17 +411,17 @@ declare namespace fm { /** * The callback to invoke after onSuccess or onFailure. See disconnectCompleteArgs for callback argument details. */ - onComplete?: (args: baseResponseArgs) => void; + onComplete?(args: baseResponseArgs): void; /** * The callback to invoke if the disconnect fails. See disconnectFailureArgs for callback argument details. */ - onFailure?: (args: baseFailureArgs) => void; + onFailure?(args: baseFailureArgs): void; /** * The callback to invoke if the disconnect succeeds. See disconnectSuccessArgs for callback argument details. */ - onSuccess?: (args: baseResponseArgs) => void; + onSuccess?(args: baseResponseArgs): void; } interface unsubscribeSuccessArgs extends baseResponseArgs { @@ -450,20 +450,20 @@ declare namespace fm { /** * The callback to invoke after onSuccess or onFailure. See unsubscribeCompleteArgs for callback argument details. */ - onComplete?: (args: baseResponseArgs) => void; + onComplete?(args: baseResponseArgs): void; /** * The callback to invoke if the unsubscribe fails. See unsubscribeFailureArgs for callback argument details. */ - onFailure?: (args: baseFailureArgs) => void; + onFailure?(args: baseFailureArgs): void; /** * The callback to invoke if the unsubscribe succeeds. See unsubscribeSuccessArgs for callback argument details. */ - onSuccess?: (args: unsubscribeSuccessArgs) => void; + onSuccess?(args: unsubscribeSuccessArgs): void; } - export class client { + class client { /** * Sets up and maintains a streaming connection to the server. * While this method will typically run asychronously, the WebSync client is designed to be used without (much) consideration for its asynchronous nature. From 524cf8e2a92baea0a4c19719e3ed9e7a5caaf93e Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 10:28:08 -0400 Subject: [PATCH 0100/1618] [semantic-ui-dropdown] Different weak-type workaround. --- types/semantic-ui-dropdown/global.d.ts | 173 +++++++++++--- .../semantic-ui-dropdown-tests.ts | 216 +++++++++++++----- 2 files changed, 306 insertions(+), 83 deletions(-) diff --git a/types/semantic-ui-dropdown/global.d.ts b/types/semantic-ui-dropdown/global.d.ts index 12425cbace..8fc8c234cd 100644 --- a/types/semantic-ui-dropdown/global.d.ts +++ b/types/semantic-ui-dropdown/global.d.ts @@ -157,19 +157,71 @@ declare namespace SemanticUI { */ (behavior: 'get placeholder text'): string; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): DropdownSettings[K]; - (behavior: 'setting', name: K, value: DropdownSettings[K]): JQuery; - (behavior: 'setting', value: DropdownSettings.Param): JQuery; - (settings?: DropdownSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): DropdownSettings._Impl[K]; + (behavior: 'setting', name: K, value: DropdownSettings._Impl[K]): JQuery; + (behavior: 'setting', value: DropdownSettings): JQuery; + (settings?: DropdownSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/dropdown.html#/settings} */ - interface DropdownSettings extends Pick { } + type DropdownSettings = DropdownSettings.Param; namespace DropdownSettings { - type Param = DropdownSettings | object; + type Param = (Pick<_Impl, 'on'> | + Pick<_Impl, 'allowReselection'> | + Pick<_Impl, 'allowAdditions'> | + Pick<_Impl, 'hideAdditions'> | + Pick<_Impl, 'action'> | + Pick<_Impl, 'minCharacters'> | + Pick<_Impl, 'match'> | + Pick<_Impl, 'selectOnKeydown'> | + Pick<_Impl, 'forceSelection'> | + Pick<_Impl, 'allowCategorySelection'> | + Pick<_Impl, 'placeholder'> | + Pick<_Impl, 'apiSettings'> | + Pick<_Impl, 'fields'> | + Pick<_Impl, 'saveRemoteData'> | + Pick<_Impl, 'filterRemoteData'> | + Pick<_Impl, 'useLabels'> | + Pick<_Impl, 'maxSelections'> | + Pick<_Impl, 'glyphWidth'> | + Pick<_Impl, 'label'> | + Pick<_Impl, 'direction'> | + Pick<_Impl, 'keepOnScreen'> | + Pick<_Impl, 'context'> | + Pick<_Impl, 'fullTextSearch'> | + Pick<_Impl, 'preserveHTML'> | + Pick<_Impl, 'sortSelect'> | + Pick<_Impl, 'showOnFocus'> | + Pick<_Impl, 'allowTab'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'keys'> | + Pick<_Impl, 'delay'> | + Pick<_Impl, 'onChange'> | + Pick<_Impl, 'onAdd'> | + Pick<_Impl, 'onRemove'> | + Pick<_Impl, 'onLabelCreate'> | + Pick<_Impl, 'onLabelRemove'> | + Pick<_Impl, 'onLabelSelect'> | + Pick<_Impl, 'onNoResults'> | + Pick<_Impl, 'onShow'> | + Pick<_Impl, 'onHide'> | + Pick<_Impl, 'message'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'regExp'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Frequently Used Settings @@ -475,10 +527,14 @@ declare namespace SemanticUI { } namespace Dropdown { - interface FieldsSettings extends Pick { } + type FieldsSettings = FieldsSettings.Param; namespace FieldsSettings { - type Param = FieldsSettings | object; + type Param = (Pick<_Impl, 'remoteValues'> | + Pick<_Impl, 'values'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'value'>) & + Partial>; interface _Impl { /** @@ -508,10 +564,13 @@ declare namespace SemanticUI { } } - interface LabelSettings extends Pick { } + type LabelSettings = LabelSettings.Param; namespace LabelSettings { - type Param = LabelSettings | object; + type Param = (Pick<_Impl, 'transition'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'variation'>) & + Partial>; interface _Impl { /** @@ -529,10 +588,21 @@ declare namespace SemanticUI { } } - interface KeySettings extends Pick { } + type KeySettings = KeySettings.Param; namespace KeySettings { - type Param = KeySettings | object; + type Param = (Pick<_Impl, 'backspace'> | + Pick<_Impl, 'delimiter'> | + Pick<_Impl, 'deleteKey'> | + Pick<_Impl, 'enter'> | + Pick<_Impl, 'escape'> | + Pick<_Impl, 'pageUp'> | + Pick<_Impl, 'pageDown'> | + Pick<_Impl, 'leftArrow'> | + Pick<_Impl, 'upArrow'> | + Pick<_Impl, 'rightArrow'> | + Pick<_Impl, 'downArrow'>) & + Partial>; interface _Impl { /** @@ -582,10 +652,14 @@ declare namespace SemanticUI { } } - interface DelaySettings extends Pick { } + type DelaySettings = DelaySettings.Param; namespace DelaySettings { - type Param = DelaySettings | object; + type Param = (Pick<_Impl, 'hide'> | + Pick<_Impl, 'show'> | + Pick<_Impl, 'search'> | + Pick<_Impl, 'touch'>) & + Partial>; interface _Impl { /** @@ -607,10 +681,14 @@ declare namespace SemanticUI { } } - interface MessageSettings extends Pick { } + type MessageSettings = MessageSettings.Param; namespace MessageSettings { - type Param = MessageSettings | object; + type Param = (Pick<_Impl, 'addResult'> | + Pick<_Impl, 'count'> | + Pick<_Impl, 'maxSelections'> | + Pick<_Impl, 'noResults'>) & + Partial>; interface _Impl { /** @@ -632,10 +710,23 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'addition'> | + Pick<_Impl, 'dropdown'> | + Pick<_Impl, 'icon'> | + Pick<_Impl, 'input'> | + Pick<_Impl, 'item'> | + Pick<_Impl, 'label'> | + Pick<_Impl, 'remove'> | + Pick<_Impl, 'siblingLabel'> | + Pick<_Impl, 'menu'> | + Pick<_Impl, 'message'> | + Pick<_Impl, 'menuIcon'> | + Pick<_Impl, 'search'> | + Pick<_Impl, 'text'>) & + Partial>; interface _Impl { /** @@ -693,10 +784,11 @@ declare namespace SemanticUI { } } - interface RegExpSettings extends Pick { } + type RegExpSettings = RegExpSettings.Param; namespace RegExpSettings { - type Param = RegExpSettings | object; + type Param = (Pick<_Impl, 'escape'>) & + Partial>; interface _Impl { /** @@ -706,10 +798,15 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { - type Param = MetadataSettings | object; + type Param = (Pick<_Impl, 'defaultText'> | + Pick<_Impl, 'defaultValue'> | + Pick<_Impl, 'placeholderText'> | + Pick<_Impl, 'text'> | + Pick<_Impl, 'value'>) & + Partial>; interface _Impl { /** @@ -735,10 +832,29 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'addition'> | + Pick<_Impl, 'animating'> | + Pick<_Impl, 'disabled'> | + Pick<_Impl, 'dropdown'> | + Pick<_Impl, 'filtered'> | + Pick<_Impl, 'hidden'> | + Pick<_Impl, 'item'> | + Pick<_Impl, 'label'> | + Pick<_Impl, 'loading'> | + Pick<_Impl, 'menu'> | + Pick<_Impl, 'message'> | + Pick<_Impl, 'multiple'> | + Pick<_Impl, 'placeholder'> | + Pick<_Impl, 'search'> | + Pick<_Impl, 'selected'> | + Pick<_Impl, 'selection'> | + Pick<_Impl, 'upward'> | + Pick<_Impl, 'visible'>) & + Partial>; interface _Impl { /** @@ -820,10 +936,15 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'action'> | + Pick<_Impl, 'alreadySetup'> | + Pick<_Impl, 'labels'> | + Pick<_Impl, 'method'> | + Pick<_Impl, 'noTransition'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-dropdown/semantic-ui-dropdown-tests.ts b/types/semantic-ui-dropdown/semantic-ui-dropdown-tests.ts index 2dafbf9c8e..915f96e40f 100644 --- a/types/semantic-ui-dropdown/semantic-ui-dropdown-tests.ts +++ b/types/semantic-ui-dropdown/semantic-ui-dropdown-tests.ts @@ -1,5 +1,5 @@ function test_dropdown_static() { - $.fn.dropdown.settings.error.method = 'method'; + $.fn.dropdown.settings.error!.method = 'method'; $.fn.dropdown.settings.namespace = 'namespace'; $.fn.dropdown.settings.name = 'name'; $.fn.dropdown.settings.silent = false; @@ -10,47 +10,48 @@ function test_dropdown_static() { function test_dropdown() { const selector = '.ui.dropdown'; - $(selector).dropdown('setup menu') === $(); - $(selector).dropdown('refresh') === $(); - $(selector).dropdown('toggle') === $(); - $(selector).dropdown('show') === $(); - $(selector).dropdown('hide') === $(); - $(selector).dropdown('clear') === $(); - $(selector).dropdown('hide others') === $(); - $(selector).dropdown('restore defaults') === $(); - $(selector).dropdown('restore default text') === $(); - $(selector).dropdown('restore placeholder text') === $(); - $(selector).dropdown('restore default value') === $(); - $(selector).dropdown('save defaults') === $(); - $(selector).dropdown('set selected', 123) === $(); - $(selector).dropdown('remove selected', false) === $(); - $(selector).dropdown('set selected', ['456']) === $(); - $(selector).dropdown('set exactly', []) === $(); - $(selector).dropdown('set text', 'hello') === $(); - $(selector).dropdown('set value', 24) === $(); - $(selector).dropdown('get text') === 'text'; - $(selector).dropdown('get value') === {}; - $(selector).dropdown('get item', 'Pennsylvania') === $(); - $(selector).dropdown('bind touch events') === $(); - $(selector).dropdown('bind mouse events') === $(); - $(selector).dropdown('bind intent') === $(); - $(selector).dropdown('unbind intent') === $(); - $(selector).dropdown('determine intent') === true; - $(selector).dropdown('determine select action', 'text', 90) === $(); - $(selector).dropdown('set active') === $(); - $(selector).dropdown('set visible') === $(); - $(selector).dropdown('remove active') === $(); - $(selector).dropdown('remove visible') === $(); - $(selector).dropdown('is selection') === false; - $(selector).dropdown('is animated') === false; - $(selector).dropdown('is visible') === false; - $(selector).dropdown('is hidden') === false; + $(selector).dropdown('setup menu'); // $ExpectType JQuery + $(selector).dropdown('refresh'); // $ExpectType JQuery + $(selector).dropdown('toggle'); // $ExpectType JQuery + $(selector).dropdown('show'); // $ExpectType JQuery + $(selector).dropdown('hide'); // $ExpectType JQuery + $(selector).dropdown('clear'); // $ExpectType JQuery + $(selector).dropdown('hide others'); // $ExpectType JQuery + $(selector).dropdown('restore defaults'); // $ExpectType JQuery + $(selector).dropdown('restore default text'); // $ExpectType JQuery + $(selector).dropdown('restore placeholder text'); // $ExpectType JQuery + $(selector).dropdown('restore default value'); // $ExpectType JQuery + $(selector).dropdown('save defaults'); // $ExpectType JQuery + $(selector).dropdown('set selected', 123); // $ExpectType JQuery + $(selector).dropdown('remove selected', false); // $ExpectType JQuery + $(selector).dropdown('set selected', ['456']); // $ExpectType JQuery + $(selector).dropdown('set exactly', []); // $ExpectType JQuery + $(selector).dropdown('set text', 'hello'); // $ExpectType JQuery + $(selector).dropdown('set value', 24); // $ExpectType JQuery + $(selector).dropdown('get text'); // $ExpectType string + $(selector).dropdown('get value'); // $ExpectType any + $(selector).dropdown('get item', 'Pennsylvania'); // $ExpectType JQuery + $(selector).dropdown('bind touch events'); // $ExpectType JQuery + $(selector).dropdown('bind mouse events'); // $ExpectType JQuery + $(selector).dropdown('bind intent'); // $ExpectType JQuery + $(selector).dropdown('unbind intent'); // $ExpectType JQuery + $(selector).dropdown('determine intent'); // $ExpectType boolean + $(selector).dropdown('determine select action', 'text', 90); // $ExpectType JQuery + $(selector).dropdown('set active'); // $ExpectType JQuery + $(selector).dropdown('set visible'); // $ExpectType JQuery + $(selector).dropdown('remove active'); // $ExpectType JQuery + $(selector).dropdown('remove visible'); // $ExpectType JQuery + $(selector).dropdown('is selection'); // $ExpectType boolean + $(selector).dropdown('is animated'); // $ExpectType boolean + $(selector).dropdown('is visible'); // $ExpectType boolean + $(selector).dropdown('is hidden'); // $ExpectType boolean $(selector).dropdown('get default text') === 'default text'; $(selector).dropdown('get placeholder text') === 'placeholder text'; - $(selector).dropdown('destroy') === $(); - $(selector).dropdown('setting', 'debug', undefined) === false; - $(selector).dropdown('setting', 'debug') === false; - $(selector).dropdown('setting', 'debug', true) === $(); + $(selector).dropdown('destroy'); // $ExpectType JQuery + $(selector).dropdown('setting', 'debug', undefined); // $ExpectType boolean + $(selector).dropdown('setting', 'debug'); // $ExpectType boolean + $(selector).dropdown('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).dropdown('setting', { namespace: 'namespace', name: 'name', @@ -58,19 +59,18 @@ function test_dropdown() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).dropdown({ on: 'hover', allowReselection: true, allowAdditions: false, hideAdditions: true, action(text, value, element) { - this === $(); - text === 'text'; - if (typeof value !== 'string') { - value === false; - } - element === $(); + this; // $ExpectType JQuery + text; // $ExpectType string + value; // $ExpectType string | false + element; // $ExpectType JQuery }, minCharacters: 2, match: 'text', @@ -79,9 +79,107 @@ function test_dropdown() { allowCategorySelection: false, placeholder: 'value', apiSettings: { - cache: 'local', + on: 'on', + cache: true, + stateContext: $(), + encodeParameters: false, + defaultData: true, + serializeForm: false, + throttle: 10, throttleFirstRequest: true, - loadingDuration: 20 + interruptRequests: false, + loadingDuration: 3, + hideError: true, + errorDuration: 10, + action: 'action', + url: 'url', + urlData: false, + response: false, + responseAsync(settings, callback) { + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void + }, + mockResponse: false, + mockResponseAsync(settings, callback) { + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void + }, + method: 'post', + dataType: 'xml', + data: {}, + beforeSend(settings) { + settings; // $ExpectType Param + }, + beforeXHR(xhrObject) { + xhrObject; // $ExpectType jqXHR + }, + onRequest(promise, xhr) { + promise; // $ExpectType Deferred + xhr; // $ExpectType jqXHR + }, + onResponse(response) { + response; // $ExpectType any + }, + successTest(response) { + response; // $ExpectType any + + return false; + }, + onSuccess(response, element, xhr) { + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR + }, + onComplete(response, element, xhr) { + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR + }, + onFailure(response, element) { + response; // $ExpectType any + element; // $ExpectType JQuery + }, + onError(errorMessage, element, xhr) { + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR + }, + onAbort(errorMessage, element, xhr) { + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR + }, + regExp: { + required: /{\$*[A-z0-9]+}/g, + optional: /{\/\$*[A-z0-9]+}/g + }, + selector: { + disabled: '.disabled', + form: 'form' + }, + className: { + loading: 'loading', + error: 'error' + }, + metadata: { + action: 'action', + url: 'url' + }, + error: { + beforeSend: 'beforeSend', + error: 'error', + exitConditions: 'exitConditions', + JSONParse: 'JSONParse', + legacyParameters: 'legacyParameters', + missingAction: 'missingAction', + missingSerialize: 'missingSerialize', + missingURL: 'missingURL', + noReturnedValue: 'noReturnedValue', + parseError: 'parseError', + requiredParameter: 'requiredParameter', + statusMessage: 'statusMessage', + timeout: 'timeout' + } }, fields: { remoteValues: 'remoteValues', @@ -129,14 +227,14 @@ function test_dropdown() { touch: 50 }, onChange(value, text, $choice) { - value === {}; - text === 'text'; - $choice === $(); + value; // $ExpectType any + text; // $ExpectType string + $choice; // $ExpectType JQuery }, onAdd(addedValue, addedText, $addedChoice) { - addedValue === {}; - addedText === 'addedText'; - $addedChoice === $(); + addedValue; // $ExpectType any + addedText; // $ExpectType string + $addedChoice; // $ExpectType JQuery }, message: { addResult: 'addResult', @@ -197,12 +295,16 @@ function test_dropdown() { method: 'method', noTransition: 'noTransition' } - }) === $(); - $(selector).dropdown() === $(); + }); + $(selector).dropdown(); // $ExpectType JQuery + + $(selector).dropdown('foo'); // $ExpectError + $(selector).dropdown({ foo: 'bar' }); // $ExpectError } import dropdown = require('semantic-ui-dropdown'); function test_module() { + dropdown; // $ExpectType Dropdown $.fn.dropdown = dropdown; } From c8cea810102dcdb03c9f72704fa0919669a6180e Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 11:12:55 -0400 Subject: [PATCH 0101/1618] [semantic-ui-embed] Different weak-type workaround. --- types/semantic-ui-embed/global.d.ts | 74 ++++++++++++++----- .../semantic-ui-embed-tests.ts | 67 +++++++++-------- 2 files changed, 94 insertions(+), 47 deletions(-) diff --git a/types/semantic-ui-embed/global.d.ts b/types/semantic-ui-embed/global.d.ts index e851b252a1..c9a096649c 100644 --- a/types/semantic-ui-embed/global.d.ts +++ b/types/semantic-ui-embed/global.d.ts @@ -50,19 +50,43 @@ declare namespace SemanticUI { * Destroys instance and removes all events */ (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): EmbedSettings[K]; - (behavior: 'setting', name: K, value: EmbedSettings[K]): JQuery; - (behavior: 'setting', value: EmbedSettings.Param): JQuery; - (settings?: EmbedSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): EmbedSettings._Impl[K]; + (behavior: 'setting', name: K, value: EmbedSettings._Impl[K]): JQuery; + (behavior: 'setting', value: EmbedSettings): JQuery; + (settings?: EmbedSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/embed.html#/settings} */ - interface EmbedSettings extends Pick { } + type EmbedSettings = EmbedSettings.Param; namespace EmbedSettings { - type Param = EmbedSettings | object; + type Param = (Pick<_Impl, 'url'> | + Pick<_Impl, 'icon'> | + Pick<_Impl, 'source'> | + Pick<_Impl, 'id'> | + Pick<_Impl, 'parameters'> | + Pick<_Impl, 'autoplay'> | + Pick<_Impl, 'color'> | + Pick<_Impl, 'hd'> | + Pick<_Impl, 'brandedUI'> | + Pick<_Impl, 'onCreate'> | + Pick<_Impl, 'onDisplay'> | + Pick<_Impl, 'onPlaceholderDisplay'> | + Pick<_Impl, 'onEmbed'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'templates'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { /** @@ -216,20 +240,23 @@ declare namespace SemanticUI { } namespace Embed { - interface ParametersSettings extends Pick { } + type ParametersSettings = ParametersSettings._Impl; namespace ParametersSettings { - type Param = ParametersSettings | object; + type Param = _Impl; interface _Impl { [key: string]: any; } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'embed'> | + Pick<_Impl, 'placeholder'> | + Pick<_Impl, 'play'>) & + Partial>; interface _Impl { /** @@ -247,10 +274,15 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { - type Param = MetadataSettings | object; + type Param = (Pick<_Impl, 'id'> | + Pick<_Impl, 'icon'> | + Pick<_Impl, 'placeholder'> | + Pick<_Impl, 'source'> | + Pick<_Impl, 'url'>) & + Partial>; interface _Impl { /** @@ -276,10 +308,12 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'embed'>) & + Partial>; interface _Impl { /** @@ -293,10 +327,12 @@ declare namespace SemanticUI { } } - interface TemplatesSettings extends Pick { } + type TemplatesSettings = TemplatesSettings.Param; namespace TemplatesSettings { - type Param = TemplatesSettings | object; + type Param = (Pick<_Impl, 'iframe'> | + Pick<_Impl, 'placeholder'>) & + Partial>; interface _Impl { /** @@ -310,10 +346,12 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'noURL'> | + Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-embed/semantic-ui-embed-tests.ts b/types/semantic-ui-embed/semantic-ui-embed-tests.ts index 486092a2a1..63d6769763 100644 --- a/types/semantic-ui-embed/semantic-ui-embed-tests.ts +++ b/types/semantic-ui-embed/semantic-ui-embed-tests.ts @@ -1,5 +1,5 @@ function test_embed_static() { - $.fn.embed.settings.error.method = 'method'; + $.fn.embed.settings.error!.method = 'method'; $.fn.embed.settings.namespace = 'namespace'; $.fn.embed.settings.name = 'name'; $.fn.embed.settings.silent = false; @@ -10,20 +10,21 @@ function test_embed_static() { function test_embed() { const selector = '.ui.embed'; - $(selector).embed('change', 'source', 'id', 'url') === $(); - $(selector).embed('reset') === $(); - $(selector).embed('show') === $(); - $(selector).embed('hide') === $(); - $(selector).embed('get id') === 'get'; - $(selector).embed('get placeholder') === 'get'; - $(selector).embed('get sources') === 'get'; - $(selector).embed('get type') === 'get'; - $(selector).embed('get url') === 'get'; + $(selector).embed('change', 'source', 'id', 'url'); // $ExpectType JQuery + $(selector).embed('reset'); // $ExpectType JQuery + $(selector).embed('show'); // $ExpectType JQuery + $(selector).embed('hide'); // $ExpectType JQuery + $(selector).embed('get id'); // $ExpectType string + $(selector).embed('get placeholder'); // $ExpectType string + $(selector).embed('get sources'); // $ExpectType string + $(selector).embed('get type'); // $ExpectType string + $(selector).embed('get url'); // $ExpectType string $(selector).embed('has placeholder') === true; - $(selector).embed('destroy') === $(); - $(selector).embed('setting', 'debug', undefined) === false; - $(selector).embed('setting', 'debug') === false; - $(selector).embed('setting', 'debug', true) === $(); + $(selector).embed('destroy'); // $ExpectType JQuery + $(selector).embed('setting', 'debug', undefined); // $ExpectType boolean + $(selector).embed('setting', 'debug'); // $ExpectType boolean + $(selector).embed('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).embed('setting', { namespace: 'namespace', name: 'name', @@ -31,7 +32,8 @@ function test_embed() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).embed({ url: 'url', icon: 'icon', @@ -45,18 +47,19 @@ function test_embed() { hd: false, brandedUI: true, onCreate(url) { - this === $(); - url === 'url'; + this; // $ExpectType JQuery + url; // $ExpectType string }, onDisplay() { - this === $(); + this; // $ExpectType JQuery }, onPlaceholderDisplay() { - this === $(); + this; // $ExpectType JQuery }, onEmbed(parameters) { - this === $(); - parameters.key = 'value'; + this; // $ExpectType JQuery + parameters; // $ExpectType _Impl + return parameters; }, selector: { @@ -77,26 +80,32 @@ function test_embed() { }, templates: { iframe(url, parameters) { - url === 'url'; - parameters === 'parameters'; - return url + parameters; + url; // $ExpectType string + parameters; // $ExpectType string + + return '
'; }, placeholder(image, icon) { - image === 'image'; - icon === 'icon'; - return image + icon; + image; // $ExpectType string + icon; // $ExpectType string + + return '
'; } }, error: { noURL: 'noURL', method: 'method' } - }) === $(); - $(selector).embed() === $(); + }); + $(selector).embed(); // $ExpectType JQuery + + $(selector).embed('foo'); // $ExpectError + $(selector).embed({ foo: 'bar' }); // $ExpectError } import embed = require('semantic-ui-embed'); function test_module() { + embed; // $ExpectType Embed $.fn.embed = embed; } From 6fe4d80f181b3c20578bb321c39978f23d40a5be Mon Sep 17 00:00:00 2001 From: juraj kocan Date: Fri, 30 Jun 2017 17:38:56 +0200 Subject: [PATCH 0102/1618] types for osmosis node module --- types/osmosis/index.d.ts | 62 ++++++++++++++++++++++++++++++++++ types/osmosis/osmosis-tests.ts | 42 +++++++++++++++++++++++ types/osmosis/tsconfig.json | 22 ++++++++++++ types/osmosis/tslint.json | 1 + 4 files changed, 127 insertions(+) create mode 100644 types/osmosis/index.d.ts create mode 100644 types/osmosis/osmosis-tests.ts create mode 100644 types/osmosis/tsconfig.json create mode 100644 types/osmosis/tslint.json diff --git a/types/osmosis/index.d.ts b/types/osmosis/index.d.ts new file mode 100644 index 0000000000..3d5a80a5e2 --- /dev/null +++ b/types/osmosis/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for osmosis 1.1 +// Project: https://github.com/rchipka/node-osmosis#readme +// Definitions by: Juraj +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export declare interface IOsmosis { + /** + * define domain where osmosis is parsing data from + */ + get: (url: string) => IOsmosis, + + /** + * set scrapped data as result, + * 1. string, after find function set data by selector as value with this string as key + * 2. object, define any json object + */ + set: (json: string | Object) => IOsmosis, + + /** + * find DOM by selector + */ + find: (selector: string) => IOsmosis, + + /** + * follw links, founded href or src + * @param selector '@href' or '@src' + * @default '@href' + */ + follow: (selector: string) => IOsmosis, + + /** + * paginate followed page + */ + paginate: (selector: string) => IOsmosis + + /** + * passing string to your function + * log data + */ + log: (callback: (param: string) => any) => IOsmosis, + + /** + * passing string to your function + * debug data + */ + debug: (callback: (param: string) => any) => IOsmosis, + + /** + * passing string to your function + * error data + */ + error: (callback: (param: string) => any) => IOsmosis, + + /** + * passing string to your function + * result data, osmosis finished + */ + data: (callback: (param: string) => any) => IOsmosis +} + +export declare const osmosis: IOsmosis + diff --git a/types/osmosis/osmosis-tests.ts b/types/osmosis/osmosis-tests.ts new file mode 100644 index 0000000000..0882bb14f7 --- /dev/null +++ b/types/osmosis/osmosis-tests.ts @@ -0,0 +1,42 @@ +import { osmosis } from 'osmosis'; + +const logFunction = (log: string) => { + const myLog = log; +}; + +const debugFunction = (debug: string) => { + const myDebug = debug; +}; + +const errorFunction = (error: string) => { + const myError = error; +}; + +// example is from https://github.com/rchipka/node-osmosis#example + +osmosis + .get('www.craigslist.org/about/sites') + .find('h1 + div a') + .set('location') + .follow('@href') + .find('header + div + div li > a') + .set('category') + .follow('@href') + .paginate('.totallink + a.button.next:first') + .find('p > a') + .follow('@href') + .set({ + title: 'section > h2', + description: '#postingbody', + subcategory: 'div.breadbox > span[4]', + date: 'time@datetime', + latitude: '#map@data-latitude', + longitude: '#map@data-longitude', + images: ['img@src'] + }) + .data((listing: any) => { + // do something with listing data + }) + .log(logFunction) + .error(errorFunction) + .debug(debugFunction); diff --git a/types/osmosis/tsconfig.json b/types/osmosis/tsconfig.json new file mode 100644 index 0000000000..c6c1cd0b81 --- /dev/null +++ b/types/osmosis/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "osmosis-tests.ts" + ] +} diff --git a/types/osmosis/tslint.json b/types/osmosis/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/osmosis/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d3864ce14458cbd58ffaab2e4298e3b30e23c708 Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Fri, 30 Jun 2017 18:01:44 +0200 Subject: [PATCH 0103/1618] [request] Add some missing properties --- types/request/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 2cf7b08cf9..dac5b36e42 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -134,12 +134,16 @@ declare namespace request { body?: any; followRedirect?: boolean | ((response: http.IncomingMessage) => boolean); followAllRedirects?: boolean; + followOriginalHttpMethod?: boolean; maxRedirects?: number; + removeRefererHeader?: boolean; encoding?: string | null; pool?: any; timeout?: number; + localAddress?: string; proxy?: any; strictSSL?: boolean; + time?: boolean; gzip?: boolean; preambleCRLF?: boolean; postambleCRLF?: boolean; From 40eef89e465de56ba3daa9eaa8edb449344c0e57 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 12:09:04 -0400 Subject: [PATCH 0104/1618] [semantic-ui-form] Different weak-type workaround. --- types/semantic-ui-form/global.d.ts | 110 ++++++++++++++---- .../semantic-ui-form-tests.ts | 73 +++++++----- 2 files changed, 132 insertions(+), 51 deletions(-) diff --git a/types/semantic-ui-form/global.d.ts b/types/semantic-ui-form/global.d.ts index 13fefb8147..3f8b3977e9 100644 --- a/types/semantic-ui-form/global.d.ts +++ b/types/semantic-ui-form/global.d.ts @@ -55,19 +55,45 @@ declare namespace SemanticUI { */ (behavior: 'add errors', errors: string[]): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): FormSettings[K]; - (behavior: 'setting', name: K, value: FormSettings[K]): JQuery; - (behavior: 'setting', value: FormSettings.Param): JQuery; - (settings?: FormSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): FormSettings._Impl[K]; + (behavior: 'setting', name: K, value: FormSettings._Impl[K]): JQuery; + (behavior: 'setting', value: FormSettings): JQuery; + (settings?: FormSettings): JQuery; } /** * @see {@link http://semantic-ui.com/behaviors/form.html#/settings} */ - interface FormSettings extends Pick { } + type FormSettings = FormSettings.Param; namespace FormSettings { - type Param = FormSettings | object; + type Param = (Pick<_Impl, 'keyboardShortcuts'> | + Pick<_Impl, 'on'> | + Pick<_Impl, 'revalidate'> | + Pick<_Impl, 'delay'> | + Pick<_Impl, 'inline'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'fields'> | + Pick<_Impl, 'text'> | + Pick<_Impl, 'prompt'> | + Pick<_Impl, 'onValid'> | + Pick<_Impl, 'onInvalid'> | + Pick<_Impl, 'onSuccess'> | + Pick<_Impl, 'onFailure'> | + Pick<_Impl, 'templates'> | + Pick<_Impl, 'rules'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Form Settings @@ -141,7 +167,7 @@ declare namespace SemanticUI { /** * Callback if a form is all valid */ - onSuccess(this: JQuery, event: JQueryEventObject, fields: any): void; + onSuccess(this: JQuery, event: JQuery.Event, fields: any): void; /** * Callback if any form field is invalid */ @@ -237,10 +263,12 @@ declare namespace SemanticUI { prompt: string; } - interface TextSettings extends Pick { } + type TextSettings = TextSettings.Param; namespace TextSettings { - type Param = TextSettings | object; + type Param = (Pick<_Impl, 'unspecifiedRule'> | + Pick<_Impl, 'unspecifiedField'>) & + Partial>; interface _Impl { /** @@ -254,10 +282,36 @@ declare namespace SemanticUI { } } - interface PromptSettings extends Pick { } + type PromptSettings = PromptSettings.Param; namespace PromptSettings { - type Param = PromptSettings | object; + type Param = (Pick<_Impl, 'empty'> | + Pick<_Impl, 'checked'> | + Pick<_Impl, 'email'> | + Pick<_Impl, 'url'> | + Pick<_Impl, 'regExp'> | + Pick<_Impl, 'integer'> | + Pick<_Impl, 'decimal'> | + Pick<_Impl, 'number'> | + Pick<_Impl, 'is'> | + Pick<_Impl, 'isExactly'> | + Pick<_Impl, 'not'> | + Pick<_Impl, 'notExactly'> | + Pick<_Impl, 'contain'> | + Pick<_Impl, 'containExactly'> | + Pick<_Impl, 'doesntContain'> | + Pick<_Impl, 'doesntContainExactly'> | + Pick<_Impl, 'minLength'> | + Pick<_Impl, 'length'> | + Pick<_Impl, 'exactLength'> | + Pick<_Impl, 'maxLength'> | + Pick<_Impl, 'match'> | + Pick<_Impl, 'different'> | + Pick<_Impl, 'creditCard'> | + Pick<_Impl, 'minCount'> | + Pick<_Impl, 'exactCount'> | + Pick<_Impl, 'maxCount'>) & + Partial>; interface _Impl { /** @@ -367,10 +421,12 @@ declare namespace SemanticUI { } } - interface TemplatesSettings extends Pick { } + type TemplatesSettings = TemplatesSettings.Param; namespace TemplatesSettings { - type Param = TemplatesSettings | object; + type Param = (Pick<_Impl, 'error'> | + Pick<_Impl, 'prompt'>) & + Partial>; interface _Impl { error(errors: string[]): JQuery; @@ -378,10 +434,16 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'message'> | + Pick<_Impl, 'field'> | + Pick<_Impl, 'group'> | + Pick<_Impl, 'input'> | + Pick<_Impl, 'prompt'> | + Pick<_Impl, 'submit'>) & + Partial>; interface _Impl { /** @@ -411,10 +473,11 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { - type Param = MetadataSettings | object; + type Param = (Pick<_Impl, 'validate'>) & + Partial>; interface _Impl { /** @@ -424,10 +487,14 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'placeholder'> | + Pick<_Impl, 'disabled'> | + Pick<_Impl, 'visible'>) & + Partial>; interface _Impl { /** @@ -449,10 +516,11 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-form/semantic-ui-form-tests.ts b/types/semantic-ui-form/semantic-ui-form-tests.ts index 58e8a18f70..56293fc5b4 100644 --- a/types/semantic-ui-form/semantic-ui-form-tests.ts +++ b/types/semantic-ui-form/semantic-ui-form-tests.ts @@ -1,5 +1,5 @@ function test_form_static() { - $.fn.form.settings.error.method = 'method'; + $.fn.form.settings.error!.method = 'method'; $.fn.form.settings.namespace = 'namespace'; $.fn.form.settings.name = 'name'; $.fn.form.settings.silent = false; @@ -10,22 +10,23 @@ function test_form_static() { function test_form() { const selector = '.ui.form'; - $(selector).form('submit') === $(); - $(selector).form('is valid') === false; - $(selector).form('validate form') === $(); + $(selector).form('submit'); // $ExpectType JQuery + $(selector).form('is valid'); // $ExpectType boolean + $(selector).form('validate form'); // $ExpectType JQuery $(selector).form('get change event') === 'change event'; - $(selector).form('get field', 'id') === $(); - $(selector).form('get value', 'id') === {}; - $(selector).form('get values', ['id1', 'id2']) === {}; - $(selector).form('set value', 'id') === $(); - $(selector).form('set values', ['id1', 'id2']) === $(); - $(selector).form('get validation', $()) === {}; - $(selector).form('has field', 'identifier') === true; - $(selector).form('add errors', ['error1', 'error2']) === $(); - $(selector).form('destroy') === $(); - $(selector).form('setting', 'debug', undefined) === false; - $(selector).form('setting', 'debug') === false; - $(selector).form('setting', 'debug', true) === $(); + $(selector).form('get field', 'id'); // $ExpectType JQuery + $(selector).form('get value', 'id'); // $ExpectType any + $(selector).form('get values', ['id1', 'id2']); // $ExpectType any + $(selector).form('set value', 'id'); // $ExpectType JQuery + $(selector).form('set values', ['id1', 'id2']); // $ExpectType JQuery + $(selector).form('get validation', $()); // $ExpectType any + $(selector).form('has field', 'identifier'); // $ExpectType boolean + $(selector).form('add errors', ['error1', 'error2']); // $ExpectType JQuery + $(selector).form('destroy'); // $ExpectType JQuery + $(selector).form('setting', 'debug', undefined); // $ExpectType boolean + $(selector).form('setting', 'debug'); // $ExpectType boolean + $(selector).form('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).form('setting', { namespace: 'namespace', name: 'name', @@ -33,12 +34,13 @@ function test_form() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).form({ keyboardShortcuts: false, on: 'submit', revalidate: true, - delay: 20, + delay: false, inline: false, transition: 'fade', duration: 22, @@ -92,36 +94,43 @@ function test_form() { maxCount: 'maxCount' }, onValid() { - this === $(); + this; // $ExpectType JQuery }, onInvalid() { - this === $(); + this; // $ExpectType JQuery }, onSuccess(event, fields) { - this === $(); - event.stopPropagation(); - fields === {}; + this; // $ExpectType JQuery + event; // $ExpectType Event + fields; // $ExpectType any }, onFailure(formErrors, fields) { - this === $(); - formErrors === []; - fields === {}; + this; // $ExpectType JQuery + formErrors; // $ExpectType string[] + fields; // $ExpectType any }, templates: { error(errors) { - errors === []; + errors; // $ExpectType string[] + return $(); }, prompt(errors) { - errors === []; + errors; // $ExpectType string[] + return $(); } }, rules: { empty(value) { + this; // $ExpectType HTMLElement + value; // $ExpectType any + return !(value === undefined || '' === value || $.isArray(value) && value.length === 0); }, checked() { + this; // $ExpectType HTMLElement + return ($(this).filter(':checked').length > 0); } }, @@ -145,12 +154,16 @@ function test_form() { error: { method: 'method' } - }) === $(); - $(selector).form() === $(); + }); + $(selector).form(); // $ExpectType JQuery + + $(selector).form('foo'); // $ExpectError + $(selector).form({ foo: 'bar' }); // $ExpectError } import form = require('semantic-ui-form'); function test_module() { + form; // $ExpectType Form $.fn.form = form; } From efaaa3c6af0aec10a7ad8d4639ceb967f754f24b Mon Sep 17 00:00:00 2001 From: juraj kocan Date: Fri, 30 Jun 2017 18:20:11 +0200 Subject: [PATCH 0105/1618] repair linter errors --- types/osmosis/index.d.ts | 33 +++++++++++++-------------------- types/osmosis/tslint.json | 4 +++- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/types/osmosis/index.d.ts b/types/osmosis/index.d.ts index 3d5a80a5e2..ee5f2700ea 100644 --- a/types/osmosis/index.d.ts +++ b/types/osmosis/index.d.ts @@ -1,62 +1,55 @@ -// Type definitions for osmosis 1.1 -// Project: https://github.com/rchipka/node-osmosis#readme -// Definitions by: Juraj -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export declare interface IOsmosis { +export interface Osmosis { /** * define domain where osmosis is parsing data from */ - get: (url: string) => IOsmosis, + get(url: string): Osmosis; /** * set scrapped data as result, * 1. string, after find function set data by selector as value with this string as key * 2. object, define any json object */ - set: (json: string | Object) => IOsmosis, + set(json: string | {}): Osmosis; /** * find DOM by selector */ - find: (selector: string) => IOsmosis, + find(selector: string): Osmosis; /** * follw links, founded href or src - * @param selector '@href' or '@src' - * @default '@href' + * @param selector '@href' or '@src', default '@href' */ - follow: (selector: string) => IOsmosis, + follow(selector: string): Osmosis; /** - * paginate followed page + * paginate followed url */ - paginate: (selector: string) => IOsmosis + paginate(selector: string): Osmosis; /** * passing string to your function * log data */ - log: (callback: (param: string) => any) => IOsmosis, + log(callback: (param: string) => any): Osmosis; /** * passing string to your function * debug data */ - debug: (callback: (param: string) => any) => IOsmosis, + debug(callback: (param: string) => any): Osmosis; /** * passing string to your function * error data */ - error: (callback: (param: string) => any) => IOsmosis, + error(callback: (param: string) => any): Osmosis; /** * passing string to your function * result data, osmosis finished */ - data: (callback: (param: string) => any) => IOsmosis + data(callback: (param: string) => any): Osmosis; } -export declare const osmosis: IOsmosis - +export const osmosis: Osmosis; diff --git a/types/osmosis/tslint.json b/types/osmosis/tslint.json index 3db14f85ea..4c3a548997 100644 --- a/types/osmosis/tslint.json +++ b/types/osmosis/tslint.json @@ -1 +1,3 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dtslint.json" +} From e9ae6bd04adb6b638e80ef5ef97fe253630e5c06 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 12:26:51 -0400 Subject: [PATCH 0106/1618] [semantic-ui-modal] Different weak-type workaround. --- types/semantic-ui-modal/global.d.ts | 57 +++++++++++--- .../semantic-ui-modal-tests.ts | 75 +++++++++++-------- 2 files changed, 87 insertions(+), 45 deletions(-) diff --git a/types/semantic-ui-modal/global.d.ts b/types/semantic-ui-modal/global.d.ts index 84f9116e8b..2e6efc4e1d 100644 --- a/types/semantic-ui-modal/global.d.ts +++ b/types/semantic-ui-modal/global.d.ts @@ -56,19 +56,46 @@ declare namespace SemanticUI { (behavior: 'set active'): JQuery; (behavior: 'attach events', selector: string | JQuery, event?: string): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ModalSettings[K]; - (behavior: 'setting', name: K, value: ModalSettings[K]): JQuery; - (behavior: 'setting', value: ModalSettings.Param): JQuery; - (settings?: ModalSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): ModalSettings._Impl[K]; + (behavior: 'setting', name: K, value: ModalSettings._Impl[K]): JQuery; + (behavior: 'setting', value: ModalSettings): JQuery; + (settings?: ModalSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/modal.html#/settings} */ - interface ModalSettings extends Pick { } + type ModalSettings = ModalSettings.Param; namespace ModalSettings { - type Param = ModalSettings | object; + type Param = (Pick<_Impl, 'detachable'> | + Pick<_Impl, 'autofocus'> | + Pick<_Impl, 'observeChanges'> | + Pick<_Impl, 'allowMultiple'> | + Pick<_Impl, 'keyboardShortcuts'> | + Pick<_Impl, 'offset'> | + Pick<_Impl, 'context'> | + Pick<_Impl, 'closable'> | + Pick<_Impl, 'dimmerSettings'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'queue'> | + Pick<_Impl, 'onShow'> | + Pick<_Impl, 'onVisible'> | + Pick<_Impl, 'onHide'> | + Pick<_Impl, 'onHidden'> | + Pick<_Impl, 'onApprove'> | + Pick<_Impl, 'onDeny'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Modal Settings @@ -232,10 +259,13 @@ declare namespace SemanticUI { } namespace Modal { - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'close'> | + Pick<_Impl, 'approve'> | + Pick<_Impl, 'deny'>) & + Partial>; interface _Impl { /** @@ -253,10 +283,12 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'scrolling'>) & + Partial>; interface _Impl { /** @@ -270,10 +302,11 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-modal/semantic-ui-modal-tests.ts b/types/semantic-ui-modal/semantic-ui-modal-tests.ts index ed2a10d3e2..422b5de2e6 100644 --- a/types/semantic-ui-modal/semantic-ui-modal-tests.ts +++ b/types/semantic-ui-modal/semantic-ui-modal-tests.ts @@ -1,5 +1,5 @@ function test_modal_static() { - $.fn.modal.settings.error.method = 'method'; + $.fn.modal.settings.error!.method = 'method'; $.fn.modal.settings.namespace = 'namespace'; $.fn.modal.settings.name = 'name'; $.fn.modal.settings.silent = false; @@ -10,23 +10,24 @@ function test_modal_static() { function test_modal() { const selector = '.ui.modal'; - $(selector).modal('show') === $(); - $(selector).modal('hide') === $(); - $(selector).modal('toggle') === $(); - $(selector).modal('refresh') === $(); - $(selector).modal('show dimmer') === $(); - $(selector).modal('hide dimmer') === $(); - $(selector).modal('hide others') === $(); - $(selector).modal('hide all') === $(); - $(selector).modal('cache sizes') === $(); - $(selector).modal('can fit') === true; - $(selector).modal('is active') === true; - $(selector).modal('set active') === $(); - $(selector).modal('attach events', 'selector', 'blur') === $(); - $(selector).modal('destroy') === $(); - $(selector).modal('setting', 'debug', undefined) === false; - $(selector).modal('setting', 'debug') === false; - $(selector).modal('setting', 'debug', true) === $(); + $(selector).modal('show'); // $ExpectType JQuery + $(selector).modal('hide'); // $ExpectType JQuery + $(selector).modal('toggle'); // $ExpectType JQuery + $(selector).modal('refresh'); // $ExpectType JQuery + $(selector).modal('show dimmer'); // $ExpectType JQuery + $(selector).modal('hide dimmer'); // $ExpectType JQuery + $(selector).modal('hide others'); // $ExpectType JQuery + $(selector).modal('hide all'); // $ExpectType JQuery + $(selector).modal('cache sizes'); // $ExpectType JQuery + $(selector).modal('can fit'); // $ExpectType boolean + $(selector).modal('is active'); // $ExpectType boolean + $(selector).modal('set active'); // $ExpectType JQuery + $(selector).modal('attach events', 'selector', 'blur'); // $ExpectType JQuery + $(selector).modal('destroy'); // $ExpectType JQuery + $(selector).modal('setting', 'debug', undefined); // $ExpectType boolean + $(selector).modal('setting', 'debug'); // $ExpectType boolean + $(selector).modal('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).modal('setting', { namespace: 'namespace', name: 'name', @@ -34,7 +35,8 @@ function test_modal() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).modal({ detachable: true, autofocus: false, @@ -57,13 +59,13 @@ function test_modal() { }, transition: 'fade', onShow() { - this === $(); + this; // $ExpectType JQuery }, onHide() { - this === $(); + this; // $ExpectType JQuery }, onChange() { - this === $(); + this; // $ExpectType JQuery }, selector: { dimmable: '.dimmable', @@ -93,27 +95,30 @@ function test_modal() { duration: 400, queue: true, onShow() { - this === $(); + this; // $ExpectType JQuery }, onVisible() { - this === $(); + this; // $ExpectType JQuery }, onHide($element) { - this === $(); - $element === $(); + this; // $ExpectType JQuery + $element; // $ExpectType JQuery + return false; }, onHidden() { - this === $(); + this; // $ExpectType JQuery }, onApprove($element) { - this === $(); - $element === $(); + this; // $ExpectType JQuery + $element; // $ExpectType JQuery + return false; }, onDeny($element) { - this === $(); - $element === $(); + this; // $ExpectType JQuery + $element; // $ExpectType JQuery + return false; }, selector: { @@ -128,12 +133,16 @@ function test_modal() { error: { method: 'method' } - }) === $(); - $(selector).modal() === $(); + }); + $(selector).modal(); // $ExpectType JQuery + + $(selector).modal('foo'); // $ExpectError + $(selector).modal({ foo: 'bar' }); // $ExpectError } import modal = require('semantic-ui-modal'); function test_module() { + modal; // $ExpectType Modal $.fn.modal = modal; } From 0657aa2c61eb9b7d3f82c98c4281d1d3cbdcd752 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 12:31:11 -0400 Subject: [PATCH 0107/1618] [semantic-ui-nag] Different weak-type workaround. --- types/semantic-ui-nag/global.d.ts | 59 ++++++++++++++----- .../semantic-ui-nag/semantic-ui-nag-tests.ts | 27 +++++---- 2 files changed, 60 insertions(+), 26 deletions(-) diff --git a/types/semantic-ui-nag/global.d.ts b/types/semantic-ui-nag/global.d.ts index 6ac11501cb..5cb597e8da 100644 --- a/types/semantic-ui-nag/global.d.ts +++ b/types/semantic-ui-nag/global.d.ts @@ -13,19 +13,42 @@ declare namespace SemanticUI { */ (behavior: 'clear'): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): NagSettings[K]; - (behavior: 'setting', name: K, value: NagSettings[K]): JQuery; - (behavior: 'setting', value: NagSettings.Param): JQuery; - (settings?: NagSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): NagSettings._Impl[K]; + (behavior: 'setting', name: K, value: NagSettings._Impl[K]): JQuery; + (behavior: 'setting', value: NagSettings): JQuery; + (settings?: NagSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/nag.html} */ - interface NagSettings extends Pick { } + type NagSettings = NagSettings.Param; namespace NagSettings { - type Param = NagSettings | object; + type Param = (Pick<_Impl, 'persist'> | + Pick<_Impl, 'displayTime'> | + Pick<_Impl, 'animation'> | + Pick<_Impl, 'context'> | + Pick<_Impl, 'detachable'> | + Pick<_Impl, 'expires'> | + Pick<_Impl, 'domain'> | + Pick<_Impl, 'path'> | + Pick<_Impl, 'storageMethod'> | + Pick<_Impl, 'key'> | + Pick<_Impl, 'value'> | + Pick<_Impl, 'speed'> | + Pick<_Impl, 'easing'> | + Pick<_Impl, 'onHide'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Behavior @@ -152,10 +175,12 @@ declare namespace SemanticUI { } namespace Nag { - interface AnimationSettings extends Pick { } + type AnimationSettings = AnimationSettings.Param; namespace AnimationSettings { - type Param = AnimationSettings | object; + type Param = (Pick<_Impl, 'show'> | + Pick<_Impl, 'hide'>) & + Partial>; interface _Impl { /** @@ -169,10 +194,12 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'bottom'> | + Pick<_Impl, 'fixed'>) & + Partial>; interface _Impl { /** @@ -186,10 +213,11 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'close'>) & + Partial>; interface _Impl { /** @@ -199,10 +227,13 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'noCookieStorage'> | + Pick<_Impl, 'noStorage'> | + Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-nag/semantic-ui-nag-tests.ts b/types/semantic-ui-nag/semantic-ui-nag-tests.ts index 45a95b827b..a559f0a10d 100644 --- a/types/semantic-ui-nag/semantic-ui-nag-tests.ts +++ b/types/semantic-ui-nag/semantic-ui-nag-tests.ts @@ -1,5 +1,5 @@ function test_nag_static() { - $.fn.nag.settings.error.method = 'method'; + $.fn.nag.settings.error!.method = 'method'; $.fn.nag.settings.namespace = 'namespace'; $.fn.nag.settings.name = 'name'; $.fn.nag.settings.silent = false; @@ -10,13 +10,14 @@ function test_nag_static() { function test_nag() { const selector = '.ui.nag'; - $(selector).nag('show') === $(); - $(selector).nag('hide') === $(); - $(selector).nag('clear') === $(); - $(selector).nag('destroy') === $(); - $(selector).nag('setting', 'debug', undefined) === false; - $(selector).nag('setting', 'debug') === false; - $(selector).nag('setting', 'debug', true) === $(); + $(selector).nag('show'); // $ExpectType JQuery + $(selector).nag('hide'); // $ExpectType JQuery + $(selector).nag('clear'); // $ExpectType JQuery + $(selector).nag('destroy'); // $ExpectType JQuery + $(selector).nag('setting', 'debug', undefined); // $ExpectType boolean + $(selector).nag('setting', 'debug'); // $ExpectType boolean + $(selector).nag('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).nag('setting', { namespace: 'namespace', name: 'name', @@ -24,7 +25,8 @@ function test_nag() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).nag({ persist: true, displayTime: 0, @@ -43,7 +45,7 @@ function test_nag() { speed: 500, easing: 'easeOutQuad', onHide() { - this === $(); + this; // $ExpectType JQuery }, className: { bottom: 'bottom', @@ -57,12 +59,13 @@ function test_nag() { noStorage: 'noStorage', method: 'method' } - }) === $(); - $(selector).nag() === $(); + }); + $(selector).nag(); // $ExpectType JQuery } import nag = require('semantic-ui-nag'); function test_module() { + nag; // $ExpectType Nag $.fn.nag = nag; } From 1dbc9189825920ab8044e2b5c1d0573ae6c25ea4 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 12:36:08 -0400 Subject: [PATCH 0108/1618] [semantic-ui-popup] Different weak-type workaround. --- types/semantic-ui-popup/global.d.ts | 97 ++++++++++++++++--- .../semantic-ui-popup-tests.ts | 74 +++++++------- 2 files changed, 122 insertions(+), 49 deletions(-) diff --git a/types/semantic-ui-popup/global.d.ts b/types/semantic-ui-popup/global.d.ts index 835d196089..f9504e1780 100644 --- a/types/semantic-ui-popup/global.d.ts +++ b/types/semantic-ui-popup/global.d.ts @@ -58,19 +58,66 @@ declare namespace SemanticUI { * Removes popup from the page */ (behavior: 'remove popup'): JQuery; - (behavior: 'setting', name: K, value?: undefined): PopupSettings[K]; - (behavior: 'setting', name: K, value: PopupSettings[K]): JQuery; - (behavior: 'setting', value: PopupSettings.Param): JQuery; - (settings?: PopupSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): PopupSettings._Impl[K]; + (behavior: 'setting', name: K, value: PopupSettings._Impl[K]): JQuery; + (behavior: 'setting', value: PopupSettings): JQuery; + (settings?: PopupSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/popup.html#/settings} */ - interface PopupSettings extends Pick { } + type PopupSettings = PopupSettings.Param; namespace PopupSettings { - type Param = PopupSettings | object; + type Param = (Pick<_Impl, 'popup'> | + Pick<_Impl, 'exclusive'> | + Pick<_Impl, 'movePopup'> | + Pick<_Impl, 'observeChanges'> | + Pick<_Impl, 'boundary'> | + Pick<_Impl, 'context'> | + Pick<_Impl, 'scrollContext'> | + Pick<_Impl, 'jitter'> | + Pick<_Impl, 'position'> | + Pick<_Impl, 'inline'> | + Pick<_Impl, 'preserve'> | + Pick<_Impl, 'prefer'> | + Pick<_Impl, 'lastResort'> | + Pick<_Impl, 'on'> | + Pick<_Impl, 'delay'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'setFluidWidth'> | + Pick<_Impl, 'hoverable'> | + Pick<_Impl, 'closable'> | + Pick<_Impl, 'addTouchEvents'> | + Pick<_Impl, 'hideOnScroll'> | + Pick<_Impl, 'target'> | + Pick<_Impl, 'distanceAway'> | + Pick<_Impl, 'offset'> | + Pick<_Impl, 'maxSearchDepth'> | + Pick<_Impl, 'onCreate'> | + Pick<_Impl, 'onRemove'> | + Pick<_Impl, 'onShow'> | + Pick<_Impl, 'onVisible'> | + Pick<_Impl, 'onHide'> | + Pick<_Impl, 'onHidden'> | + Pick<_Impl, 'onUnplaceable'> | + Pick<_Impl, 'variation'> | + Pick<_Impl, 'content'> | + Pick<_Impl, 'title'> | + Pick<_Impl, 'html'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Popup Settings @@ -352,10 +399,12 @@ declare namespace SemanticUI { } namespace Popup { - interface DelaySettings extends Pick { } + type DelaySettings = DelaySettings.Param; namespace DelaySettings { - type Param = DelaySettings | object; + type Param = (Pick<_Impl, 'show'> | + Pick<_Impl, 'hide'>) & + Partial>; interface _Impl { show: number; @@ -363,10 +412,11 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'popup'>) & + Partial>; interface _Impl { /** @@ -376,10 +426,16 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { - type Param = MetadataSettings | object; + type Param = (Pick<_Impl, 'content'> | + Pick<_Impl, 'html'> | + Pick<_Impl, 'offset'> | + Pick<_Impl, 'position'> | + Pick<_Impl, 'title'> | + Pick<_Impl, 'variation'>) & + Partial>; interface _Impl { /** @@ -409,10 +465,14 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'loading'> | + Pick<_Impl, 'popup'> | + Pick<_Impl, 'position'> | + Pick<_Impl, 'visible'>) & + Partial>; interface _Impl { /** @@ -434,10 +494,15 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'invalidPosition'> | + Pick<_Impl, 'cannotPlace'> | + Pick<_Impl, 'method'> | + Pick<_Impl, 'noTransition'> | + Pick<_Impl, 'notFound'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-popup/semantic-ui-popup-tests.ts b/types/semantic-ui-popup/semantic-ui-popup-tests.ts index b9cda09890..9b00a9dba8 100644 --- a/types/semantic-ui-popup/semantic-ui-popup-tests.ts +++ b/types/semantic-ui-popup/semantic-ui-popup-tests.ts @@ -1,5 +1,5 @@ function test_popup_static() { - $.fn.popup.settings.error.method = 'method'; + $.fn.popup.settings.error!.method = 'method'; $.fn.popup.settings.namespace = 'namespace'; $.fn.popup.settings.name = 'name'; $.fn.popup.settings.silent = false; @@ -10,21 +10,22 @@ function test_popup_static() { function test_popup() { const selector = '.ui.popup'; - $(selector).popup('show') === $(); - $(selector).popup('hide') === $(); - $(selector).popup('hide all') === $(); - $(selector).popup('get popup') === $(); - $(selector).popup('change content', '
') === $(); - $(selector).popup('toggle') === $(); - $(selector).popup('is visible') === true; - $(selector).popup('is hidden') === true; - $(selector).popup('exists') === true; - $(selector).popup('reposition') === $(); - $(selector).popup('set position', 'position') === $(); - $(selector).popup('destroy') === $(); - $(selector).popup('setting', 'debug', undefined) === false; - $(selector).popup('setting', 'debug') === false; - $(selector).popup('setting', 'debug', true) === $(); + $(selector).popup('show'); // $ExpectType JQuery + $(selector).popup('hide'); // $ExpectType JQuery + $(selector).popup('hide all'); // $ExpectType JQuery + $(selector).popup('get popup'); // $ExpectType JQuery + $(selector).popup('change content', '
'); // $ExpectType JQuery + $(selector).popup('toggle'); // $ExpectType JQuery + $(selector).popup('is visible'); // $ExpectType boolean + $(selector).popup('is hidden'); // $ExpectType boolean + $(selector).popup('exists'); // $ExpectType boolean + $(selector).popup('reposition'); // $ExpectType JQuery + $(selector).popup('set position', 'position'); // $ExpectType JQuery + $(selector).popup('destroy'); // $ExpectType JQuery + $(selector).popup('setting', 'debug', undefined); // $ExpectType boolean + $(selector).popup('setting', 'debug'); // $ExpectType boolean + $(selector).popup('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).popup('setting', { namespace: 'namespace', name: 'name', @@ -32,7 +33,8 @@ function test_popup() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).popup({ popup: $(), exclusive: true, @@ -64,34 +66,36 @@ function test_popup() { offset: 2, maxSearchDepth: 10, onCreate($module) { - this === $(); - $module === $(); + this; // $ExpectType JQuery + $module; // $ExpectType JQuery }, onRemove($module) { - this === $(); - $module === $(); + this; // $ExpectType JQuery + $module; // $ExpectType JQuery }, onShow($module) { - this === $(); - $module === $(); + this; // $ExpectType JQuery + $module; // $ExpectType JQuery + return false; }, onVisible($module) { - this === $(); - $module === $(); + this; // $ExpectType JQuery + $module; // $ExpectType JQuery }, onHide($module) { - this === $(); - $module === $(); + this; // $ExpectType JQuery + $module; // $ExpectType JQuery + return false; }, onHidden($module) { - this === $(); - $module === $(); + this; // $ExpectType JQuery + $module; // $ExpectType JQuery }, onUnplaceable($module) { - this === $(); - $module === $(); + this; // $ExpectType JQuery + $module; // $ExpectType JQuery }, variation: 'variation', content: 'content', @@ -121,12 +125,16 @@ function test_popup() { noTransition: 'noTransition', notFound: 'notFound' } - }) === $(); - $(selector).popup() === $(); + }); + $(selector).popup(); // $ExpectType JQuery + + $(selector).popup('foo'); // $ExpectError + $(selector).popup({ foo: 'bar' }); // $ExpectError } import popup = require('semantic-ui-popup'); function test_module() { + popup; // $ExpectType Popup $.fn.popup = popup; } From 97138d4e82f34ad1f4c1bceca4408c6c598ef279 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 12:36:41 -0400 Subject: [PATCH 0109/1618] [semantic-ui-nag] Add weak type tests. --- types/semantic-ui-nag/semantic-ui-nag-tests.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/semantic-ui-nag/semantic-ui-nag-tests.ts b/types/semantic-ui-nag/semantic-ui-nag-tests.ts index a559f0a10d..ba39bfad5d 100644 --- a/types/semantic-ui-nag/semantic-ui-nag-tests.ts +++ b/types/semantic-ui-nag/semantic-ui-nag-tests.ts @@ -61,6 +61,9 @@ function test_nag() { } }); $(selector).nag(); // $ExpectType JQuery + + $(selector).nag('foo'); // $ExpectError + $(selector).nag({ foo: 'bar' }); // $ExpectError } import nag = require('semantic-ui-nag'); From 061a5f686ca3b29025fbfeb20c830e469ffe797e Mon Sep 17 00:00:00 2001 From: juraj kocan Date: Fri, 30 Jun 2017 18:38:21 +0200 Subject: [PATCH 0110/1618] add basic comment --- types/osmosis/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/osmosis/index.d.ts b/types/osmosis/index.d.ts index ee5f2700ea..e76db57828 100644 --- a/types/osmosis/index.d.ts +++ b/types/osmosis/index.d.ts @@ -1,3 +1,8 @@ +// Type definitions for osmosis 1.1.4 +// Project: https://github.com/rchipka/node-osmosis +// Definitions by: Mohamed Hegazy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + export interface Osmosis { /** * define domain where osmosis is parsing data from From 59fde981fc2c345a5d60361cb9c5fcf4851c66c7 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 12:50:50 -0400 Subject: [PATCH 0111/1618] [semantic-ui-progress] Different weak-type workaround. --- types/semantic-ui-progress/global.d.ts | 86 ++++++++++---- .../semantic-ui-progress-tests.ts | 110 +++++++++--------- 2 files changed, 124 insertions(+), 72 deletions(-) diff --git a/types/semantic-ui-progress/global.d.ts b/types/semantic-ui-progress/global.d.ts index 06fe3b9892..4d7cd242c9 100644 --- a/types/semantic-ui-progress/global.d.ts +++ b/types/semantic-ui-progress/global.d.ts @@ -123,19 +123,44 @@ declare namespace SemanticUI { */ (behavior: 'remove error'): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ProgressSettings[K]; - (behavior: 'setting', name: K, value: ProgressSettings[K]): JQuery; - (behavior: 'setting', value: ProgressSettings.Param): JQuery; - (settings?: ProgressSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): ProgressSettings._Impl[K]; + (behavior: 'setting', name: K, value: ProgressSettings._Impl[K]): JQuery; + (behavior: 'setting', value: ProgressSettings): JQuery; + (settings?: ProgressSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/progress.html#/settings} */ - interface ProgressSettings extends Pick { } + type ProgressSettings = ProgressSettings.Param; namespace ProgressSettings { - type Param = ProgressSettings | object; + type Param = (Pick<_Impl, 'autoSuccess'> | + Pick<_Impl, 'showActivity'> | + Pick<_Impl, 'limitValues'> | + Pick<_Impl, 'label'> | + Pick<_Impl, 'random'> | + Pick<_Impl, 'precision'> | + Pick<_Impl, 'total'> | + Pick<_Impl, 'value'> | + Pick<_Impl, 'onChange'> | + Pick<_Impl, 'onSuccess'> | + Pick<_Impl, 'onActive'> | + Pick<_Impl, 'onError'> | + Pick<_Impl, 'onWarning'> | + Pick<_Impl, 'text'> | + Pick<_Impl, 'regExp'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Progress Settings @@ -287,10 +312,12 @@ declare namespace SemanticUI { } namespace Progress { - interface RandomSettings extends Pick { } + type RandomSettings = RandomSettings.Param; namespace RandomSettings { - type Param = RandomSettings | object; + type Param = (Pick<_Impl, 'min'> | + Pick<_Impl, 'max'>) & + Partial>; interface _Impl { /** @@ -304,10 +331,16 @@ declare namespace SemanticUI { } } - interface TextSettings extends Pick { } + type TextSettings = TextSettings.Param; namespace TextSettings { - type Param = TextSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'success'> | + Pick<_Impl, 'warning'> | + Pick<_Impl, 'percent'> | + Pick<_Impl, 'ratio'>) & + Partial>; interface _Impl { /** @@ -337,10 +370,11 @@ declare namespace SemanticUI { } } - interface RegExpSettings extends Pick { } + type RegExpSettings = RegExpSettings.Param; namespace RegExpSettings { - type Param = RegExpSettings | object; + type Param = (Pick<_Impl, 'variable'>) & + Partial>; interface _Impl { /** @@ -350,10 +384,13 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'bar'> | + Pick<_Impl, 'label'> | + Pick<_Impl, 'progress'> ) & + Partial>; interface _Impl { /** @@ -371,10 +408,13 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { - type Param = MetadataSettings | object; + type Param = (Pick<_Impl, 'percent'> | + Pick<_Impl, 'total'> | + Pick<_Impl, 'value'>) & + Partial>; interface _Impl { /** @@ -392,10 +432,14 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'success'> | + Pick<_Impl, 'warning'>) & + Partial>; interface _Impl { /** @@ -417,10 +461,12 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'method'> | + Pick<_Impl, 'nonNumeric'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-progress/semantic-ui-progress-tests.ts b/types/semantic-ui-progress/semantic-ui-progress-tests.ts index b950ed786f..747283828b 100644 --- a/types/semantic-ui-progress/semantic-ui-progress-tests.ts +++ b/types/semantic-ui-progress/semantic-ui-progress-tests.ts @@ -1,5 +1,5 @@ function test_progress_static() { - $.fn.progress.settings.error.method = 'method'; + $.fn.progress.settings.error!.method = 'method'; $.fn.progress.settings.namespace = 'namespace'; $.fn.progress.settings.name = 'name'; $.fn.progress.settings.silent = false; @@ -10,39 +10,40 @@ function test_progress_static() { function test_progress() { const selector = '.ui.progress'; - $(selector).progress('set percent', 10) === $(); - $(selector).progress('set progress', 25) === $(); - $(selector).progress('increment', 5) === $(); - $(selector).progress('decrement', 2) === $(); - $(selector).progress('update progress', 45) === $(); - $(selector).progress('complete') === $(); - $(selector).progress('reset') === $(); - $(selector).progress('set total', 100) === $(); - $(selector).progress('get text', 'text') === 'text'; - $(selector).progress('get normalized value', 20) === 40; - $(selector).progress('get percent') === 22; - $(selector).progress('get value') === 45; - $(selector).progress('get total') === 67; - $(selector).progress('is complete') === false; - $(selector).progress('is success') === false; - $(selector).progress('is warning') === false; - $(selector).progress('is error') === false; - $(selector).progress('is active') === false; - $(selector).progress('set active') === $(); - $(selector).progress('set warning') === $(); - $(selector).progress('set success') === $(); - $(selector).progress('set error') === $(); - $(selector).progress('set duration', 4) === $(); - $(selector).progress('set label', 'label') === $(); - $(selector).progress('set bar label', 'bar label') === $(); - $(selector).progress('remove active') === $(); - $(selector).progress('remove warning') === $(); - $(selector).progress('remove success') === $(); - $(selector).progress('remove error') === $(); - $(selector).progress('destroy') === $(); - $(selector).progress('setting', 'debug', undefined) === false; - $(selector).progress('setting', 'debug') === false; - $(selector).progress('setting', 'debug', true) === $(); + $(selector).progress('set percent', 10); // $ExpectType JQuery + $(selector).progress('set progress', 25); // $ExpectType JQuery + $(selector).progress('increment', 5); // $ExpectType JQuery + $(selector).progress('decrement', 2); // $ExpectType JQuery + $(selector).progress('update progress', 45); // $ExpectType JQuery + $(selector).progress('complete'); // $ExpectType JQuery + $(selector).progress('reset'); // $ExpectType JQuery + $(selector).progress('set total', 100); // $ExpectType JQuery + $(selector).progress('get text', 'text'); // $ExpectType string + $(selector).progress('get normalized value', 20); // $ExpectType number + $(selector).progress('get percent'); // $ExpectType number + $(selector).progress('get value'); // $ExpectType number + $(selector).progress('get total'); // $ExpectType number + $(selector).progress('is complete'); // $ExpectType boolean + $(selector).progress('is success'); // $ExpectType boolean + $(selector).progress('is warning'); // $ExpectType boolean + $(selector).progress('is error'); // $ExpectType boolean + $(selector).progress('is active'); // $ExpectType boolean + $(selector).progress('set active'); // $ExpectType JQuery + $(selector).progress('set warning'); // $ExpectType JQuery + $(selector).progress('set success'); // $ExpectType JQuery + $(selector).progress('set error'); // $ExpectType JQuery + $(selector).progress('set duration', 4); // $ExpectType JQuery + $(selector).progress('set label', 'label'); // $ExpectType JQuery + $(selector).progress('set bar label', 'bar label'); // $ExpectType JQuery + $(selector).progress('remove active'); // $ExpectType JQuery + $(selector).progress('remove warning'); // $ExpectType JQuery + $(selector).progress('remove success'); // $ExpectType JQuery + $(selector).progress('remove error'); // $ExpectType JQuery + $(selector).progress('destroy'); // $ExpectType JQuery + $(selector).progress('setting', 'debug', undefined); // $ExpectType boolean + $(selector).progress('setting', 'debug'); // $ExpectType boolean + $(selector).progress('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).progress('setting', { namespace: 'namespace', name: 'name', @@ -50,7 +51,8 @@ function test_progress() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).progress({ autoSuccess: false, showActivity: true, @@ -64,29 +66,29 @@ function test_progress() { total: 10, value: 20, onChange(percent, value, total) { - this === $(); - percent === 10; - value === 20; - total === 30; + this; // $ExpectType JQuery + percent; // $ExpectType number + value; // $ExpectType number + total; // $ExpectType number }, onSuccess(total) { - this === $(); - total === 30; + this; // $ExpectType JQuery + total; // $ExpectType number }, onActive(value, total) { - this === $(); - value === 20; - total === 30; + this; // $ExpectType JQuery + value; // $ExpectType number + total; // $ExpectType number }, onError(value, total) { - this === $(); - value === 20; - total === 30; + this; // $ExpectType JQuery + value; // $ExpectType number + total; // $ExpectType number }, onWarning(value, total) { - this === $(); - value === 20; - total === 30; + this; // $ExpectType JQuery + value; // $ExpectType number + total; // $ExpectType number }, text: { active: 'active', @@ -119,12 +121,16 @@ function test_progress() { method: 'method', nonNumeric: 'nonNumeric' } - }) === $(); - $(selector).progress() === $(); + }); + $(selector).progress(); // $ExpectType JQuery + + $(selector).progress('foo'); // $ExpectError + $(selector).progress({ foo: 'bar' }); // $ExpectError } import progress = require('semantic-ui-progress'); function test_module() { + progress; // $ExpectType Progress $.fn.progress = progress; } From a54be1a39ad79190087b9380e7f3415f97b81e8b Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 13:00:41 -0400 Subject: [PATCH 0112/1618] [semantic-ui-rating] Different weak-type workaround. --- types/semantic-ui-progress/global.d.ts | 2 +- types/semantic-ui-rating/global.d.ts | 43 +++++++++++++------ .../semantic-ui-rating-tests.ts | 36 +++++++++------- 3 files changed, 53 insertions(+), 28 deletions(-) diff --git a/types/semantic-ui-progress/global.d.ts b/types/semantic-ui-progress/global.d.ts index 4d7cd242c9..da83f68dbe 100644 --- a/types/semantic-ui-progress/global.d.ts +++ b/types/semantic-ui-progress/global.d.ts @@ -389,7 +389,7 @@ declare namespace SemanticUI { namespace SelectorSettings { type Param = (Pick<_Impl, 'bar'> | Pick<_Impl, 'label'> | - Pick<_Impl, 'progress'> ) & + Pick<_Impl, 'progress'>) & Partial>; interface _Impl { diff --git a/types/semantic-ui-rating/global.d.ts b/types/semantic-ui-rating/global.d.ts index 5fae40e3e3..e1f163ae0e 100644 --- a/types/semantic-ui-rating/global.d.ts +++ b/types/semantic-ui-rating/global.d.ts @@ -27,19 +27,33 @@ declare namespace SemanticUI { */ (behavior: 'clear rating'): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): RatingSettings[K]; - (behavior: 'setting', name: K, value: RatingSettings[K]): JQuery; - (behavior: 'setting', value: RatingSettings.Param): JQuery; - (settings?: RatingSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): RatingSettings._Impl[K]; + (behavior: 'setting', name: K, value: RatingSettings._Impl[K]): JQuery; + (behavior: 'setting', value: RatingSettings): JQuery; + (settings?: RatingSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/rating.html#/settings} */ - interface RatingSettings extends Pick { } + type RatingSettings = RatingSettings.Param; namespace RatingSettings { - type Param = RatingSettings | object; + type Param = (Pick<_Impl, 'initialRating'> | + Pick<_Impl, 'fireOnInit'> | + Pick<_Impl, 'clearable'> | + Pick<_Impl, 'interactive'> | + Pick<_Impl, 'onRate'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Rating Settings @@ -134,10 +148,11 @@ declare namespace SemanticUI { } namespace Rating { - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'icon'>) & + Partial>; interface _Impl { /** @@ -147,10 +162,13 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'hover'> | + Pick<_Impl, 'loading'>) & + Partial>; interface _Impl { /** @@ -168,10 +186,11 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'action'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-rating/semantic-ui-rating-tests.ts b/types/semantic-ui-rating/semantic-ui-rating-tests.ts index 8ea94b61aa..efc30f92d7 100644 --- a/types/semantic-ui-rating/semantic-ui-rating-tests.ts +++ b/types/semantic-ui-rating/semantic-ui-rating-tests.ts @@ -1,5 +1,5 @@ function test_rating_static() { - $.fn.rating.settings.error.action = 'action'; + $.fn.rating.settings.error!.action = 'action'; $.fn.rating.settings.namespace = 'namespace'; $.fn.rating.settings.name = 'name'; $.fn.rating.settings.silent = false; @@ -10,15 +10,16 @@ function test_rating_static() { function test_rating() { const selector = '.ui.rating'; - $(selector).rating('set rating', 3) === $(); - $(selector).rating('get rating') === 4; - $(selector).rating('disable') === $(); - $(selector).rating('enable') === $(); - $(selector).rating('clear rating') === $(); - $(selector).rating('destroy') === $(); - $(selector).rating('setting', 'debug', undefined) === false; - $(selector).rating('setting', 'debug') === false; - $(selector).rating('setting', 'debug', true) === $(); + $(selector).rating('set rating', 3); // $ExpectType JQuery + $(selector).rating('get rating'); // $ExpectType number + $(selector).rating('disable'); // $ExpectType JQuery + $(selector).rating('enable'); // $ExpectType JQuery + $(selector).rating('clear rating'); // $ExpectType JQuery + $(selector).rating('destroy'); // $ExpectType JQuery + $(selector).rating('setting', 'debug', undefined); // $ExpectType boolean + $(selector).rating('setting', 'debug'); // $ExpectType boolean + $(selector).rating('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).rating('setting', { namespace: 'namespace', name: 'name', @@ -26,15 +27,16 @@ function test_rating() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).rating({ initialRating: 0, fireOnInit: false, clearable: false, interactive: true, onRate(value) { - this === $(); - value === 3; + this; // $ExpectType JQuery + value; // $ExpectType number }, selector: { icon: '.icon' @@ -47,12 +49,16 @@ function test_rating() { error: { action: 'action' } - }) === $(); - $(selector).rating() === $(); + }); + $(selector).rating(); // $ExpectType JQuery + + $(selector).rating('foo'); // $ExpectError + $(selector).rating({ foo: 'bar' }); // $ExpectError } import rating = require('semantic-ui-rating'); function test_module() { + rating; // $ExpectType Rating $.fn.rating = rating; } From c8cbb580d0fa95905ad2d3d8c5e93c14a966d995 Mon Sep 17 00:00:00 2001 From: juraj kocan Date: Fri, 30 Jun 2017 19:17:11 +0200 Subject: [PATCH 0113/1618] test osmosis fix --- types/osmosis/index.d.ts | 2 +- types/osmosis/tslint.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/osmosis/index.d.ts b/types/osmosis/index.d.ts index e76db57828..bce44f8ad3 100644 --- a/types/osmosis/index.d.ts +++ b/types/osmosis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for osmosis 1.1.4 +// Type definitions for osmosis 1.0 // Project: https://github.com/rchipka/node-osmosis // Definitions by: Mohamed Hegazy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/osmosis/tslint.json b/types/osmosis/tslint.json index 4c3a548997..f93cf8562a 100644 --- a/types/osmosis/tslint.json +++ b/types/osmosis/tslint.json @@ -1,3 +1,3 @@ { - "extends": "dtslint/dtslint.json" + "extends": "dtslint/dt.json" } From f9f92e80909e2e01dc8c4ae67bfd344d9b74a2cd Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 13:22:36 -0400 Subject: [PATCH 0114/1618] [semantic-ui-search] Different weak-type workaround. --- types/semantic-ui-search/global.d.ts | 109 ++++++++++--- .../semantic-ui-search-tests.ts | 151 ++++++++++-------- 2 files changed, 174 insertions(+), 86 deletions(-) diff --git a/types/semantic-ui-search/global.d.ts b/types/semantic-ui-search/global.d.ts index bb3df65035..d5d265a4af 100644 --- a/types/semantic-ui-search/global.d.ts +++ b/types/semantic-ui-search/global.d.ts @@ -94,19 +94,52 @@ declare namespace SemanticUI { * Removes all events */ (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): SearchSettings[K]; - (behavior: 'setting', name: K, value: SearchSettings[K]): JQuery; - (behavior: 'setting', value: SearchSettings.Param): JQuery; - (settings?: SearchSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): SearchSettings._Impl[K]; + (behavior: 'setting', name: K, value: SearchSettings._Impl[K]): JQuery; + (behavior: 'setting', value: SearchSettings): JQuery; + (settings?: SearchSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/search.html#/settings} */ - interface SearchSettings extends Pick { } + type SearchSettings = SearchSettings.Param; namespace SearchSettings { - type Param = SearchSettings | object; + type Param = (Pick<_Impl, 'apiSettings'> | + Pick<_Impl, 'minCharacters'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'maxResults'> | + Pick<_Impl, 'cache'> | + Pick<_Impl, 'source'> | + Pick<_Impl, 'selectFirstResult'> | + Pick<_Impl, 'showNoResults'> | + Pick<_Impl, 'searchFullText'> | + Pick<_Impl, 'fields'> | + Pick<_Impl, 'searchFields'> | + Pick<_Impl, 'hideDelay'> | + Pick<_Impl, 'searchDelay'> | + Pick<_Impl, 'easing'> | + Pick<_Impl, 'onSelect'> | + Pick<_Impl, 'onResultsAdd'> | + Pick<_Impl, 'onSearchQuery'> | + Pick<_Impl, 'onResults'> | + Pick<_Impl, 'onResultsOpen'> | + Pick<_Impl, 'onResultsClose'> | + Pick<_Impl, 'templates'> | + Pick<_Impl, 'regExp'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Behavior @@ -306,10 +339,21 @@ declare namespace SemanticUI { } namespace Search { - interface FieldsSettings extends Pick { } + type FieldsSettings = FieldsSettings.Param; namespace FieldsSettings { - type Param = FieldsSettings | object; + type Param = (Pick<_Impl, 'categories'> | + Pick<_Impl, 'categoryName'> | + Pick<_Impl, 'categoryResults'> | + Pick<_Impl, 'description'> | + Pick<_Impl, 'image'> | + Pick<_Impl, 'price'> | + Pick<_Impl, 'results'> | + Pick<_Impl, 'title'> | + Pick<_Impl, 'action'> | + Pick<_Impl, 'actionText'> | + Pick<_Impl, 'actionURL'>) & + Partial>; interface _Impl { /** @@ -381,10 +425,14 @@ declare namespace SemanticUI { } } - interface TemplatesSettings extends Pick { } + type TemplatesSettings = TemplatesSettings.Param; namespace TemplatesSettings { - type Param = TemplatesSettings | object; + type Param = (Pick<_Impl, 'escape'> | + Pick<_Impl, 'message'> | + Pick<_Impl, 'category'> | + Pick<_Impl, 'standard'>) & + Partial>; interface _Impl { escape(string: string): string; @@ -394,10 +442,12 @@ declare namespace SemanticUI { } } - interface RegExpSettings extends Pick { } + type RegExpSettings = RegExpSettings.Param; namespace RegExpSettings { - type Param = RegExpSettings | object; + type Param = (Pick<_Impl, 'escape'> | + Pick<_Impl, 'beginsWith'>) & + Partial>; interface _Impl { /** @@ -411,10 +461,15 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'prompt'> | + Pick<_Impl, 'searchButton'> | + Pick<_Impl, 'results'> | + Pick<_Impl, 'category'> | + Pick<_Impl, 'result'>) & + Partial>; interface _Impl { /** @@ -440,10 +495,12 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { - type Param = MetadataSettings | object; + type Param = (Pick<_Impl, 'cache'> | + Pick<_Impl, 'results'>) & + Partial>; interface _Impl { /** @@ -457,10 +514,15 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'empty'> | + Pick<_Impl, 'focus'> | + Pick<_Impl, 'loading'> | + Pick<_Impl, 'pressed'>) & + Partial>; interface _Impl { /** @@ -486,10 +548,17 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'source'> | + Pick<_Impl, 'noResults'> | + Pick<_Impl, 'logging'> | + Pick<_Impl, 'noTemplate'> | + Pick<_Impl, 'serverError'> | + Pick<_Impl, 'maxResults'> | + Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-search/semantic-ui-search-tests.ts b/types/semantic-ui-search/semantic-ui-search-tests.ts index 86760f2832..25d964a5db 100644 --- a/types/semantic-ui-search/semantic-ui-search-tests.ts +++ b/types/semantic-ui-search/semantic-ui-search-tests.ts @@ -1,5 +1,5 @@ function test_search_static() { - $.fn.search.settings.error.method = 'method'; + $.fn.search.settings.error!.method = 'method'; $.fn.search.settings.namespace = 'namespace'; $.fn.search.settings.name = 'name'; $.fn.search.settings.silent = false; @@ -10,31 +10,32 @@ function test_search_static() { function test_search() { const selector = '.ui.search'; - $(selector).search('query', () => { }) === $(); - $(selector).search('display message', 'text', 'type') === $(); - $(selector).search('cancel query') === $(); - $(selector).search('search local', 'query') === $(); - $(selector).search('has minimum characters') === true; - $(selector).search('search remote', 'query', () => { }) === $(); - $(selector).search('search object', 'query', {}, ['searchField']) === {}; - $(selector).search('cancel query') === $(); - $(selector).search('is focused') === false; - $(selector).search('is visible') === true; - $(selector).search('is empty') === false; - $(selector).search('get value') === {}; - $(selector).search('get result', 'value') === {}; - $(selector).search('set value', 'value') === $(); - $(selector).search('read cache', 'query') === $(); - $(selector).search('clear cache', 'query') === $(); - $(selector).search('write cache', 'query') === $(); - $(selector).search('add results', 'html') === $(); - $(selector).search('show results', () => { }) === $(); - $(selector).search('hide results', () => { }) === $(); - $(selector).search('generate results', {}) === $(); - $(selector).search('destroy') === $(); - $(selector).search('setting', 'debug', undefined) === false; - $(selector).search('setting', 'debug') === false; - $(selector).search('setting', 'debug', true) === $(); + $(selector).search('query', () => { }); // $ExpectType JQuery + $(selector).search('display message', 'text', 'type'); // $ExpectType JQuery + $(selector).search('cancel query'); // $ExpectType JQuery + $(selector).search('search local', 'query'); // $ExpectType JQuery + $(selector).search('has minimum characters'); // $ExpectType boolean + $(selector).search('search remote', 'query', () => { }); // $ExpectType JQuery + $(selector).search('search object', 'query', {}, ['searchField']); // $ExpectType any + $(selector).search('cancel query'); // $ExpectType JQuery + $(selector).search('is focused'); // $ExpectType boolean + $(selector).search('is visible'); // $ExpectType boolean + $(selector).search('is empty'); // $ExpectType boolean + $(selector).search('get value'); // $ExpectType any + $(selector).search('get result', 'value'); // $ExpectType any + $(selector).search('set value', 'value'); // $ExpectType JQuery + $(selector).search('read cache', 'query'); // $ExpectType JQuery + $(selector).search('clear cache', 'query'); // $ExpectType JQuery + $(selector).search('write cache', 'query'); // $ExpectType JQuery + $(selector).search('add results', 'html'); // $ExpectType JQuery + $(selector).search('show results', () => { }); // $ExpectType JQuery + $(selector).search('hide results', () => { }); // $ExpectType JQuery + $(selector).search('generate results', {}); // $ExpectType JQuery + $(selector).search('destroy'); // $ExpectType JQuery + $(selector).search('setting', 'debug', undefined); // $ExpectType boolean + $(selector).search('setting', 'debug'); // $ExpectType boolean + $(selector).search('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).search('setting', { namespace: 'namespace', name: 'name', @@ -42,7 +43,8 @@ function test_search() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).search({ apiSettings: { on: 'on', @@ -62,56 +64,58 @@ function test_search() { urlData: false, response: false, responseAsync(settings, callback) { - settings === ({} as SemanticUI.ApiSettings); - callback === ((response: any) => { }); + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void }, mockResponse: false, mockResponseAsync(settings, callback) { - settings === ({} as SemanticUI.ApiSettings); - callback === ((response: any) => { }); + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void }, method: 'post', dataType: 'xml', data: {}, beforeSend(settings) { - settings === ({} as SemanticUI.ApiSettings); + settings; // $ExpectType Param }, beforeXHR(xhrObject) { - xhrObject === ({} as JQueryXHR); + xhrObject; // $ExpectType jqXHR }, onRequest(promise, xhr) { - promise === ({} as JQueryDeferred); - xhr === ({} as JQueryXHR); + promise; // $ExpectType Deferred + xhr; // $ExpectType jqXHR }, onResponse(response) { - response === ({} as any); + response; // $ExpectType any }, successTest(response) { - return response === ({} as any); + response; // $ExpectType any + + return false; }, onSuccess(response, element, xhr) { - response === ({} as any); - element === $(); - xhr === ({} as JQueryXHR); + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onComplete(response, element, xhr) { - response === ({} as any); - element === $(); - xhr === ({} as JQueryXHR); + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onFailure(response, element) { - response === ({} as any); - element === $(); + response; // $ExpectType any + element; // $ExpectType JQuery }, onError(errorMessage, element, xhr) { - errorMessage === ''; - element === $(); - xhr === ({} as JQueryXHR); + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onAbort(errorMessage, element, xhr) { - errorMessage === ''; - element === $(); - xhr === ({} as JQueryXHR); + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, regExp: { required: /{\$*[A-z0-9]+}/g, @@ -175,41 +179,52 @@ function test_search() { searchDelay: 10, easing: 'easeOutExpo', onSelect(result, response) { - this === $(); - result === {}; - response === {}; + this; // $ExpectType JQuery + result; // $ExpectType any + response; // $ExpectType any + return false; }, onResultsAdd(html) { - this === $(); - html === 'html'; + this; // $ExpectType JQuery + html; // $ExpectType string + return false; }, onSearchQuery(query) { - this === $(); - query === 'query'; + this; // $ExpectType JQuery + query; // $ExpectType string }, onResults(response) { - this === $(); - response === {}; + this; // $ExpectType JQuery + response; // $ExpectType any }, onResultsOpen() { - this === $(); + this; // $ExpectType JQuery }, onResultsClose() { - this === $(); + this; // $ExpectType JQuery }, templates: { escape(string) { - return string; + string; // $ExpectType string + + return 'escape'; }, message(message, type) { - return message + type; + message; // $ExpectType string + type; // $ExpectType string + + return 'message'; }, category(response) { + response; // $ExpectType any + return 'category'; }, standard(response) { + response; // $ExpectType any + return 'standard'; } }, @@ -244,12 +259,16 @@ function test_search() { maxResults: 'maxResults', method: 'method' } - }) === $(); - $(selector).search() === $(); + }); + $(selector).search(); // $ExpectType JQuery + + $(selector).search('foo'); // $ExpectError + $(selector).search({ foo: 'bar' }); // $ExpectError } import search = require('semantic-ui-search'); function test_module() { + search; // $ExpectType Search $.fn.search = search; } From 257d851fbd19e8e28f9ac4c285f71b87f8728e5c Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 13:32:57 -0400 Subject: [PATCH 0115/1618] [semantic-ui-shape] Different weak-type workaround. --- types/semantic-ui-shape/global.d.ts | 46 +++++++++---- .../semantic-ui-shape-tests.ts | 64 ++++++++++--------- 2 files changed, 69 insertions(+), 41 deletions(-) diff --git a/types/semantic-ui-shape/global.d.ts b/types/semantic-ui-shape/global.d.ts index cfd6cc689e..37bdcc5af7 100644 --- a/types/semantic-ui-shape/global.d.ts +++ b/types/semantic-ui-shape/global.d.ts @@ -83,19 +83,33 @@ declare namespace SemanticUI { */ (behavior: 'get transform down'): Shape.Translation; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ShapeSettings[K]; - (behavior: 'setting', name: K, value: ShapeSettings[K]): JQuery; - (behavior: 'setting', value: ShapeSettings.Param): JQuery; - (settings?: ShapeSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): ShapeSettings._Impl[K]; + (behavior: 'setting', name: K, value: ShapeSettings._Impl[K]): JQuery; + (behavior: 'setting', value: ShapeSettings): JQuery; + (settings?: ShapeSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/shape.html#/settings} */ - interface ShapeSettings extends Pick { } + type ShapeSettings = ShapeSettings.Param; namespace ShapeSettings { - type Param = ShapeSettings | object; + type Param = (Pick<_Impl, 'duration'> | + Pick<_Impl, 'width'> | + Pick<_Impl, 'height'> | + Pick<_Impl, 'beforeChange'> | + Pick<_Impl, 'onChange'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Shape Settings @@ -198,10 +212,12 @@ declare namespace SemanticUI { transform: string; } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'sides'> | + Pick<_Impl, 'side'>) & + Partial>; interface _Impl { /** @@ -215,10 +231,14 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'animating'> | + Pick<_Impl, 'hidden'> | + Pick<_Impl, 'loading'> | + Pick<_Impl, 'active'>) & + Partial>; interface _Impl { /** @@ -240,10 +260,12 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'side'> | + Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-shape/semantic-ui-shape-tests.ts b/types/semantic-ui-shape/semantic-ui-shape-tests.ts index 994909085a..92cb5e6bef 100644 --- a/types/semantic-ui-shape/semantic-ui-shape-tests.ts +++ b/types/semantic-ui-shape/semantic-ui-shape-tests.ts @@ -1,5 +1,5 @@ function test_shape_static() { - $.fn.shape.settings.error.method = 'method'; + $.fn.shape.settings.error!.method = 'method'; $.fn.shape.settings.namespace = 'namespace'; $.fn.shape.settings.name = 'name'; $.fn.shape.settings.silent = false; @@ -10,29 +10,30 @@ function test_shape_static() { function test_shape() { const selector = '.ui.shape'; - $(selector).shape('flip up') === $(); - $(selector).shape('flip down') === $(); - $(selector).shape('flip right') === $(); - $(selector).shape('flip left') === $(); - $(selector).shape('flip over') === $(); - $(selector).shape('flip back') === $(); - $(selector).shape('set next side', $()) === $(); - $(selector).shape('is animating') === false; - $(selector).shape('reset') === $(); - $(selector).shape('queue', 'animation') === $(); - $(selector).shape('repaint') === $(); - $(selector).shape('set default side') === $(); - $(selector).shape('set stage size') === $(); - $(selector).shape('refresh') === $(); - $(selector).shape('get transform down') === { transform: 'transform' }; - $(selector).shape('get transform left') === { transform: 'transform' }; - $(selector).shape('get transform right') === { transform: 'transform' }; - $(selector).shape('get transform up') === { transform: 'transform' }; - $(selector).shape('get transform down') === { transform: 'transform' }; - $(selector).shape('destroy') === $(); - $(selector).shape('setting', 'debug', undefined) === false; - $(selector).shape('setting', 'debug') === false; - $(selector).shape('setting', 'debug', true) === $(); + $(selector).shape('flip up'); // $ExpectType JQuery + $(selector).shape('flip down'); // $ExpectType JQuery + $(selector).shape('flip right'); // $ExpectType JQuery + $(selector).shape('flip left'); // $ExpectType JQuery + $(selector).shape('flip over'); // $ExpectType JQuery + $(selector).shape('flip back'); // $ExpectType JQuery + $(selector).shape('set next side', $()); // $ExpectType JQuery + $(selector).shape('is animating'); // $ExpectType boolean + $(selector).shape('reset'); // $ExpectType JQuery + $(selector).shape('queue', 'animation'); // $ExpectType JQuery + $(selector).shape('repaint'); // $ExpectType JQuery + $(selector).shape('set default side'); // $ExpectType JQuery + $(selector).shape('set stage size'); // $ExpectType JQuery + $(selector).shape('refresh'); // $ExpectType JQuery + $(selector).shape('get transform down'); // $ExpectType Translation + $(selector).shape('get transform left'); // $ExpectType Translation + $(selector).shape('get transform right'); // $ExpectType Translation + $(selector).shape('get transform up'); // $ExpectType Translation + $(selector).shape('get transform down'); // $ExpectType Translation + $(selector).shape('destroy'); // $ExpectType JQuery + $(selector).shape('setting', 'debug', undefined); // $ExpectType boolean + $(selector).shape('setting', 'debug'); // $ExpectType boolean + $(selector).shape('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).shape('setting', { namespace: 'namespace', name: 'name', @@ -40,16 +41,17 @@ function test_shape() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).shape({ duration: 700, width: 'next', height: 200, beforeChange() { - this === $(); + this; // $ExpectType JQuery }, onChange() { - this === $(); + this; // $ExpectType JQuery }, selector: { sides: 'sides', @@ -65,12 +67,16 @@ function test_shape() { side: 'side', method: 'method' } - }) === $(); - $(selector).shape() === $(); + }); + $(selector).shape(); // $ExpectType JQuery + + $(selector).shape('foo'); // $ExpectError + $(selector).shape({ foo: 'bar' }); // $ExpectError } import shape = require('semantic-ui-shape'); function test_module() { + shape; // $ExpectType Shape $.fn.shape = shape; } From 2571300670e802022c4bc161f94005aa4241ecc2 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 13:39:22 -0400 Subject: [PATCH 0116/1618] [semantic-ui-sidebar] Different weak-type workaround. --- types/semantic-ui-sidebar/global.d.ts | 100 ++++++++++++++---- .../semantic-ui-sidebar-tests.ts | 56 +++++----- 2 files changed, 111 insertions(+), 45 deletions(-) diff --git a/types/semantic-ui-sidebar/global.d.ts b/types/semantic-ui-sidebar/global.d.ts index 1217444f53..5ad0228182 100644 --- a/types/semantic-ui-sidebar/global.d.ts +++ b/types/semantic-ui-sidebar/global.d.ts @@ -55,19 +55,47 @@ declare namespace SemanticUI { */ (behavior: 'get transition event'): string; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): SidebarSettings[K]; - (behavior: 'setting', name: K, value: SidebarSettings[K]): JQuery; - (behavior: 'setting', value: SidebarSettings.Param): JQuery; - (settings?: SidebarSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): SidebarSettings._Impl[K]; + (behavior: 'setting', name: K, value: SidebarSettings._Impl[K]): JQuery; + (behavior: 'setting', value: SidebarSettings): JQuery; + (settings?: SidebarSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/sidebar.html#/settings} */ - interface SidebarSettings extends Pick { } + type SidebarSettings = SidebarSettings.Param; namespace SidebarSettings { - type Param = SidebarSettings | object; + type Param = (Pick<_Impl, 'context'> | + Pick<_Impl, 'exclusive'> | + Pick<_Impl, 'closable'> | + Pick<_Impl, 'dimPage'> | + Pick<_Impl, 'scrollLock'> | + Pick<_Impl, 'returnScroll'> | + Pick<_Impl, 'delaySetup'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'mobileTransition'> | + Pick<_Impl, 'defaultTransition'> | + Pick<_Impl, 'useLegacy'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'easing'> | + Pick<_Impl, 'onVisible'> | + Pick<_Impl, 'onShow'> | + Pick<_Impl, 'onChange'> | + Pick<_Impl, 'onHide'> | + Pick<_Impl, 'onHidden'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'regExp'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Behavior @@ -236,20 +264,26 @@ declare namespace SemanticUI { } namespace Sidebar { - interface DefaultTransitionSettings extends Pick { } + type DefaultTransitionSettings = DefaultTransitionSettings.Param; namespace DefaultTransitionSettings { - type Param = DefaultTransitionSettings | object; + type Param = (Pick<_Impl, 'computer'> | + Pick<_Impl, 'mobile'>) & + Partial>; interface _Impl { computer: ComputerSettings; mobile: MobileSettings; } - interface ComputerSettings extends Pick { } + type ComputerSettings = ComputerSettings.Param; namespace ComputerSettings { - type Param = ComputerSettings | object; + type Param = (Pick<_Impl, 'left'> | + Pick<_Impl, 'right'> | + Pick<_Impl, 'top'> | + Pick<_Impl, 'bottom'>) & + Partial>; interface _Impl { /** @@ -271,10 +305,14 @@ declare namespace SemanticUI { } } - interface MobileSettings extends Pick { } + type MobileSettings = MobileSettings.Param; namespace MobileSettings { - type Param = MobileSettings | object; + type Param = (Pick<_Impl, 'left'> | + Pick<_Impl, 'right'> | + Pick<_Impl, 'top'> | + Pick<_Impl, 'bottom'>) & + Partial>; interface _Impl { /** @@ -297,10 +335,21 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'active'> | + Pick<_Impl, 'animating'> | + Pick<_Impl, 'dimmed'> | + Pick<_Impl, 'ios'> | + Pick<_Impl, 'pushable'> | + Pick<_Impl, 'pushed'> | + Pick<_Impl, 'right'> | + Pick<_Impl, 'top'> | + Pick<_Impl, 'left'> | + Pick<_Impl, 'bottom'> | + Pick<_Impl, 'visible'>) & + Partial>; interface _Impl { /** @@ -350,10 +399,12 @@ declare namespace SemanticUI { } } - interface RegExpSettings extends Pick { } + type RegExpSettings = RegExpSettings.Param; namespace RegExpSettings { - type Param = RegExpSettings | object; + type Param = (Pick<_Impl, 'ios'> | + Pick<_Impl, 'mobile'>) & + Partial>; interface _Impl { /** @@ -367,10 +418,14 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'fixed'> | + Pick<_Impl, 'omitted'> | + Pick<_Impl, 'pusher'> | + Pick<_Impl, 'sidebar'>) & + Partial>; interface _Impl { /** @@ -392,10 +447,15 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'method'> | + Pick<_Impl, 'pusher'> | + Pick<_Impl, 'movedSidebar'> | + Pick<_Impl, 'overlay'> | + Pick<_Impl, 'notFound'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-sidebar/semantic-ui-sidebar-tests.ts b/types/semantic-ui-sidebar/semantic-ui-sidebar-tests.ts index c98b73b47c..c747438052 100644 --- a/types/semantic-ui-sidebar/semantic-ui-sidebar-tests.ts +++ b/types/semantic-ui-sidebar/semantic-ui-sidebar-tests.ts @@ -1,5 +1,5 @@ function test_sidebar_static() { - $.fn.sidebar.settings.error.method = 'method'; + $.fn.sidebar.settings.error!.method = 'method'; $.fn.sidebar.settings.namespace = 'namespace'; $.fn.sidebar.settings.name = 'name'; $.fn.sidebar.settings.silent = false; @@ -10,22 +10,23 @@ function test_sidebar_static() { function test_sidebar() { const selector = '.ui.sidebar'; - $(selector).sidebar('attach events', $(), 'toggle') === $(); - $(selector).sidebar('show') === $(); - $(selector).sidebar('hide') === $(); - $(selector).sidebar('toggle') === $(); - $(selector).sidebar('is visible') === false; - $(selector).sidebar('is hidden') === true; - $(selector).sidebar('push page') === $(); - $(selector).sidebar('get direction') === 'top'; - $(selector).sidebar('pull page') === $(); - $(selector).sidebar('add body CSS') === $(); - $(selector).sidebar('remove body CSS') === $(); - $(selector).sidebar('get transition event') === 'transition'; - $(selector).sidebar('destroy') === $(); - $(selector).sidebar('setting', 'debug', undefined) === false; - $(selector).sidebar('setting', 'debug') === false; - $(selector).sidebar('setting', 'debug', true) === $(); + $(selector).sidebar('attach events', $(), 'toggle'); // $ExpectType JQuery + $(selector).sidebar('show'); // $ExpectType JQuery + $(selector).sidebar('hide'); // $ExpectType JQuery + $(selector).sidebar('toggle'); // $ExpectType JQuery + $(selector).sidebar('is visible'); // $ExpectType boolean + $(selector).sidebar('is hidden'); // $ExpectType boolean + $(selector).sidebar('push page'); // $ExpectType JQuery + $(selector).sidebar('get direction'); // $ExpectType string + $(selector).sidebar('pull page'); // $ExpectType JQuery + $(selector).sidebar('add body CSS'); // $ExpectType JQuery + $(selector).sidebar('remove body CSS'); // $ExpectType JQuery + $(selector).sidebar('get transition event'); // $ExpectType string + $(selector).sidebar('destroy'); // $ExpectType JQuery + $(selector).sidebar('setting', 'debug', undefined); // $ExpectType boolean + $(selector).sidebar('setting', 'debug'); // $ExpectType boolean + $(selector).sidebar('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).sidebar('setting', { namespace: 'namespace', name: 'name', @@ -33,7 +34,8 @@ function test_sidebar() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).sidebar({ context: $(), exclusive: false, @@ -62,19 +64,19 @@ function test_sidebar() { duration: 20, easing: 'easeInOutQuint', onVisible() { - this === $(); + this; // $ExpectType JQuery }, onShow() { - this === $(); + this; // $ExpectType JQuery }, onChange() { - this === $(); + this; // $ExpectType JQuery }, onHide() { - this === $(); + this; // $ExpectType JQuery }, onHidden() { - this === $(); + this; // $ExpectType JQuery }, className: { active: 'active', @@ -107,12 +109,16 @@ function test_sidebar() { overlay: 'overlay', notFound: 'notFound' } - }) === $(); - $(selector).sidebar() === $(); + }); + $(selector).sidebar(); // $ExpectType JQuery + + $(selector).sidebar('foo'); // $ExpectError + $(selector).sidebar({ foo: 'bar' }); // $ExpectError } import sidebar = require('semantic-ui-sidebar'); function test_module() { + sidebar; // $ExpectType Sidebar $.fn.sidebar = sidebar; } From 2f49c9c475b4b701aedc73a4cefb6aabc57b5cf7 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 13:43:32 -0400 Subject: [PATCH 0117/1618] [semantic-ui-site] Different weak-type workaround. --- types/semantic-ui-site/global.d.ts | 30 ++++++++++++++----- .../semantic-ui-site-tests.ts | 20 ++++++++----- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/types/semantic-ui-site/global.d.ts b/types/semantic-ui-site/global.d.ts index 1cd7caa858..d03516fc9b 100644 --- a/types/semantic-ui-site/global.d.ts +++ b/types/semantic-ui-site/global.d.ts @@ -11,16 +11,25 @@ declare namespace SemanticUI { settings: SiteSettings; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): SiteSettings[K]; - (behavior: 'setting', name: K, value: SiteSettings[K]): JQuery; - (behavior: 'setting', value: SiteSettings.Param): JQuery; - (settings?: SiteSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): SiteSettings._Impl[K]; + (behavior: 'setting', name: K, value: SiteSettings._Impl[K]): JQuery; + (behavior: 'setting', value: SiteSettings): JQuery; + (settings?: SiteSettings): JQuery; } - interface SiteSettings extends Pick { } + type SiteSettings = SiteSettings.Param; namespace SiteSettings { - type Param = SiteSettings | object; + type Param = (Pick<_Impl, 'modules'> | + Pick<_Impl, 'siteNamespace'> | + Pick<_Impl, 'namespaceStub'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { modules: string[]; @@ -68,10 +77,15 @@ declare namespace SemanticUI { } namespace Site { - interface NamespaceStubSettings extends Pick { } + type NamespaceStubSettings = NamespaceStubSettings.Param; namespace NamespaceStubSettings { - type Param = NamespaceStubSettings | object; + type Param = (Pick<_Impl, 'cache'> | + Pick<_Impl, 'config'> | + Pick<_Impl, 'sections'> | + Pick<_Impl, 'section'> | + Pick<_Impl, 'utilities'>) & + Partial>; interface _Impl { cache: any; diff --git a/types/semantic-ui-site/semantic-ui-site-tests.ts b/types/semantic-ui-site/semantic-ui-site-tests.ts index 0eaddfc5b2..a5fac3ff89 100644 --- a/types/semantic-ui-site/semantic-ui-site-tests.ts +++ b/types/semantic-ui-site/semantic-ui-site-tests.ts @@ -16,10 +16,11 @@ function test_site_static() { function test_site() { const selector = '.ui.site'; - $(selector).site('destroy') === $(); - $(selector).site('setting', 'debug', undefined) === false; - $(selector).site('setting', 'debug') === false; - $(selector).site('setting', 'debug', true) === $(); + $(selector).site('destroy'); // $ExpectType JQuery + $(selector).site('setting', 'debug', undefined); // $ExpectType boolean + $(selector).site('setting', 'debug'); // $ExpectType boolean + $(selector).site('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).site('setting', { namespace: 'namespace', name: 'name', @@ -27,7 +28,8 @@ function test_site() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).site({ modules: [ 'module1', @@ -41,12 +43,16 @@ function test_site() { section: {}, utilities: {} } - }) === $(); - $(selector).site() === $(); + }); + $(selector).site(); // $ExpectType JQuery + + $(selector).site('foo'); // $ExpectError + $(selector).site({ foo: 'bar' }); // $ExpectError } import site = require('semantic-ui-site'); function test_module() { + site; // $ExpectType Site $.fn.site = site; } From b71e354e522eafea0b0ab6e3a5f6e99e6a448b0c Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 13:47:01 -0400 Subject: [PATCH 0118/1618] [semantic-ui-sticky] Different weak-type workaround. --- types/semantic-ui-sticky/global.d.ts | 51 +++++++++++++++---- .../semantic-ui-sticky-tests.ts | 36 +++++++------ 2 files changed, 62 insertions(+), 25 deletions(-) diff --git a/types/semantic-ui-sticky/global.d.ts b/types/semantic-ui-sticky/global.d.ts index 683d1aafc7..220e57a011 100644 --- a/types/semantic-ui-sticky/global.d.ts +++ b/types/semantic-ui-sticky/global.d.ts @@ -11,19 +11,40 @@ declare namespace SemanticUI { */ (behavior: 'refresh'): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): StickySettings[K]; - (behavior: 'setting', name: K, value: StickySettings[K]): JQuery; - (behavior: 'setting', value: StickySettings.Param): JQuery; - (settings?: StickySettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): StickySettings._Impl[K]; + (behavior: 'setting', name: K, value: StickySettings._Impl[K]): JQuery; + (behavior: 'setting', value: StickySettings): JQuery; + (settings?: StickySettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/sticky.html#/settings} */ - interface StickySettings extends Pick { } + type StickySettings = StickySettings.Param; namespace StickySettings { - type Param = StickySettings | object; + type Param = (Pick<_Impl, 'pushing'> | + Pick<_Impl, 'jitter'> | + Pick<_Impl, 'observeChanges'> | + Pick<_Impl, 'context'> | + Pick<_Impl, 'scrollContext'> | + Pick<_Impl, 'offset'> | + Pick<_Impl, 'bottomOffset'> | + Pick<_Impl, 'onReposition'> | + Pick<_Impl, 'onScroll'> | + Pick<_Impl, 'onStick'> | + Pick<_Impl, 'onUnstick'> | + Pick<_Impl, 'onTop'> | + Pick<_Impl, 'onBottom'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Sticky Settings @@ -158,10 +179,15 @@ declare namespace SemanticUI { } namespace Sticky { - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'bound'> | + Pick<_Impl, 'fixed'> | + Pick<_Impl, 'supported'> | + Pick<_Impl, 'top'> | + Pick<_Impl, 'bottom'>) & + Partial>; interface _Impl { /** @@ -187,10 +213,15 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'container'> | + Pick<_Impl, 'visible'> | + Pick<_Impl, 'method'> | + Pick<_Impl, 'invalidContext'> | + Pick<_Impl, 'elementSize'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-sticky/semantic-ui-sticky-tests.ts b/types/semantic-ui-sticky/semantic-ui-sticky-tests.ts index 0a3585f08d..fefad8870a 100644 --- a/types/semantic-ui-sticky/semantic-ui-sticky-tests.ts +++ b/types/semantic-ui-sticky/semantic-ui-sticky-tests.ts @@ -1,5 +1,5 @@ function test_sticky_static() { - $.fn.sticky.settings.error.method = 'method'; + $.fn.sticky.settings.error!.method = 'method'; $.fn.sticky.settings.namespace = 'namespace'; $.fn.sticky.settings.name = 'name'; $.fn.sticky.settings.silent = false; @@ -10,11 +10,12 @@ function test_sticky_static() { function test_sticky() { const selector = '.ui.sticky'; - $(selector).sticky('refresh') === $(); - $(selector).sticky('destroy') === $(); - $(selector).sticky('setting', 'debug', undefined) === false; - $(selector).sticky('setting', 'debug') === false; - $(selector).sticky('setting', 'debug', true) === $(); + $(selector).sticky('refresh'); // $ExpectType JQuery + $(selector).sticky('destroy'); // $ExpectType JQuery + $(selector).sticky('setting', 'debug', undefined); // $ExpectType boolean + $(selector).sticky('setting', 'debug'); // $ExpectType boolean + $(selector).sticky('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).sticky('setting', { namespace: 'namespace', name: 'name', @@ -22,7 +23,8 @@ function test_sticky() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).sticky({ pushing: false, jitter: 4, @@ -32,22 +34,22 @@ function test_sticky() { offset: 1, bottomOffset: 200, onReposition() { - this === $(); + this; // $ExpectType JQuery }, onScroll() { - this === $(); + this; // $ExpectType JQuery }, onStick() { - this === $(); + this; // $ExpectType JQuery }, onUnstick() { - this === $(); + this; // $ExpectType JQuery }, onTop() { - this === $(); + this; // $ExpectType JQuery }, onBottom() { - this === $(); + this; // $ExpectType JQuery }, className: { bound: 'bound', @@ -63,12 +65,16 @@ function test_sticky() { invalidContext: 'invalidContext', elementSize: 'elementSize' } - }) === $(); - $(selector).sticky() === $(); + }); + $(selector).sticky(); // $ExpectType JQuery + + $(selector).sticky('foo'); // $ExpectError + $(selector).sticky({ foo: 'bar' }); // $ExpectError } import sticky = require('semantic-ui-sticky'); function test_module() { + sticky; // $ExpectType Sticky $.fn.sticky = sticky; } From c4d80f639a37f186026acd0bcd4f5413478f1d33 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 13:53:17 -0400 Subject: [PATCH 0119/1618] [semantic-ui-tab] Different weak-type workaround. --- types/semantic-ui-tab/global.d.ts | 77 +++++++++--- .../semantic-ui-tab/semantic-ui-tab-tests.ts | 113 ++++++++++-------- 2 files changed, 122 insertions(+), 68 deletions(-) diff --git a/types/semantic-ui-tab/global.d.ts b/types/semantic-ui-tab/global.d.ts index 7bd8aad4fc..5a31dffb18 100644 --- a/types/semantic-ui-tab/global.d.ts +++ b/types/semantic-ui-tab/global.d.ts @@ -40,19 +40,49 @@ declare namespace SemanticUI { */ (behavior: 'cache remove', path: string): JQuery; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): TabSettings[K]; - (behavior: 'setting', name: K, value: TabSettings[K]): JQuery; - (behavior: 'setting', value: TabSettings.Param): JQuery; - (settings?: TabSettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): TabSettings._Impl[K]; + (behavior: 'setting', name: K, value: TabSettings._Impl[K]): JQuery; + (behavior: 'setting', value: TabSettings): JQuery; + (settings?: TabSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/tab.html#/settings} */ - interface TabSettings extends Pick { } + type TabSettings = TabSettings.Param; namespace TabSettings { - type Param = TabSettings | object; + type Param = (Pick<_Impl, 'auto'> | + Pick<_Impl, 'deactivate'> | + Pick<_Impl, 'history'> | + Pick<_Impl, 'ignoreFirstLoad'> | + Pick<_Impl, 'evaluateScripts'> | + Pick<_Impl, 'alwaysRefresh'> | + Pick<_Impl, 'cacheType'> | + Pick<_Impl, 'cache'> | + Pick<_Impl, 'apiSettings'> | + Pick<_Impl, 'historyType'> | + Pick<_Impl, 'path'> | + Pick<_Impl, 'context'> | + Pick<_Impl, 'childrenOnly'> | + Pick<_Impl, 'maxDepth'> | + Pick<_Impl, 'loadOnce'> | + Pick<_Impl, 'onFirstLoad'> | + Pick<_Impl, 'onLoad'> | + Pick<_Impl, 'onRequest'> | + Pick<_Impl, 'onVisible'> | + Pick<_Impl, 'templates'> | + Pick<_Impl, 'selector'> | + Pick<_Impl, 'metadata'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Tab Settings @@ -249,10 +279,11 @@ declare namespace SemanticUI { } namespace Tab { - interface TemplatesSettings extends Pick { } + type TemplatesSettings = TemplatesSettings.Param; namespace TemplatesSettings { - type Param = TemplatesSettings | object; + type Param = (Pick<_Impl, 'determineTitle'>) & + Partial>; interface _Impl { /** @@ -262,10 +293,12 @@ declare namespace SemanticUI { } } - interface SelectorSettings extends Pick { } + type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { - type Param = SelectorSettings | object; + type Param = (Pick<_Impl, 'tabs'> | + Pick<_Impl, 'parent'>) & + Partial>; interface _Impl { /** @@ -279,10 +312,13 @@ declare namespace SemanticUI { } } - interface MetadataSettings extends Pick { } + type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { - type Param = MetadataSettings | object; + type Param = (Pick<_Impl, 'tab'> | + Pick<_Impl, 'loaded'> | + Pick<_Impl, 'promise'>) & + Partial>; interface _Impl { /** @@ -300,10 +336,12 @@ declare namespace SemanticUI { } } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'loading'> | + Pick<_Impl, 'active'>) & + Partial>; interface _Impl { /** @@ -317,10 +355,17 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'api'> | + Pick<_Impl, 'method'> | + Pick<_Impl, 'missingTab'> | + Pick<_Impl, 'noContent'> | + Pick<_Impl, 'path'> | + Pick<_Impl, 'recursion'> | + Pick<_Impl, 'state'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-tab/semantic-ui-tab-tests.ts b/types/semantic-ui-tab/semantic-ui-tab-tests.ts index a3bbc096c4..f2bf6c874a 100644 --- a/types/semantic-ui-tab/semantic-ui-tab-tests.ts +++ b/types/semantic-ui-tab/semantic-ui-tab-tests.ts @@ -1,5 +1,5 @@ function test_tab_static() { - $.fn.tab.settings.error.method = 'method'; + $.fn.tab.settings.error!.method = 'method'; $.fn.tab.settings.namespace = 'namespace'; $.fn.tab.settings.name = 'name'; $.fn.tab.settings.silent = false; @@ -10,17 +10,18 @@ function test_tab_static() { function test_tab() { const selector = '.ui.tab'; - $(selector).tab('change tab', 'path') === $(); - $(selector).tab('set state', 'path') === $(); - $(selector).tab('get path') === 'path'; - $(selector).tab('is tab') === false; - $(selector).tab('cache read', 'path') === false; - $(selector).tab('cache add', 'path', 'html') === $(); - $(selector).tab('cache remove', 'path') === $(); - $(selector).tab('destroy') === $(); - $(selector).tab('setting', 'debug', undefined) === false; - $(selector).tab('setting', 'debug') === false; - $(selector).tab('setting', 'debug', true) === $(); + $(selector).tab('change tab', 'path'); // $ExpectType JQuery + $(selector).tab('set state', 'path'); // $ExpectType JQuery + $(selector).tab('get path'); // $ExpectType string + $(selector).tab('is tab'); // $ExpectType boolean + $(selector).tab('cache read', 'path'); // $ExpectType string | false + $(selector).tab('cache add', 'path', 'html'); // $ExpectType JQuery + $(selector).tab('cache remove', 'path'); // $ExpectType JQuery + $(selector).tab('destroy'); // $ExpectType JQuery + $(selector).tab('setting', 'debug', undefined); // $ExpectType boolean + $(selector).tab('setting', 'debug'); // $ExpectType boolean + $(selector).tab('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).tab('setting', { namespace: 'namespace', name: 'name', @@ -28,7 +29,8 @@ function test_tab() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).tab({ auto: false, deactivate: 'siblings', @@ -56,56 +58,58 @@ function test_tab() { urlData: false, response: false, responseAsync(settings, callback) { - settings === ({} as SemanticUI.ApiSettings); - callback === ((response: any) => { }); + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void }, mockResponse: false, mockResponseAsync(settings, callback) { - settings === ({} as SemanticUI.ApiSettings); - callback === ((response: any) => { }); + settings; // $ExpectType Param + callback; // $ExpectType (response: any) => void }, method: 'post', dataType: 'xml', data: {}, beforeSend(settings) { - settings === ({} as SemanticUI.ApiSettings); + settings; // $ExpectType Param }, beforeXHR(xhrObject) { - xhrObject === ({} as JQueryXHR); + xhrObject; // $ExpectType jqXHR }, onRequest(promise, xhr) { - promise === ({} as JQueryDeferred); - xhr === ({} as JQueryXHR); + promise; // $ExpectType Deferred + xhr; // $ExpectType jqXHR }, onResponse(response) { - response === ({} as any); + response; // $ExpectType any }, successTest(response) { - return response === ({} as any); + response; // $ExpectType any + + return false; }, onSuccess(response, element, xhr) { - response === ({} as any); - element === $(); - xhr === ({} as JQueryXHR); + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onComplete(response, element, xhr) { - response === ({} as any); - element === $(); - xhr === ({} as JQueryXHR); + response; // $ExpectType any + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onFailure(response, element) { - response === ({} as any); - element === $(); + response; // $ExpectType any + element; // $ExpectType JQuery }, onError(errorMessage, element, xhr) { - errorMessage === ''; - element === $(); - xhr === ({} as JQueryXHR); + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, onAbort(errorMessage, element, xhr) { - errorMessage === ''; - element === $(); - xhr === ({} as JQueryXHR); + errorMessage; // $ExpectType string + element; // $ExpectType JQuery + xhr; // $ExpectType jqXHR }, regExp: { required: /{\$*[A-z0-9]+}/g, @@ -146,28 +150,29 @@ function test_tab() { maxDepth: 10, loadOnce: false, onFirstLoad(tabPath, parameterArray, historyEvent) { - this === $(); - tabPath === 'tabPath'; - parameterArray === []; - historyEvent === {}; + this; // $ExpectType JQuery + tabPath; // $ExpectType string + parameterArray; // $ExpectType any[] + historyEvent; // $ExpectType any }, onLoad(tabPath, parameterArray, historyEvent) { - this === $(); - tabPath === 'tabPath'; - parameterArray === []; - historyEvent === {}; + this; // $ExpectType JQuery + tabPath; // $ExpectType string + parameterArray; // $ExpectType any[] + historyEvent; // $ExpectType any }, onRequest(tabPath) { - this === $(); - tabPath === 'tabPath'; + this; // $ExpectType JQuery + tabPath; // $ExpectType string }, onVisible(tabPath) { - this === $(); - tabPath === 'tabPath'; + this; // $ExpectType JQuery + tabPath; // $ExpectType string }, templates: { determineTitle(tabArray) { - tabArray === []; + tabArray; // $ExpectType any[] + return 'title'; } }, @@ -193,12 +198,16 @@ function test_tab() { recursion: 'recursion', state: 'state' } - }) === $(); - $(selector).tab() === $(); + }); + $(selector).tab(); // $ExpectType JQuery + + $(selector).tab('foo'); // $ExpectError + $(selector).tab({ foo: 'bar' }); // $ExpectError } import tab = require('semantic-ui-tab'); function test_module() { + tab; // $ExpectType Tab $.fn.tab = tab; } From 03dcedb1f4d851e0d8daad9b15d84bd4658f79c4 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 14:00:59 -0400 Subject: [PATCH 0120/1618] [semantic-ui-transition] Different weak-type workaround. --- types/semantic-ui-transition/global.d.ts | 51 +++++++++++-- .../semantic-ui-transition-tests.ts | 75 ++++++++++--------- 2 files changed, 84 insertions(+), 42 deletions(-) diff --git a/types/semantic-ui-transition/global.d.ts b/types/semantic-ui-transition/global.d.ts index 2ec4cf4ba4..48b530ad11 100644 --- a/types/semantic-ui-transition/global.d.ts +++ b/types/semantic-ui-transition/global.d.ts @@ -95,19 +95,41 @@ declare namespace SemanticUI { */ (behavior: 'is supported'): boolean; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): TransitionSettings[K]; - (behavior: 'setting', name: K, value: TransitionSettings[K]): JQuery; - (behavior: 'setting', value: TransitionSettings | object): JQuery; + (behavior: 'setting', name: K, value?: undefined): TransitionSettings._Impl[K]; + (behavior: 'setting', name: K, value: TransitionSettings._Impl[K]): JQuery; + (behavior: 'setting', value: TransitionSettings): JQuery; (transition: string): JQuery; - (settings?: TransitionSettings | object): JQuery; + (settings?: TransitionSettings): JQuery; } /** * @see {@link http://semantic-ui.com/modules/transition.html#/settings} */ - interface TransitionSettings extends Pick { } + type TransitionSettings = TransitionSettings.Param; namespace TransitionSettings { + type Param = (Pick<_Impl, 'animation'> | + Pick<_Impl, 'interval'> | + Pick<_Impl, 'reverse'> | + Pick<_Impl, 'displayType'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'useFailSafe'> | + Pick<_Impl, 'allowRepeats'> | + Pick<_Impl, 'queue'> | + Pick<_Impl, 'onShow'> | + Pick<_Impl, 'onHide'> | + Pick<_Impl, 'onStart'> | + Pick<_Impl, 'onComplete'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; + interface _Impl { // region Transition Settings @@ -233,9 +255,20 @@ declare namespace SemanticUI { } namespace Transition { - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { + type Param = (Pick<_Impl, 'animating'> | + Pick<_Impl, 'disabled'> | + Pick<_Impl, 'hidden'> | + Pick<_Impl, 'inward'> | + Pick<_Impl, 'loading'> | + Pick<_Impl, 'looping'> | + Pick<_Impl, 'outward'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'visible'>) & + Partial>; + interface _Impl { /** * @default 'animating' @@ -276,9 +309,13 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { + type Param = (Pick<_Impl, 'noAnimation'> | + Pick<_Impl, 'method'>) & + Partial>; + interface _Impl { /** * @default 'There is no CSS animation matching the one you specified.' diff --git a/types/semantic-ui-transition/semantic-ui-transition-tests.ts b/types/semantic-ui-transition/semantic-ui-transition-tests.ts index a9b3208e8a..a010ba1437 100644 --- a/types/semantic-ui-transition/semantic-ui-transition-tests.ts +++ b/types/semantic-ui-transition/semantic-ui-transition-tests.ts @@ -1,5 +1,5 @@ function test_static() { - $.fn.transition.settings.error.method = 'method'; + $.fn.transition.settings.error!.method = 'method'; $.fn.transition.settings.namespace = 'namespace'; $.fn.transition.settings.name = 'name'; $.fn.transition.settings.silent = false; @@ -10,32 +10,33 @@ function test_static() { function test_transition() { const selector = '.ui.transition'; - $(selector).transition('stop') === $(); - $(selector).transition('stop all') === $(); - $(selector).transition('clear queue') === $(); - $(selector).transition('show') === $(); - $(selector).transition('hide') === $(); - $(selector).transition('toggle') === $(); - $(selector).transition('force repaint') === $(); - $(selector).transition('repaint') === $(); - $(selector).transition('reset') === $(); - $(selector).transition('looping') === $(); - $(selector).transition('remove looping') === $(); - $(selector).transition('disable') === $(); - $(selector).transition('enable') === $(); - $(selector).transition('set duration', 10) === $(); - $(selector).transition('save conditions') === $(); - $(selector).transition('restore conditions') === $(); - $(selector).transition('get animation name') === 'animation name'; - $(selector).transition('get animation event') === 'animation event'; - $(selector).transition('is visible') === false; - $(selector).transition('is animating') === false; - $(selector).transition('is looping') === false; - $(selector).transition('is supported') === false; - $(selector).transition('destroy') === $(); - $(selector).transition('setting', 'debug', undefined) === false; - $(selector).transition('setting', 'debug') === false; - $(selector).transition('setting', 'debug', true) === $(); + $(selector).transition('stop'); // $ExpectType JQuery + $(selector).transition('stop all'); // $ExpectType JQuery + $(selector).transition('clear queue'); // $ExpectType JQuery + $(selector).transition('show'); // $ExpectType JQuery + $(selector).transition('hide'); // $ExpectType JQuery + $(selector).transition('toggle'); // $ExpectType JQuery + $(selector).transition('force repaint'); // $ExpectType JQuery + $(selector).transition('repaint'); // $ExpectType JQuery + $(selector).transition('reset'); // $ExpectType JQuery + $(selector).transition('looping'); // $ExpectType JQuery + $(selector).transition('remove looping'); // $ExpectType JQuery + $(selector).transition('disable'); // $ExpectType JQuery + $(selector).transition('enable'); // $ExpectType JQuery + $(selector).transition('set duration', 10); // $ExpectType JQuery + $(selector).transition('save conditions'); // $ExpectType JQuery + $(selector).transition('restore conditions'); // $ExpectType JQuery + $(selector).transition('get animation name'); // $ExpectType string + $(selector).transition('get animation event'); // $ExpectType string + $(selector).transition('is visible'); // $ExpectType boolean + $(selector).transition('is animating'); // $ExpectType boolean + $(selector).transition('is looping'); // $ExpectType boolean + $(selector).transition('is supported'); // $ExpectType boolean + $(selector).transition('destroy'); // $ExpectType JQuery + $(selector).transition('setting', 'debug', undefined); // $ExpectType boolean + $(selector).transition('setting', 'debug'); // $ExpectType boolean + $(selector).transition('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).transition('setting', { namespace: 'namespace', name: 'name', @@ -43,8 +44,9 @@ function test_transition() { debug: true, performance: true, verbose: true - }) === $(); - $(selector).transition('fade') === $(); + }); + $(selector).transition('fade'); // $ExpectType JQuery + // $ExpectType JQuery $(selector).transition({ animation: 'fade', interval: 200, @@ -55,16 +57,16 @@ function test_transition() { allowRepeats: true, queue: false, onShow() { - this === $(); + this; // $ExpectType JQuery }, onHide() { - this === $(); + this; // $ExpectType JQuery }, onStart() { - this === $(); + this; // $ExpectType JQuery }, onComplete() { - this === $(); + this; // $ExpectType JQuery }, className: { animating: 'animating', @@ -81,12 +83,15 @@ function test_transition() { noAnimation: 'noAnimation', method: 'method' } - }) === $(); - $(selector).transition() === $(); + }); + $(selector).transition(); // $ExpectType JQuery + + $(selector).transition({ foo: 'bar' }); // $ExpectError } import transition = require('semantic-ui-transition'); function test_module() { + transition; // $ExpectType Transition $.fn.transition = transition; } From a718e41a609ca3a043dc62040cada98870b1e0a2 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Fri, 30 Jun 2017 14:05:05 -0400 Subject: [PATCH 0121/1618] [semantic-ui-visibility] Different weak-type workaround. --- types/semantic-ui-visibility/global.d.ts | 63 ++++++++-- .../semantic-ui-visibility-tests.ts | 119 ++++++------------ 2 files changed, 94 insertions(+), 88 deletions(-) diff --git a/types/semantic-ui-visibility/global.d.ts b/types/semantic-ui-visibility/global.d.ts index fa735676c5..1f582bf257 100644 --- a/types/semantic-ui-visibility/global.d.ts +++ b/types/semantic-ui-visibility/global.d.ts @@ -39,19 +39,60 @@ declare namespace SemanticUI { */ (behavior: 'get screen size'): Visibility.ScreenSize; (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): VisibilitySettings[K]; - (behavior: 'setting', name: K, value: VisibilitySettings[K]): JQuery; - (behavior: 'setting', value: VisibilitySettings.Param): JQuery; - (settings?: VisibilitySettings.Param): JQuery; + (behavior: 'setting', name: K, value?: undefined): VisibilitySettings._Impl[K]; + (behavior: 'setting', name: K, value: VisibilitySettings._Impl[K]): JQuery; + (behavior: 'setting', value: VisibilitySettings): JQuery; + (settings?: VisibilitySettings): JQuery; } /** * @see {@link http://semantic-ui.com/behaviors/visibility.html#/settings} */ - interface VisibilitySettings extends Pick { } + type VisibilitySettings = VisibilitySettings.Param; namespace VisibilitySettings { - type Param = VisibilitySettings | object; + type Param = (Pick<_Impl, 'once'> | + Pick<_Impl, 'continuous'> | + Pick<_Impl, 'type'> | + Pick<_Impl, 'initialCheck'> | + Pick<_Impl, 'context'> | + Pick<_Impl, 'refreshOnLoad'> | + Pick<_Impl, 'refreshOnResize'> | + Pick<_Impl, 'checkOnRefresh'> | + Pick<_Impl, 'zIndex'> | + Pick<_Impl, 'offset'> | + Pick<_Impl, 'includeMargin'> | + Pick<_Impl, 'throttle'> | + Pick<_Impl, 'observeChanges'> | + Pick<_Impl, 'transition'> | + Pick<_Impl, 'duration'> | + Pick<_Impl, 'onTopVisible'> | + Pick<_Impl, 'onTopPassed'> | + Pick<_Impl, 'onBottomVisible'> | + Pick<_Impl, 'onPassing'> | + Pick<_Impl, 'onBottomPassed'> | + Pick<_Impl, 'onTopVisibleReverse'> | + Pick<_Impl, 'onTopPassedReverse'> | + Pick<_Impl, 'onBottomVisibleReverse'> | + Pick<_Impl, 'onPassingReverse'> | + Pick<_Impl, 'onBottomPassedReverse'> | + Pick<_Impl, 'onOnScreen'> | + Pick<_Impl, 'onOffScreen'> | + Pick<_Impl, 'onLoad'> | + Pick<_Impl, 'onAllLoaded'> | + Pick<_Impl, 'onFixed'> | + Pick<_Impl, 'onUnfixed'> | + Pick<_Impl, 'onUpdate'> | + Pick<_Impl, 'onRefresh'> | + Pick<_Impl, 'className'> | + Pick<_Impl, 'error'> | + Pick<_Impl, 'namespace'> | + Pick<_Impl, 'name'> | + Pick<_Impl, 'silent'> | + Pick<_Impl, 'debug'> | + Pick<_Impl, 'performance'> | + Pick<_Impl, 'verbose'>) & + Partial>; interface _Impl { // region Functionality @@ -337,10 +378,11 @@ declare namespace SemanticUI { height: number; } - interface ClassNameSettings extends Pick { } + type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { - type Param = ClassNameSettings | object; + type Param = (Pick<_Impl, 'fixed'>) & + Partial>; interface _Impl { /** @@ -350,10 +392,11 @@ declare namespace SemanticUI { } } - interface ErrorSettings extends Pick { } + type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { - type Param = ErrorSettings | object; + type Param = (Pick<_Impl, 'method'>) & + Partial>; interface _Impl { /** diff --git a/types/semantic-ui-visibility/semantic-ui-visibility-tests.ts b/types/semantic-ui-visibility/semantic-ui-visibility-tests.ts index 960eeb5215..44d8bb0361 100644 --- a/types/semantic-ui-visibility/semantic-ui-visibility-tests.ts +++ b/types/semantic-ui-visibility/semantic-ui-visibility-tests.ts @@ -1,5 +1,5 @@ function test_visibility_static() { - $.fn.visibility.settings.error.method = 'method'; + $.fn.visibility.settings.error!.method = 'method'; $.fn.visibility.settings.namespace = 'namespace'; $.fn.visibility.settings.name = 'name'; $.fn.visibility.settings.silent = false; @@ -10,42 +10,19 @@ function test_visibility_static() { function test_visibility() { const selector = '.ui.visibility'; - $(selector).visibility('disable callbacks') === $(); - $(selector).visibility('enable callbacks') === $(); - $(selector).visibility('is on screen') === false; - $(selector).visibility('is off screen') === true; - $(selector).visibility('get pixels passed') === 20; - $(selector).visibility('get element calculations') === { - fits: false, - offset: { - top: 955.96875, - left: 292 - }, - width: 466, - height: 1665.890625, - top: 955.96875, - bottom: 2621.859375, - topPassed: true, - bottomPassed: false, - topVisible: true, - bottomVisible: false, - pixelsPassed: 742.03125, - percentagePassed: 0.44542615155182, - onScreen: true, - passing: true, - offScreen: false - }; - $(selector).visibility('get screen calculations') === { - bottom: 2658, - top: 1698 - }; - $(selector).visibility('get screen size') === { - height: 960 - }; - $(selector).visibility('destroy') === $(); - $(selector).visibility('setting', 'debug', undefined) === false; - $(selector).visibility('setting', 'debug') === false; - $(selector).visibility('setting', 'debug', true) === $(); + $(selector).visibility('disable callbacks'); // $ExpectType JQuery + $(selector).visibility('enable callbacks'); // $ExpectType JQuery + $(selector).visibility('is on screen'); // $ExpectType boolean + $(selector).visibility('is off screen'); // $ExpectType boolean + $(selector).visibility('get pixels passed'); // $ExpectType number + $(selector).visibility('get element calculations'); // $ExpectType ElementCalculations + $(selector).visibility('get screen calculations'); // $ExpectType ScreenCalculations + $(selector).visibility('get screen size'); // $ExpectType ScreenSize + $(selector).visibility('destroy'); // $ExpectType JQuery + $(selector).visibility('setting', 'debug', undefined); // $ExpectType boolean + $(selector).visibility('setting', 'debug'); // $ExpectType boolean + $(selector).visibility('setting', 'debug', true); // $ExpectType JQuery + // $ExpectType JQuery $(selector).visibility('setting', { namespace: 'namespace', name: 'name', @@ -53,7 +30,8 @@ function test_visibility() { debug: true, performance: true, verbose: true - }) === $(); + }); + // $ExpectType JQuery $(selector).visibility({ once: false, continuous: true, @@ -71,78 +49,59 @@ function test_visibility() { transition: 'fade', duration: 5, onTopVisible() { - this === $(); + this; // $ExpectType JQuery }, onTopPassed() { - this === $(); + this; // $ExpectType JQuery }, onBottomVisible() { - this === $(); + this; // $ExpectType JQuery }, onPassing() { - this === $(); + this; // $ExpectType JQuery }, onBottomPassed() { - this === $(); + this; // $ExpectType JQuery }, onTopVisibleReverse() { - this === $(); + this; // $ExpectType JQuery }, onTopPassedReverse() { - this === $(); + this; // $ExpectType JQuery }, onBottomVisibleReverse() { - this === $(); + this; // $ExpectType JQuery }, onPassingReverse() { - this === $(); + this; // $ExpectType JQuery }, onBottomPassedReverse() { - this === $(); + this; // $ExpectType JQuery }, onOnScreen() { - this === $(); + this; // $ExpectType JQuery }, onOffScreen() { - this === $(); + this; // $ExpectType JQuery }, onLoad() { - this === $(); + this; // $ExpectType JQuery }, onAllLoaded() { - this === $(); + this; // $ExpectType JQuery }, onFixed() { - this === $(); + this; // $ExpectType JQuery }, onUnfixed() { - this === $(); + this; // $ExpectType JQuery }, onUpdate(calculations) { - this === $(); - calculations === { - fits: false, - offset: { - top: 955.96875, - left: 292 - }, - width: 466, - height: 1665.890625, - top: 955.96875, - bottom: 2621.859375, - topPassed: true, - bottomPassed: false, - topVisible: true, - bottomVisible: false, - pixelsPassed: 742.03125, - percentagePassed: 0.44542615155182, - onScreen: true, - passing: true, - offScreen: false - }; + this; // $ExpectType JQuery + calculations; // $ExpectType ElementCalculations }, onRefresh() { - this === $(); + this; // $ExpectType JQuery }, className: { fixed: 'fixed', @@ -150,12 +109,16 @@ function test_visibility() { error: { method: 'method' } - }) === $(); - $(selector).visibility() === $(); + }); + $(selector).visibility(); // $ExpectType JQuery + + $(selector).visibility('foo'); // $ExpectError + $(selector).visibility({ foo: 'bar' }); // $ExpectError } import visibility = require('semantic-ui-visibility'); function test_module() { + visibility; // $ExpectType Visibility $.fn.visibility = visibility; } From cd3d9fe4f774a8ddd392e49132a17641e9926fc0 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Fri, 30 Jun 2017 22:49:49 +0100 Subject: [PATCH 0122/1618] put files in right place and add tslint.json --- {nano => types/nano}/index.d.ts | 58 +++++++++++++++--------------- {nano => types/nano}/nano-tests.ts | 0 {nano => types/nano}/tsconfig.json | 6 ++-- types/nano/tslint.json | 1 + 4 files changed, 33 insertions(+), 32 deletions(-) rename {nano => types/nano}/index.d.ts (70%) rename {nano => types/nano}/nano-tests.ts (100%) rename {nano => types/nano}/tsconfig.json (85%) create mode 100644 types/nano/tslint.json diff --git a/nano/index.d.ts b/types/nano/index.d.ts similarity index 70% rename from nano/index.d.ts rename to types/nano/index.d.ts index deb453bb98..4b7cc6f367 100644 --- a/nano/index.d.ts +++ b/types/nano/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/apache/couchdb-nano // Definitions by: Tim Jacobi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.0 declare module "nano" { import { EventEmitter } from "events"; @@ -34,7 +34,7 @@ declare module "nano" { auth(username: string, userpass: string, callback?: Callback): Request session(callback?: Callback): Request updates(params?: UpdatesParams, callback?: Callback): Request - followUpdates(params?: object, callback?: Callback): EventEmitter + followUpdates(params?: any, callback?: Callback): EventEmitter uuids(num: number, callback: Callback): Request } @@ -45,52 +45,52 @@ declare module "nano" { list(callback?: Callback): Request use(db: string): DocumentScope compact(name: string, designname?: string, callback?: Callback): Request - replicate(source: string | DocumentScope, target: string | DocumentScope, options?: object, callback?: Callback): Request - changes(name: string, params?: object, callback?: Callback): Request + replicate(source: string | DocumentScope, target: string | DocumentScope, options?: any, callback?: Callback): Request + changes(name: string, params?: any, callback?: Callback): Request follow(source: string, params?: DatabaseScopeFollowUpdatesParams, callback?: Callback): void - followUpdates(params?: object, callback?: Callback): EventEmitter + followUpdates(params?: any, callback?: Callback): EventEmitter updates(params?: UpdatesParams, callback?: Callback): Request } interface DocumentScope { readonly config: ServerConfig info(callback?: Callback): Request - replicate(target: string | DocumentScope, options?: object, callback?: Callback): Request + replicate(target: string | DocumentScope, options?: any, callback?: Callback): Request compact(callback?: Callback): Request - changes(params?: object, callback?: Callback): Request + changes(params?: any, callback?: Callback): Request follow(params?: DocumentScopeFollowUpdatesParams, callback?: Callback): void auth(username: string, userpass: string, callback?: Callback): Request session(callback?: Callback): Request - insert(document: object, params?: string | object, callback?: Callback): Request - get(docname: string, params?: object, callback?: Callback): Request + insert(document: any, params?: any, callback?: Callback): Request + get(docname: string, params?: any, callback?: Callback): Request head(docname: string, callback: Callback): Request - copy(src_document: string, dst_document: string, options: object, callback?: Callback): Request + copy(src_document: string, dst_document: string, options: any, callback?: Callback): Request destroy(docname: string, rev: string, callback?: Callback): Request - bulk(docs: BulkModifyDocsWrapper, params?: object, callback?: Callback): Request - list(params?: object, callback?: Callback): Request - fetch(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request - fetchRevs(docnames: BulkFetchDocsWrapper, params?: object, callback?: Callback): Request + bulk(docs: BulkModifyDocsWrapper, params?: any, callback?: Callback): Request + list(params?: any, callback?: Callback): Request + fetch(docnames: BulkFetchDocsWrapper, params?: any, callback?: Callback): Request + fetchRevs(docnames: BulkFetchDocsWrapper, params?: any, callback?: Callback): Request multipart: Multipart attachment: Attachment - show(designname: string, showname: string, doc_id: string, params?: object, callback?: Callback): Request - atomic(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request - updateWithHandler(designname: string, updatename: string, docname: string, body?: object, callback?: Callback): Request - search(designname: string, searchname: string, params?: object, callback?: Callback): Request - spatial(ddoc: string, viewname: string, params?: object, callback?: Callback): Request - view(designname: string, viewname: string, params?: object, callback?: Callback): Request - viewWithList(designname: string, viewname: string, listname: string, params?: object, callback?: Callback): Request + show(designname: string, showname: string, doc_id: string, params?: any, callback?: Callback): Request + atomic(designname: string, updatename: string, docname: string, body?: any, callback?: Callback): Request + updateWithHandler(designname: string, updatename: string, docname: string, body?: any, callback?: Callback): Request + search(designname: string, searchname: string, params?: any, callback?: Callback): Request + spatial(ddoc: string, viewname: string, params?: any, callback?: Callback): Request + view(designname: string, viewname: string, params?: any, callback?: Callback): Request + viewWithList(designname: string, viewname: string, listname: string, params?: any, callback?: Callback): Request server: ServerScope } interface Multipart { - insert(doc: object, attachments: object[], params: string | object, callback?: Callback): Request - get(docname: string, params?: string | object, callback?: Callback): Request + insert(doc: any, attachments: any[], params: string | any, callback?: Callback): Request + get(docname: string, params?: string | any, callback?: Callback): Request } interface Attachment { - insert(docname: string, attname: string, att: any, contenttype: string, params?: object, callback?: Callback): Request - get(docname: string, attname: string, params?: object, callback?: Callback): Request - destroy(docname: string, attname: string, params?: object, callback?: Callback): Request + insert(docname: string, attname: string, att: any, contenttype: string, params?: any, callback?: Callback): Request + get(docname: string, attname: string, params?: any, callback?: Callback): Request + destroy(docname: string, attname: string, params?: any, callback?: Callback): Request } interface ServerConfig { @@ -128,8 +128,8 @@ declare module "nano" { heartbeat?: number feed?: "continuous" filter?: string | FollowUpdatesParamsFilterFunction - query_params?: object - headers?: object + query_params?: any + headers?: any inactivity_ms?: number max_retry_seconds?: number initial_retry_delay?: number @@ -145,7 +145,7 @@ declare module "nano" { } interface BulkModifyDocsWrapper { - docs: object[] + docs: any[] } interface BulkFetchDocsWrapper { diff --git a/nano/nano-tests.ts b/types/nano/nano-tests.ts similarity index 100% rename from nano/nano-tests.ts rename to types/nano/nano-tests.ts diff --git a/nano/tsconfig.json b/types/nano/tsconfig.json similarity index 85% rename from nano/tsconfig.json rename to types/nano/tsconfig.json index 7ae532da90..6290b1a17e 100644 --- a/nano/tsconfig.json +++ b/types/nano/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "couchdb-nano-tests.ts" + "nano-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/nano/tslint.json b/types/nano/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/nano/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c1aeed1c41a81ae9cd5cc219cd391267456e8db8 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Fri, 30 Jun 2017 23:32:28 +0100 Subject: [PATCH 0123/1618] fix lint errors --- types/nano/index.d.ts | 361 ++++++++++++++++++++++++--------------- types/nano/nano-tests.ts | 81 +++++---- 2 files changed, 266 insertions(+), 176 deletions(-) diff --git a/types/nano/index.d.ts b/types/nano/index.d.ts index 4b7cc6f367..ab80e563d4 100644 --- a/types/nano/index.d.ts +++ b/types/nano/index.d.ts @@ -1,157 +1,248 @@ -// Type definitions for nano 6.2.0 +// Type definitions for nano 6.2 // Project: https://github.com/apache/couchdb-nano // Definitions by: Tim Jacobi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.0 -declare module "nano" { - import { EventEmitter } from "events"; - import { Request, CoreOptions } from "request"; +import { EventEmitter } from "events"; +import { Request, CoreOptions } from "request"; - function nano(config: nano.Configuration | string): nano.ServerScope | nano.DocumentScope; +declare function nano( + config: nano.Configuration | string +): nano.ServerScope | nano.DocumentScope; - namespace nano { - interface Configuration { - url: string - requestDefaults?: CoreOptions - log?(id: string, args: any): void - parseUrl?: boolean - request?: Function - } +declare namespace nano { + interface Configuration { + url: string; + requestDefaults?: CoreOptions; + log?(id: string, args: any): void; + parseUrl?: boolean; + request?(params: any): void; + } - interface Callback { - (error: any, result: any, headers?: any): void - } + type Callback = (error: any, result: any, headers?: any) => void; - interface ServerScope { - readonly config: ServerConfig - db: DatabaseScope - use(db: string): DocumentScope - scope(db: string): DocumentScope - request: RequestFunction - relax: RequestFunction - dinosaur: RequestFunction - auth(username: string, userpass: string, callback?: Callback): Request - session(callback?: Callback): Request - updates(params?: UpdatesParams, callback?: Callback): Request - followUpdates(params?: any, callback?: Callback): EventEmitter - uuids(num: number, callback: Callback): Request - } + interface ServerScope { + readonly config: ServerConfig; + db: DatabaseScope; + use(db: string): DocumentScope; + scope(db: string): DocumentScope; + request: RequestFunction; + relax: RequestFunction; + dinosaur: RequestFunction; + auth(username: string, userpass: string, callback?: Callback): Request; + session(callback?: Callback): Request; + updates(params?: UpdatesParams, callback?: Callback): Request; + followUpdates(params?: any, callback?: Callback): EventEmitter; + uuids(num: number, callback: Callback): Request; + } - interface DatabaseScope { - create(name: string, callback?: Callback): Request - get(name: string, callback?: Callback): Request - destroy(name: string, callback?: Callback): Request - list(callback?: Callback): Request - use(db: string): DocumentScope - compact(name: string, designname?: string, callback?: Callback): Request - replicate(source: string | DocumentScope, target: string | DocumentScope, options?: any, callback?: Callback): Request - changes(name: string, params?: any, callback?: Callback): Request - follow(source: string, params?: DatabaseScopeFollowUpdatesParams, callback?: Callback): void - followUpdates(params?: any, callback?: Callback): EventEmitter - updates(params?: UpdatesParams, callback?: Callback): Request - } + interface DatabaseScope { + create(name: string, callback?: Callback): Request; + get(name: string, callback?: Callback): Request; + destroy(name: string, callback?: Callback): Request; + list(callback?: Callback): Request; + use(db: string): DocumentScope; + compact(name: string, designname?: string, callback?: Callback): Request; + replicate( + source: string | DocumentScope, + target: string | DocumentScope, + options?: any, + callback?: Callback + ): Request; + changes(name: string, params?: any, callback?: Callback): Request; + follow( + source: string, + params?: DatabaseScopeFollowUpdatesParams, + callback?: Callback + ): EventEmitter; + followUpdates(params?: any, callback?: Callback): EventEmitter; + updates(params?: UpdatesParams, callback?: Callback): Request; + } - interface DocumentScope { - readonly config: ServerConfig - info(callback?: Callback): Request - replicate(target: string | DocumentScope, options?: any, callback?: Callback): Request - compact(callback?: Callback): Request - changes(params?: any, callback?: Callback): Request - follow(params?: DocumentScopeFollowUpdatesParams, callback?: Callback): void - auth(username: string, userpass: string, callback?: Callback): Request - session(callback?: Callback): Request - insert(document: any, params?: any, callback?: Callback): Request - get(docname: string, params?: any, callback?: Callback): Request - head(docname: string, callback: Callback): Request - copy(src_document: string, dst_document: string, options: any, callback?: Callback): Request - destroy(docname: string, rev: string, callback?: Callback): Request - bulk(docs: BulkModifyDocsWrapper, params?: any, callback?: Callback): Request - list(params?: any, callback?: Callback): Request - fetch(docnames: BulkFetchDocsWrapper, params?: any, callback?: Callback): Request - fetchRevs(docnames: BulkFetchDocsWrapper, params?: any, callback?: Callback): Request - multipart: Multipart - attachment: Attachment - show(designname: string, showname: string, doc_id: string, params?: any, callback?: Callback): Request - atomic(designname: string, updatename: string, docname: string, body?: any, callback?: Callback): Request - updateWithHandler(designname: string, updatename: string, docname: string, body?: any, callback?: Callback): Request - search(designname: string, searchname: string, params?: any, callback?: Callback): Request - spatial(ddoc: string, viewname: string, params?: any, callback?: Callback): Request - view(designname: string, viewname: string, params?: any, callback?: Callback): Request - viewWithList(designname: string, viewname: string, listname: string, params?: any, callback?: Callback): Request - server: ServerScope - } + interface DocumentScope { + readonly config: ServerConfig; + info(callback?: Callback): Request; + replicate( + target: string | DocumentScope, + options?: any, + callback?: Callback + ): Request; + compact(callback?: Callback): Request; + changes(params?: any, callback?: Callback): Request; + follow( + params?: DocumentScopeFollowUpdatesParams, + callback?: Callback + ): EventEmitter; + auth(username: string, userpass: string, callback?: Callback): Request; + session(callback?: Callback): Request; + insert(document: any, params?: any, callback?: Callback): Request; + get(docname: string, params?: any, callback?: Callback): Request; + head(docname: string, callback: Callback): Request; + copy( + src_document: string, + dst_document: string, + options: any, + callback?: Callback + ): Request; + destroy(docname: string, rev: string, callback?: Callback): Request; + bulk( + docs: BulkModifyDocsWrapper, + params?: any, + callback?: Callback + ): Request; + list(params?: any, callback?: Callback): Request; + fetch( + docnames: BulkFetchDocsWrapper, + params?: any, + callback?: Callback + ): Request; + fetchRevs( + docnames: BulkFetchDocsWrapper, + params?: any, + callback?: Callback + ): Request; + multipart: Multipart; + attachment: Attachment; + show( + designname: string, + showname: string, + doc_id: string, + params?: any, + callback?: Callback + ): Request; + atomic( + designname: string, + updatename: string, + docname: string, + body?: any, + callback?: Callback + ): Request; + updateWithHandler( + designname: string, + updatename: string, + docname: string, + body?: any, + callback?: Callback + ): Request; + search( + designname: string, + searchname: string, + params?: any, + callback?: Callback + ): Request; + spatial( + ddoc: string, + viewname: string, + params?: any, + callback?: Callback + ): Request; + view( + designname: string, + viewname: string, + params?: any, + callback?: Callback + ): Request; + viewWithList( + designname: string, + viewname: string, + listname: string, + params?: any, + callback?: Callback + ): Request; + server: ServerScope; + } - interface Multipart { - insert(doc: any, attachments: any[], params: string | any, callback?: Callback): Request - get(docname: string, params?: string | any, callback?: Callback): Request - } + interface Multipart { + insert( + doc: any, + attachments: any[], + params: string | any, + callback?: Callback + ): Request; + get(docname: string, params?: string | any, callback?: Callback): Request; + } - interface Attachment { - insert(docname: string, attname: string, att: any, contenttype: string, params?: any, callback?: Callback): Request - get(docname: string, attname: string, params?: any, callback?: Callback): Request - destroy(docname: string, attname: string, params?: any, callback?: Callback): Request - } + interface Attachment { + insert( + docname: string, + attname: string, + att: any, + contenttype: string, + params?: any, + callback?: Callback + ): Request; + get( + docname: string, + attname: string, + params?: any, + callback?: Callback + ): Request; + destroy( + docname: string, + attname: string, + params?: any, + callback?: Callback + ): Request; + } - interface ServerConfig { - url: string - db: string - } + interface ServerConfig { + url: string; + db: string; + } - interface RequestFunction { - (options?: RequestOptions | string, callback?: Callback): void - } + type RequestFunction = ( + options?: RequestOptions | string, + callback?: Callback + ) => void; - interface RequestOptions { - db?: string - method?: string - path?: string - doc?: string - att?: string - qs?: any - content_type?: string - headers?: any - body?: any - encoding?: string - multipart?: any[] - } + interface RequestOptions { + db?: string; + method?: string; + path?: string; + doc?: string; + att?: string; + qs?: any; + content_type?: string; + headers?: any; + body?: any; + encoding?: string; + multipart?: any[]; + } - interface UpdatesParams { - feed: "longpoll" | "continuous" | "eventsource" - timeout: number - heartbeat: boolean - } + interface UpdatesParams { + feed: "longpoll" | "continuous" | "eventsource"; + timeout: number; + heartbeat: boolean; + } - interface DocumentScopeFollowUpdatesParams { - inlucde_docs?: boolean - since?: string - heartbeat?: number - feed?: "continuous" - filter?: string | FollowUpdatesParamsFilterFunction - query_params?: any - headers?: any - inactivity_ms?: number - max_retry_seconds?: number - initial_retry_delay?: number - response_grace_time?: number - } + interface DocumentScopeFollowUpdatesParams { + inlucde_docs?: boolean; + since?: string; + heartbeat?: number; + feed?: "continuous"; + filter?: string | FollowUpdatesParamsFilterFunction; + query_params?: any; + headers?: any; + inactivity_ms?: number; + max_retry_seconds?: number; + initial_retry_delay?: number; + response_grace_time?: number; + } - interface DatabaseScopeFollowUpdatesParams extends DocumentScopeFollowUpdatesParams { - db: string - } + interface DatabaseScopeFollowUpdatesParams + extends DocumentScopeFollowUpdatesParams { + db: string; + } - interface FollowUpdatesParamsFilterFunction { - (doc: any, req: any): boolean - } + type FollowUpdatesParamsFilterFunction = (doc: any, req: any) => boolean; - interface BulkModifyDocsWrapper { - docs: any[] - } + interface BulkModifyDocsWrapper { + docs: any[]; + } - interface BulkFetchDocsWrapper { - keys: string[] - } - } - - export = nano + interface BulkFetchDocsWrapper { + keys: string[]; + } } + +export = nano; diff --git a/types/nano/nano-tests.ts b/types/nano/nano-tests.ts index 79b2fded4c..1e57052329 100644 --- a/types/nano/nano-tests.ts +++ b/types/nano/nano-tests.ts @@ -7,7 +7,7 @@ import * as path from "path"; */ const config: nano.Configuration = { url: "http://localhost:5984/foo", - requestDefaults: { "proxy": "http://someproxy" } + requestDefaults: { proxy: "http://someproxy" } }; const cfgInstance = nano(config); @@ -15,73 +15,72 @@ const cfgInstance = nano(config); /* * Server Scope */ -const instance: nano.ServerScope = nano("http://localhost:5984/emails"); +const instance: nano.ServerScope = nano("http://localhost:5984/emails"); -instance.dinosaur("", function (err, response) { }); +instance.dinosaur("", (err, response) => {}); const url = instance.config.url; -instance.relax({ method: "POST", path: "_users", body: { _id: "org.couchdb.user:", type: "user", name: "ss", roles: ["admin"], password: "rf" } }, function (err: any) { }); -instance.session(function (error, session) { }); -instance.request({ db: "shared_headers", doc: "new", headers: { "If-None-Match": JSON.stringify({}) } }, function (error, helloWorld, rh) { }); -instance.relax({ db: "document_list", doc: "_all_docs", method: "GET", qs: { limit: 1 } }, function (error, docs) { }); -instance.auth("", "", function (err: any, _: any, headers: any) { }); -instance.uuids(3, function (error, data) { }); +instance.relax({ method: "POST", path: "_users", body: { _id: "org.couchdb.user:", type: "user", name: "ss", roles: ["admin"], password: "rf" } }, (err: any) => {}); +instance.session((error, session) => {}); +instance.request({ db: "shared_headers", doc: "new", headers: { "If-None-Match": JSON.stringify({}) } }, (error, helloWorld, rh) => {}); +instance.relax({ db: "document_list", doc: "_all_docs", method: "GET", qs: { limit: 1 } }, (error, docs) => {}); +instance.auth("", "", (err: any, _: any, headers: any) => {}); +instance.uuids(3, (error, data) => {}); /* * Database Scope */ const db: nano.DatabaseScope = instance.db; -db.create("az09_$()+-/", function (err) { }); -db.get("database_get", function (error, response) { }); -db.destroy("_users", function () { }); -db.list(function (error, list) { }); -db.replicate(instance.use("a"), instance.use("b"), function (error: any) { }); -db.replicate("a", "b", function (error: any) { }); - +db.create("az09_$()+-/", (err) => {}); +db.get("database_get", (err, response) => {}); +db.destroy("_users", () => {}); +db.list((error, list) => {}); +db.replicate(instance.use("a"), instance.use("b"), (error: any) => {}); +db.replicate("a", "b", (error: any) => {}); /* * Document Scope */ const mydb: nano.DocumentScope = instance.use("mydb"); -mydb.insert({ "foo": "baz" }, null, function (error, response) { }); -mydb.insert({ "foo": "baz" }, "foobar", function (error, foo) { }); -mydb.get("foobaz", { "revs_info": true }, function (error, foobaz) { }); -mydb.head("foobaz", function (error, body, headers) { }); -mydb.copy("foo_src", "foo_dest", { overwrite: true }, function (error, response, headers) { }); -mydb.destroy(undefined, undefined, function (error, response) { }); -mydb.bulk({ "docs": [{ "key": "baz", "name": "bazzel" }, { "key": "bar", "name": "barry" }] }, function (error: any, response: any) { }); -mydb.list(function (error: any, docs: any) { }); -mydb.fetch({ keys: ["foobar"] }, function (error: any, docs: any) { }); -mydb.fetchRevs({ keys: ["foobar"] }, function (error: any, docs: any) { }); -mydb.changes({ since: 0 }, function (error, response) { }); -mydb.compact(function (error) { }); +mydb.insert({ foo: "baz" }, null, (err, response) => {}); +mydb.insert({ foo: "baz" }, "foobar", (error, foo) => {}); +mydb.get("foobaz", { revs_info: true }, (error, foobaz) => {}); +mydb.head("foobaz", (error, body, headers) => {}); +mydb.copy("foo_src", "foo_dest", { overwrite: true }, (error, response, headers) => {}); +mydb.destroy("x", "x", (err, response) => {}); +mydb.bulk({ docs: [{ key: "baz", name: "bazzel" }, { key: "bar", name: "barry" }] }, (error: any, response: any) => {}); +mydb.list((error: any, docs: any) => {}); +mydb.fetch({ keys: ["foobar"] }, (error: any, docs: any) => {}); +mydb.fetchRevs({ keys: ["foobar"] }, (error: any, docs: any) => {}); +mydb.changes({ since: 0 }, (err, response) => {}); +mydb.compact((error) => {}); const feed = mydb.follow({ since: "0" }); -feed.on("change", function (change: any) { }); -mydb.atomic("update", "addbaz", "baz", function (error: any, response: any) { }); -mydb.viewWithList("people", "by_name_and_city", "my_list", { key: ["Derek", "San Francisco"] }, function (error, list) { }); -mydb.view("alice", "by_id", { keys: ["foobar", "barfoo"], "include_docs": true }, function (err, view) { }); -mydb.show("people", "singleDoc", "p_clemens", function (error: any, doc: any, rh: any) { }); -mydb.replicate("database_replica", function (error: any) { }); +feed.on("change", (change: any) => {}); +mydb.atomic("update", "addbaz", "baz", (error: any, response: any) => {}); +mydb.viewWithList("people", "by_name_and_city", "my_list", { key: ["Derek", "San Francisco"] }, (error, list) => {}); +mydb.view("alice", "by_id", { keys: ["foobar", "barfoo"], include_docs: true }, (err, view) => {}); +mydb.show("people", "singleDoc", "p_clemens", (error: any, doc: any, rh: any) => {}); +mydb.replicate("database_replica", (error: any) => {}); /* * Attachments */ -mydb.attachment.insert("new", "att", "Hello World!", "text/plain", function (error: any, att: any) { }); -mydb.attachment.destroy("new", "att", { rev: "123" }, function (error, response) { }); -mydb.attachment.get("new_string", "att", function (error: any, helloWorld: any) { }); +mydb.attachment.insert("new", "att", "Hello World!", "text/plain", (error: any, att: any) => {}); +mydb.attachment.destroy("new", "att", { rev: "123" }, (err, response) => {}); +mydb.attachment.get("new_string", "att", (error: any, helloWorld: any) => {}); /* * Multipart */ -mydb.multipart.insert({ "foo": "baz" }, [{}], "foobaz", function (error, foo) { }); -mydb.multipart.get("foobaz", function (error: any, foobaz: any, headers: any) { }); +mydb.multipart.insert({ foo: "baz" }, [{}], "foobaz", (error, foo) => {}); +mydb.multipart.get("foobaz", (error: any, foobaz: any, headers: any) => {}); /* * Piping */ const rs = fs.createReadStream(""); const is = mydb.attachment.insert("nodejs", "logo.png", null, "image/png"); -is.on("end", function () { }); -rs.pipe(is); \ No newline at end of file +is.on("end", () => {}); +rs.pipe(is); From e9547ae020a8e71630159652f6d483a271251dc0 Mon Sep 17 00:00:00 2001 From: Tim Jacobi Date: Fri, 30 Jun 2017 23:34:20 +0100 Subject: [PATCH 0124/1618] run prettier on tests --- types/nano/nano-tests.ts | 83 +++++++++++++++++++++++++++++++++------- 1 file changed, 69 insertions(+), 14 deletions(-) diff --git a/types/nano/nano-tests.ts b/types/nano/nano-tests.ts index 1e57052329..c65f2407ec 100644 --- a/types/nano/nano-tests.ts +++ b/types/nano/nano-tests.ts @@ -6,8 +6,8 @@ import * as path from "path"; * Instantiate with configuration object */ const config: nano.Configuration = { - url: "http://localhost:5984/foo", - requestDefaults: { proxy: "http://someproxy" } + url: "http://localhost:5984/foo", + requestDefaults: { proxy: "http://someproxy" } }; const cfgInstance = nano(config); @@ -15,15 +15,40 @@ const cfgInstance = nano(config); /* * Server Scope */ -const instance: nano.ServerScope = nano("http://localhost:5984/emails"); +const instance: nano.ServerScope = nano( + "http://localhost:5984/emails" +); instance.dinosaur("", (err, response) => {}); const url = instance.config.url; -instance.relax({ method: "POST", path: "_users", body: { _id: "org.couchdb.user:", type: "user", name: "ss", roles: ["admin"], password: "rf" } }, (err: any) => {}); +instance.relax( + { + method: "POST", + path: "_users", + body: { + _id: "org.couchdb.user:", + type: "user", + name: "ss", + roles: ["admin"], + password: "rf" + } + }, + (err: any) => {} +); instance.session((error, session) => {}); -instance.request({ db: "shared_headers", doc: "new", headers: { "If-None-Match": JSON.stringify({}) } }, (error, helloWorld, rh) => {}); -instance.relax({ db: "document_list", doc: "_all_docs", method: "GET", qs: { limit: 1 } }, (error, docs) => {}); +instance.request( + { + db: "shared_headers", + doc: "new", + headers: { "If-None-Match": JSON.stringify({}) } + }, + (error, helloWorld, rh) => {} +); +instance.relax( + { db: "document_list", doc: "_all_docs", method: "GET", qs: { limit: 1 } }, + (error, docs) => {} +); instance.auth("", "", (err: any, _: any, headers: any) => {}); instance.uuids(3, (error, data) => {}); @@ -32,7 +57,7 @@ instance.uuids(3, (error, data) => {}); */ const db: nano.DatabaseScope = instance.db; -db.create("az09_$()+-/", (err) => {}); +db.create("az09_$()+-/", err => {}); db.get("database_get", (err, response) => {}); db.destroy("_users", () => {}); db.list((error, list) => {}); @@ -48,26 +73,56 @@ mydb.insert({ foo: "baz" }, null, (err, response) => {}); mydb.insert({ foo: "baz" }, "foobar", (error, foo) => {}); mydb.get("foobaz", { revs_info: true }, (error, foobaz) => {}); mydb.head("foobaz", (error, body, headers) => {}); -mydb.copy("foo_src", "foo_dest", { overwrite: true }, (error, response, headers) => {}); +mydb.copy( + "foo_src", + "foo_dest", + { overwrite: true }, + (error, response, headers) => {} +); mydb.destroy("x", "x", (err, response) => {}); -mydb.bulk({ docs: [{ key: "baz", name: "bazzel" }, { key: "bar", name: "barry" }] }, (error: any, response: any) => {}); +mydb.bulk( + { docs: [{ key: "baz", name: "bazzel" }, { key: "bar", name: "barry" }] }, + (error: any, response: any) => {} +); mydb.list((error: any, docs: any) => {}); mydb.fetch({ keys: ["foobar"] }, (error: any, docs: any) => {}); mydb.fetchRevs({ keys: ["foobar"] }, (error: any, docs: any) => {}); mydb.changes({ since: 0 }, (err, response) => {}); -mydb.compact((error) => {}); +mydb.compact(error => {}); const feed = mydb.follow({ since: "0" }); feed.on("change", (change: any) => {}); mydb.atomic("update", "addbaz", "baz", (error: any, response: any) => {}); -mydb.viewWithList("people", "by_name_and_city", "my_list", { key: ["Derek", "San Francisco"] }, (error, list) => {}); -mydb.view("alice", "by_id", { keys: ["foobar", "barfoo"], include_docs: true }, (err, view) => {}); -mydb.show("people", "singleDoc", "p_clemens", (error: any, doc: any, rh: any) => {}); +mydb.viewWithList( + "people", + "by_name_and_city", + "my_list", + { key: ["Derek", "San Francisco"] }, + (error, list) => {} +); +mydb.view( + "alice", + "by_id", + { keys: ["foobar", "barfoo"], include_docs: true }, + (err, view) => {} +); +mydb.show( + "people", + "singleDoc", + "p_clemens", + (error: any, doc: any, rh: any) => {} +); mydb.replicate("database_replica", (error: any) => {}); /* * Attachments */ -mydb.attachment.insert("new", "att", "Hello World!", "text/plain", (error: any, att: any) => {}); +mydb.attachment.insert( + "new", + "att", + "Hello World!", + "text/plain", + (error: any, att: any) => {} +); mydb.attachment.destroy("new", "att", { rev: "123" }, (err, response) => {}); mydb.attachment.get("new_string", "att", (error: any, helloWorld: any) => {}); From 440b4d29da2c56da87d698e36645cc281f1945ed Mon Sep 17 00:00:00 2001 From: kamil bukum Date: Sat, 1 Jul 2017 02:50:07 +0300 Subject: [PATCH 0125/1618] * added new definiton type for 'framebus' library. --- types/framebus/framebus-tests.ts | 14 +++++ types/framebus/index.d.ts | 105 +++++++++++++++++++++++++++++++ types/framebus/tsconfig.json | 22 +++++++ types/framebus/tslint.json | 1 + 4 files changed, 142 insertions(+) create mode 100644 types/framebus/framebus-tests.ts create mode 100644 types/framebus/index.d.ts create mode 100644 types/framebus/tsconfig.json create mode 100644 types/framebus/tslint.json diff --git a/types/framebus/framebus-tests.ts b/types/framebus/framebus-tests.ts new file mode 100644 index 0000000000..9d135d8940 --- /dev/null +++ b/types/framebus/framebus-tests.ts @@ -0,0 +1,14 @@ +import * as framebus from "./index"; + +let popup = window.open('https://example.com'); +framebus.include(popup); +framebus.emit('hello popup and friends!'); + +framebus.target('https://example.com').on('my cool event', () => {}); + +framebus.publish('Marco!', callback, 'http://listener.example.com'); + +let callback = (data: any) => { + console.log('Got back %s as a reply!', data); +}; +framebus.publish('Marco!', callback, 'http://listener.example.com'); diff --git a/types/framebus/index.d.ts b/types/framebus/index.d.ts new file mode 100644 index 0000000000..7b9fab3d44 --- /dev/null +++ b/types/framebus/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for framebus 2.0 +// Project: https://github.com/braintree/framebus +// Definitions by: kbukum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ If this module is a UMD module that exposes a global variable 'myLib' when + *~ loaded outside a module loader environment, declare that global here. + *~ Otherwise, delete this declaration. + */ +export as namespace framebus; + +export interface FrameBus { + publish(event: string, args: any[], callback: Callback): boolean; + pub(event: string, args: any[], callback: Callback): boolean; + trigger(event: string, args: any[], callback: Callback): boolean; + emit(event: string, args: any[], callback: Callback): boolean; + subscribe(event: string, fn: Callback): boolean; + sub(event: string, fn: Callback): boolean; + on(event: string, fn: Callback): boolean; + unsubscribe(event: string, fn: Callback): boolean; + unsub(event: string, fn: Callback): boolean; + off(event: string, fn: Callback): boolean; +} +/*~ If this module has methods, declare them as functions like so. + */ +/** + * let popup = window.open('https://example.com'); + * framebus.include(popup); + * framebus.emit('hello popup and friends!'); + * @param popup + */ +export function include(popup: Window): boolean; +/** + * framebus.target('https://example.com').on('my cool event', function () {}); + * // will ignore all incoming 'my cool event' NOT from 'https://example.com' + * @param origin {string} + */ +export function target(origin: string): FrameBus; + +/** + * let callback = (data: any) => { + * console.log('Got back %s as a reply!', data) + * } + * framebus.publish('Marco!', callback, 'http://listener.example.com'); + * @param event {string} The name of the event + * @param args {...any[]} The data to give to subscribers + * // @param last{callback(data)} Give subscribers a function for easy, direct replies + */ +export function publish(event: string, ...args: any[]/* fn: callback(data:)*/): boolean; + +/** + * publish = pub = trigger = emit + * framebus.publish('Marco!', callback, 'http://listener.example.com'); + * @param event {string} The name of the event + * @param args {...any[]} The data to give to subscribers + * // @param last{callback(data)} Give subscribers a function for easy, direct replies + */ +export function pub(event: string, ...args: any[]): boolean; +/** + * publish = pub = trigger = emit + * @param event {string} The name of the event + * @param args {...any[]} The data to give to subscribers + * // @param last{callback(data)} Give subscribers a function for easy, direct replies + */ +export function trigger(event: string, ...args: any[]): boolean; +/** + * publish = pub = trigger = emit + * @param event {string} The name of the event + * @param args {...any[]} The data to give to subscribers + * // @param last{callback(data)} Give subscribers a function for easy, direct replies + */ +export function emit(event: string, ...args: any[]): boolean; +/** + * **this** scope is the MessageEvent object from the underlying postMessage + * @param event {string} The name of the event + * @param fn {Callback} ([arg...] [, callback]) Event handler. Arguments are from the publish invocation + */ +export function subscribe(event: string, fn: (...args: any[]) => any): boolean; +/** + * **this** scope is the MessageEvent object from the underlying postMessage + * @param event {string} The name of the event + * @param fn {Callback} ([arg...] [, callback]) Event handler. Arguments are from the publish invocation + */ +export function sub(event: string, fn: (...args: any[]) => any): boolean; +/** + * **this** scope is the MessageEvent object from the underlying postMessage + * @param event {string} The name of the event + * @param fn {Callback} ([arg...] [, callback]) Event handler. Arguments are from the publish invocation + */ +export function on(event: string, fn: (...args: any[]) => any): boolean; +/** + * @param event {string} The name of the event + * @param fn {Callback} The function that was subscribed + */ +export function unsubscribe(event: string, fn: (...args: any[]) => any): boolean; +/** + * @param event {string} The name of the event + * @param fn {Callback} The function that was subscribed + */ +export function unsub(event: string, fn: (...args: any[]) => any): boolean; +/** + * @param event {string} The name of the event + * @param fn {Callback} The function that was subscribed + */ +export function off(event: string, fn: (...args: any[]) => any): boolean; diff --git a/types/framebus/tsconfig.json b/types/framebus/tsconfig.json new file mode 100644 index 0000000000..2d0cd3530d --- /dev/null +++ b/types/framebus/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "framebus-tests.ts" + ] +} diff --git a/types/framebus/tslint.json b/types/framebus/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/framebus/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d4d886d72801bfe00b20556840b8983be74f1fe9 Mon Sep 17 00:00:00 2001 From: kamil bukum Date: Sat, 1 Jul 2017 03:02:49 +0300 Subject: [PATCH 0126/1618] * fixed dom and callback problems in test. --- types/framebus/framebus-tests.ts | 5 +++-- types/framebus/tsconfig.json | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/types/framebus/framebus-tests.ts b/types/framebus/framebus-tests.ts index 9d135d8940..b54c8dbee0 100644 --- a/types/framebus/framebus-tests.ts +++ b/types/framebus/framebus-tests.ts @@ -6,9 +6,10 @@ framebus.emit('hello popup and friends!'); framebus.target('https://example.com').on('my cool event', () => {}); -framebus.publish('Marco!', callback, 'http://listener.example.com'); - let callback = (data: any) => { console.log('Got back %s as a reply!', data); }; + +framebus.publish('Marco!', callback, 'http://listener.example.com'); + framebus.publish('Marco!', callback, 'http://listener.example.com'); diff --git a/types/framebus/tsconfig.json b/types/framebus/tsconfig.json index 2d0cd3530d..6444134bb7 100644 --- a/types/framebus/tsconfig.json +++ b/types/framebus/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, From ef2b0f232f1810295ba973c3427c5775b507e8ce Mon Sep 17 00:00:00 2001 From: kamil bukum Date: Sat, 1 Jul 2017 03:08:41 +0300 Subject: [PATCH 0127/1618] * fixed relative import problem. --- types/framebus/framebus-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/framebus/framebus-tests.ts b/types/framebus/framebus-tests.ts index b54c8dbee0..acd8f1ff2f 100644 --- a/types/framebus/framebus-tests.ts +++ b/types/framebus/framebus-tests.ts @@ -1,4 +1,4 @@ -import * as framebus from "./index"; +import * as framebus from "framebus"; let popup = window.open('https://example.com'); framebus.include(popup); From 430537fa7ae4fac13ccc51aa9c4021a0c3ff3cc9 Mon Sep 17 00:00:00 2001 From: kamil bukum Date: Sat, 1 Jul 2017 03:14:17 +0300 Subject: [PATCH 0128/1618] * fixed not found Callback problem. --- types/framebus/index.d.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/types/framebus/index.d.ts b/types/framebus/index.d.ts index 7b9fab3d44..88f6d5e238 100644 --- a/types/framebus/index.d.ts +++ b/types/framebus/index.d.ts @@ -10,16 +10,16 @@ export as namespace framebus; export interface FrameBus { - publish(event: string, args: any[], callback: Callback): boolean; - pub(event: string, args: any[], callback: Callback): boolean; - trigger(event: string, args: any[], callback: Callback): boolean; - emit(event: string, args: any[], callback: Callback): boolean; - subscribe(event: string, fn: Callback): boolean; - sub(event: string, fn: Callback): boolean; - on(event: string, fn: Callback): boolean; - unsubscribe(event: string, fn: Callback): boolean; - unsub(event: string, fn: Callback): boolean; - off(event: string, fn: Callback): boolean; + publish(event: string, args: any[], callback: (...args: any[]) => any): boolean; + pub(event: string, args: any[], callback: (...args: any[]) => any): boolean; + trigger(event: string, args: any[], callback: (...args: any[]) => any): boolean; + emit(event: string, args: any[], callback: (...args: any[]) => any): boolean; + subscribe(event: string, fn: (...args: any[]) => any): boolean; + sub(event: string, fn: (...args: any[]) => any): boolean; + on(event: string, fn: (...args: any[]) => any): boolean; + unsubscribe(event: string, fn: (...args: any[]) => any): boolean; + unsub(event: string, fn: (...args: any[]) => any): boolean; + off(event: string, fn: (...args: any[]) => any): boolean; } /*~ If this module has methods, declare them as functions like so. */ From 8b5a9d089f06a12ffde90a9694a94d6933de94c2 Mon Sep 17 00:00:00 2001 From: Jutta Klebe Date: Sat, 1 Jul 2017 23:09:27 +0200 Subject: [PATCH 0129/1618] Change indexer to KnockoutValidationRuleBase. --- types/knockout.validation/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/knockout.validation/index.d.ts b/types/knockout.validation/index.d.ts index 480a2607e7..5b8b61d066 100644 --- a/types/knockout.validation/index.d.ts +++ b/types/knockout.validation/index.d.ts @@ -158,7 +158,7 @@ interface KnockoutValidationRuleDefinitions { required: KnockoutValidationRuleDefinition; step: KnockoutValidationRuleDefinition; unique: KnockoutValidationRuleDefinition; - [ruleName: string]: KnockoutValidationRuleDefinition; + [ruleName: string]: KnockoutValidationRuleBase; } interface KnockoutValidationRule { From b658d363667264fb2e81284cfaa2f3208aa97c4b Mon Sep 17 00:00:00 2001 From: kamil bukum Date: Mon, 3 Jul 2017 09:52:51 +0300 Subject: [PATCH 0130/1618] * fixed problems methods. --- types/framebus/index.d.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/types/framebus/index.d.ts b/types/framebus/index.d.ts index 88f6d5e238..37f3ff7a4e 100644 --- a/types/framebus/index.d.ts +++ b/types/framebus/index.d.ts @@ -10,10 +10,10 @@ export as namespace framebus; export interface FrameBus { - publish(event: string, args: any[], callback: (...args: any[]) => any): boolean; - pub(event: string, args: any[], callback: (...args: any[]) => any): boolean; - trigger(event: string, args: any[], callback: (...args: any[]) => any): boolean; - emit(event: string, args: any[], callback: (...args: any[]) => any): boolean; + publish(event: string, ...args: any[]): boolean; + pub(event: string, ...args: any[]): boolean; + trigger(event: string, ...args: any[]): boolean; + emit(event: string, ...args: any[]): boolean; subscribe(event: string, fn: (...args: any[]) => any): boolean; sub(event: string, fn: (...args: any[]) => any): boolean; on(event: string, fn: (...args: any[]) => any): boolean; @@ -103,3 +103,4 @@ export function unsub(event: string, fn: (...args: any[]) => any): boolean; * @param fn {Callback} The function that was subscribed */ export function off(event: string, fn: (...args: any[]) => any): boolean; +} From 8e418e4a6ece4031e1c6c978e9ca22a1138beca7 Mon Sep 17 00:00:00 2001 From: kamil bukum Date: Mon, 3 Jul 2017 09:54:07 +0300 Subject: [PATCH 0131/1618] * fixed some functions problems. --- types/framebus/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/framebus/index.d.ts b/types/framebus/index.d.ts index 37f3ff7a4e..25286a495b 100644 --- a/types/framebus/index.d.ts +++ b/types/framebus/index.d.ts @@ -103,4 +103,3 @@ export function unsub(event: string, fn: (...args: any[]) => any): boolean; * @param fn {Callback} The function that was subscribed */ export function off(event: string, fn: (...args: any[]) => any): boolean; -} From e87ba7e90c6b7972811d01f21fc9a015d2a917f8 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Mon, 3 Jul 2017 12:41:37 +0200 Subject: [PATCH 0132/1618] add reconnect method --- types/fm-websync/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/fm-websync/index.d.ts b/types/fm-websync/index.d.ts index 14c9cae027..0a3f42958c 100644 --- a/types/fm-websync/index.d.ts +++ b/types/fm-websync/index.d.ts @@ -488,6 +488,12 @@ declare namespace fm { */ static initialize(config: initializeConfig): client; + /** + * Reconnects after a stream failure using either the most recent connectConfig or the one specified. + * This method should only be called from the callback specified by onSreamFailure and only if the args.willReconnect flag is set to false. Otherwise, the client will reconnect automatically. + */ + reconnect( config?: connectConfig ): client; + /** * Subscribes the client to receive messages on one or more channels. * When the subscribe completes successfully, the callback specified by onSuccess will be invoked, passing in the subscribed channel(s), From c4d1e138578635606b7db7d2276908cf1da920f4 Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Mon, 3 Jul 2017 15:01:22 +0200 Subject: [PATCH 0133/1618] updated bitcoinjs-lib to version 3.0.3 --- types/bitcoinjs-lib/index.d.ts | 1229 +++++++++++++++++++++++++---- types/bitcoinjs-lib/tsconfig.json | 2 +- 2 files changed, 1074 insertions(+), 157 deletions(-) diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index 600edda000..cc6dca8747 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -1,114 +1,234 @@ -// Type definitions for bitcoinjs-lib 2.3 -// Project: https://github.com/bitcoinjs/bitcoinjs-lib#readme -// Definitions by: Mohamed Hegazy -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** Declaration file initially generated by dts-gen for bitcoinjs-lib 3.0.3*/ + +// Definitions by: Daniel . +/* modified by dlebrecht based on the flow version found at https://github.com/flowtype/flow-typed/blob/master/definitions/npm/bitcoinjs-lib_v2.x.x/flow_v0.17.x-/bitcoinjs-lib_v2.x.x.js */ + + +export type Utxo = { + address: string; + amount: number; + scriptPubKey: Buffer; + txid: string; + vout: number; +} + +export type Output = { + script: Buffer; + value: number; +}; + +export type Input = { + script: Buffer; + hash: Buffer; + index: number; + sequence: number; +}; + +export type Network = { + bip32: { + public: number; + private: number; + }; + messagePrefix: string; + pubKeyHash: number; + scriptHash: number; + wif: number; +} + export class Block { constructor(); + + byteLength(headersOnly: any): any; + checkMerkleRoot(): any; + checkProofOfWork(): any; - getHash(): any; - getId(): any; + + getHash(): Buffer; + + getId(): string; + getUTCDate(): any; - toBuffer(headersOnly: any): any; - toHex(headersOnly: any): any; + + toBuffer(headersOnly?: boolean): Buffer; + + toHex(headersOnly?: boolean): string; + static calculateMerkleRoot(transactions: any): any; + static calculateTarget(bits: any): any; - static fromBuffer(buffer: any): any; - static fromHex(hex: any): any; + + static fromBuffer(buffer: Buffer): any; + + static fromHex(hex: string): any; + } + export class ECPair { - constructor(d: any, Q?: any, options?: any); + constructor(d: any, Q: any, options: any); + getAddress(): string; + getNetwork(): Network; - getPublicKeyBuffer(): any; - sign(hash: any): any; + + getPublicKeyBuffer(): Buffer; + + sign(hash: Buffer): Buffer; + toWIF(): string; - verify(hash: any, signature: any): boolean; - static fromPublicKeyBuffer(buffer: any, network: Network): ECPair; - static fromWIF(string: any, network?: Network): ECPair; + + verify(hash: Buffer, signature: ECSignature): boolean; + + static fromPublicKeyBuffer(buffer: Buffer, network: Network): ECPair; + + static fromWIF(string: string, network: Network): ECPair; + static makeRandom(options: any): ECPair; + } + export class ECSignature { constructor(r: any, s: any, ...args: any[]); + toCompact(i: any, compressed: any): any; + toDER(): any; + toScriptSignature(hashType: any): any; - static fromDER(buffer: any): ECSignature; - static parseCompact(buffer: any): ECSignature; - static parseScriptSignature(buffer: any): ECSignature; -} -export class HDNode { - constructor(keyPair: any, chainCode: any, ...args: any[]); - derive(index: any): any; - deriveHardened(index: any): any; - derivePath(path: any): any; - getAddress(): string; - getFingerprint(): any; - getIdentifier(): any; - getNetwork(): Network; - getPublicKeyBuffer(): any; - isNeutered(): any; - neutered(): any; - sign(hash: any): any; - toBase58(__isPrivate: any): any; - toString(__isPrivate: any): any; - verify(hash: any, signature: any): any; - static HIGHEST_BIT: number; - static LENGTH: number; - static fromBase58(string: any, networks: Network[]): HDNode; - static fromSeedBuffer(seed: any, network: Network, ...args: any[]): HDNode; - static fromSeedHex(hex: any, network: Network): HDNode; -} -export class Transaction { - constructor(); - addInput(hash: any, index: any, sequence: any, scriptSig: any, ...args: any[]): any; - addOutput(scriptPubKey: any, value: any, ...args: any[]): any; - byteLength(): number; - clone(): Transaction; - getHash(): any; - getId(): any; - hashForSignature(inIndex: any, prevOutScript: any, hashType: any, ...args: any[]): any; - isCoinbase(): boolean; - setInputScript(index: any, scriptSig: any, ...args: any[]): void; - toBuffer(buffer?: any, initialOffset?: any): Buffer; - toHex(): string; - static DEFAULT_SEQUENCE: number; - static SIGHASH_ALL: number; - static SIGHASH_ANYONECANPAY: number; - static SIGHASH_NONE: number; - static SIGHASH_SINGLE: number; - static fromBuffer(buffer: any, __noStrict: any): Transaction; - static fromHex(hex: any): Transaction; - static isCoinbaseHash(buffer: any): Transaction; -} -export class TransactionBuilder { - constructor(network?: Network); - addInput(txHash: any, vout: any, sequence?: any, prevOutScript?: any): any; - addOutput(scriptPubKey: any, value: any): any; - build(): Transaction; - buildIncomplete(): Transaction; - setLockTime(locktime: number): any; - setVersion(version: number): void; - sign(index: any, keyPair: any, redeemScript?: any, hashType?: any): any; - static fromTransaction(transaction: Transaction, network: Network): TransactionBuilder; + + static fromDER(buffer: Buffer): any; + + static parseCompact(buffer: Buffer): any; + + static parseScriptSignature(buffer: Buffer): any; + } -export interface Network { - bitcoin: { - private: number; - public: number; - }; - dustThreshold: number; - messagePrefix: string; - pubKeyHash: number; - scriptHash: number; - wif: number; +export class HDNode { + constructor(keyPair: ECPair, chainCode: any, ...args: any[]); + + keyPair: ECPair // dl added manually TODO check if correct + + derive(index: number): HDNode; + + deriveHardened(index: number): HDNode; + + derivePath(path: string): HDNode; + + getAddress(): string; + + getFingerprint(): Buffer; + + getIdentifier(): Buffer; + + getNetwork(): any; + + getPublicKeyBuffer(): Buffer; + + isNeutered(): boolean; + + neutered(): HDNode; + + sign(hash: Buffer): ECSignature; + + toBase58(__isPrivate?: any): string; + + verify(hash: Buffer, signature: any): Buffer; + + static HIGHEST_BIT: number; + + static LENGTH: number; + + static fromBase58(string: string, networks?: any): HDNode; + + static fromSeedBuffer(seed: Buffer, network: Network, ...args: any[]): HDNode; + + static fromSeedHex(hex: string, network: Network): HDNode; + } +export class Transaction { + version: number; + locktime: number; + ins: Array; + outs: Array; + constructor(); + + addInput(hash: Buffer, index: number, sequence: any, scriptSig: Buffer, ...args: any[]): any; + + addOutput(scriptPubKey: any, value: any, ...args: any[]): any; + + byteLength(): any; + + clone(): Transaction; + + getHash(): Buffer; + + getId(): any; + + hasWitnesses(): any; + + hashForSignature(inindex: number, prevOutScript: any, hashType: any, ...args: any[]): any; + + hashForWitnessV0(inindex: number, prevOutScript: any, value: any, hashType: any, ...args: any[]): any; + + isCoinbase(): boolean; + + setInputScript(index: number, scriptSig: Buffer, ...args: any[]): void; + + setWitness(index: number, witness: any, ...args: any[]): void; + + toBuffer(buffer: Buffer, initialOffset: any): Buffer; + + toHex(): any; + + static ADVANCED_TRANSACTION_FLAG: number; + + static ADVANCED_TRANSACTION_MARKER: number; + + static DEFAULT_SEQUENCE: number; + + static SIGHASH_ALL: number; + + static SIGHASH_ANYONECANPAY: number; + + static SIGHASH_NONE: number; + + static SIGHASH_SINGLE: number; + + static fromBuffer(buffer: Buffer, __noStrict: any): Transaction; + + static fromHex(hex: string): Transaction; + + static isCoinbaseHash(buffer: Buffer): any; + +} + +export class TransactionBuilder { + constructor(network: Network, maximumFeeRate?: any); + + addInput(txhash: Buffer|string|Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): void; + + addOutput(scriptPubKey: Buffer|string, value: any): any; + + build(): Transaction; + + buildIncomplete(): Transaction; + + setLockTime(locktime: number): void; + + setVersion(version: number): void; + + sign(vin: number, keyPair: ECPair, redeemScript?: Buffer, hashType?: number, witnessValue?: any, witnessScript?: any): void; + + static fromTransaction(transaction: Transaction, network: Network): TransactionBuilder; + +} + + export const networks: { - bitcoin: Network; - dogecoin: Network; + bitcoin: Network ; litecoin: Network; testnet: Network; }; @@ -232,172 +352,969 @@ export const opcodes: { OP_WITHIN: number; OP_XOR: number; }; + export namespace HDNode { namespace MASTER_SECRET { const BYTES_PER_ELEMENT: number; + const byteLength: number; + const byteOffset: number; + const length: number; + const offset: number; + function asciiSlice(): any; + function asciiWrite(): any; + function base64Slice(): any; + function base64Write(): any; - function compare(target: any, start: any, end: any, thisStart: any, thisEnd: any): any; + + function compare(target: any, start: any, end: any, thisStart: any, thisEnd: any, ...args: any[]): any; + function copy(): any; + function copyWithin(p0: any, p1: any): any; + function entries(): any; + function equals(b: any): any; + function every(p0: any): any; + function fill(val: any, start: any, end: any, encoding: any): any; + function filter(p0: any): any; + function find(p0: any): any; + function findIndex(p0: any): any; + function forEach(p0: any): any; + function hexSlice(): any; + function hexWrite(): any; + function includes(val: any, byteOffset: any, encoding: any): any; + function indexOf(val: any, byteOffset: any, encoding: any): any; + function inspect(): any; + function join(p0: any): any; + function keys(): any; + function lastIndexOf(val: any, byteOffset: any, encoding: any): any; + function latin1Slice(): any; + function latin1Write(): any; + function map(p0: any): any; + function readDoubleBE(offset: any, noAssert: any): any; + function readDoubleLE(offset: any, noAssert: any): any; + function readFloatBE(offset: any, noAssert: any): any; + function readFloatLE(offset: any, noAssert: any): any; + function readInt16BE(offset: any, noAssert: any): any; + function readInt16LE(offset: any, noAssert: any): any; + function readInt32BE(offset: any, noAssert: any): any; + function readInt32LE(offset: any, noAssert: any): any; + function readInt8(offset: any, noAssert: any): any; + function readIntBE(offset: any, byteLength: any, noAssert: any): any; + function readIntLE(offset: any, byteLength: any, noAssert: any): any; + function readUInt16BE(offset: any, noAssert: any): any; + function readUInt16LE(offset: any, noAssert: any): any; + function readUInt32BE(offset: any, noAssert: any): any; + function readUInt32LE(offset: any, noAssert: any): any; + function readUInt8(offset: any, noAssert: any): any; + function readUIntBE(offset: any, byteLength: any, noAssert: any): any; + function readUIntLE(offset: any, byteLength: any, noAssert: any): any; + function reduce(p0: any): any; + function reduceRight(p0: any): any; + function reverse(): any; + function set(p0: any): any; + function slice(start: any, end: any): any; + function some(p0: any): any; + function sort(p0: any): any; + function subarray(p0: any, p1: any): any; + function swap16(): any; + function swap32(): any; + function swap64(): any; + function toJSON(): any; - function toLocaleString(): any; - function toString(...args: any[]): any; + + function toLocaleString(encoding: any, start: any, end: any, ...args: any[]): any; + + function toString(encoding: any, start: any, end: any, ...args: any[]): any; + function ucs2Slice(): any; + function ucs2Write(): any; - function undefined(): any; + function utf8Slice(): any; + function utf8Write(): any; + function values(): any; + function write(string: any, offset: any, length: any, encoding: any): any; + function writeDoubleBE(val: any, offset: any, noAssert: any): any; + function writeDoubleLE(val: any, offset: any, noAssert: any): any; + function writeFloatBE(val: any, offset: any, noAssert: any): any; + function writeFloatLE(val: any, offset: any, noAssert: any): any; + function writeInt16BE(value: any, offset: any, noAssert: any): any; + function writeInt16LE(value: any, offset: any, noAssert: any): any; + function writeInt32BE(value: any, offset: any, noAssert: any): any; + function writeInt32LE(value: any, offset: any, noAssert: any): any; + function writeInt8(value: any, offset: any, noAssert: any): any; + function writeIntBE(value: any, offset: any, byteLength: any, noAssert: any): any; + function writeIntLE(value: any, offset: any, byteLength: any, noAssert: any): any; + function writeUInt16BE(value: any, offset: any, noAssert: any): any; + function writeUInt16LE(value: any, offset: any, noAssert: any): any; + function writeUInt32BE(value: any, offset: any, noAssert: any): any; + function writeUInt32LE(value: any, offset: any, noAssert: any): any; + function writeUInt8(value: any, offset: any, noAssert: any): any; + function writeUIntBE(value: any, offset: any, byteLength: any, noAssert: any): any; + function writeUIntLE(value: any, offset: any, byteLength: any, noAssert: any): any; + + namespace asciiSlice { + const prototype: { + }; + + } + + namespace asciiWrite { + const prototype: { + }; + + } + + namespace base64Slice { + const prototype: { + }; + + } + + namespace base64Write { + const prototype: { + }; + + } + namespace buffer { const byteLength: number; + function slice(p0: any, p1: any): any; + } + + namespace compare { + const prototype: { + }; + + } + + namespace copy { + const prototype: { + }; + + } + + namespace equals { + const prototype: { + }; + + } + + namespace fill { + const prototype: { + }; + + } + + namespace hexSlice { + const prototype: { + }; + + } + + namespace hexWrite { + const prototype: { + }; + + } + + namespace includes { + const prototype: { + }; + + } + + namespace indexOf { + const prototype: { + }; + + } + + namespace inspect { + const prototype: { + }; + + } + + namespace lastIndexOf { + const prototype: { + }; + + } + + namespace latin1Slice { + const prototype: { + }; + + } + + namespace latin1Write { + const prototype: { + }; + + } + namespace parent { const byteLength: number; + function slice(p0: any, p1: any): any; + } + + namespace readDoubleBE { + const prototype: { + }; + + } + + namespace readDoubleLE { + const prototype: { + }; + + } + + namespace readFloatBE { + const prototype: { + }; + + } + + namespace readFloatLE { + const prototype: { + }; + + } + + namespace readInt16BE { + const prototype: { + }; + + } + + namespace readInt16LE { + const prototype: { + }; + + } + + namespace readInt32BE { + const prototype: { + }; + + } + + namespace readInt32LE { + const prototype: { + }; + + } + + namespace readInt8 { + const prototype: { + }; + + } + + namespace readIntBE { + const prototype: { + }; + + } + + namespace readIntLE { + const prototype: { + }; + + } + + namespace readUInt16BE { + const prototype: { + }; + + } + + namespace readUInt16LE { + const prototype: { + }; + + } + + namespace readUInt32BE { + const prototype: { + }; + + } + + namespace readUInt32LE { + const prototype: { + }; + + } + + namespace readUInt8 { + const prototype: { + }; + + } + + namespace readUIntBE { + const prototype: { + }; + + } + + namespace readUIntLE { + const prototype: { + }; + + } + + namespace slice { + const prototype: { + }; + + } + + namespace swap16 { + const prototype: { + }; + + } + + namespace swap32 { + const prototype: { + }; + + } + + namespace swap64 { + const prototype: { + }; + + } + + namespace toJSON { + const prototype: { + }; + + } + + namespace toLocaleString { + const prototype: { + }; + + } + + namespace toString { + const prototype: { + }; + + } + + namespace ucs2Slice { + const prototype: { + }; + + } + + namespace ucs2Write { + const prototype: { + }; + + } + + namespace utf8Slice { + const prototype: { + }; + + } + + namespace utf8Write { + const prototype: { + }; + + } + + namespace write { + const prototype: { + }; + + } + + namespace writeDoubleBE { + const prototype: { + }; + + } + + namespace writeDoubleLE { + const prototype: { + }; + + } + + namespace writeFloatBE { + const prototype: { + }; + + } + + namespace writeFloatLE { + const prototype: { + }; + + } + + namespace writeInt16BE { + const prototype: { + }; + + } + + namespace writeInt16LE { + const prototype: { + }; + + } + + namespace writeInt32BE { + const prototype: { + }; + + } + + namespace writeInt32LE { + const prototype: { + }; + + } + + namespace writeInt8 { + const prototype: { + }; + + } + + namespace writeIntBE { + const prototype: { + }; + + } + + namespace writeIntLE { + const prototype: { + }; + + } + + namespace writeUInt16BE { + const prototype: { + }; + + } + + namespace writeUInt16LE { + const prototype: { + }; + + } + + namespace writeUInt32BE { + const prototype: { + }; + + } + + namespace writeUInt32LE { + const prototype: { + }; + + } + + namespace writeUInt8 { + const prototype: { + }; + + } + + namespace writeUIntBE { + const prototype: { + }; + + } + + namespace writeUIntLE { + const prototype: { + }; + + } + } + + } + + + export namespace address { - function fromBase58Check(address: any): any; - function fromOutputScript(scriptPubKey: any, network?: Network): any; - function toBase58Check(hash: any, version: any, ...args: any[]): any; - function toOutputScript(address: any, network?: Network): any; -} -export namespace bufferutils { - function equal(a: any, b: any): any; - function pushDataSize(i: any): any; - function readPushDataInt(buffer: any, offset: any): any; - function readUInt64LE(buffer: any, offset: any): any; - function readVarInt(buffer: any, offset: any): any; - function reverse(src: any): any; - function varIntBuffer(i: any): any; - function varIntSize(i: any): any; - function writePushDataInt(buffer: any, number: any, offset: any): any; - function writeUInt64LE(buffer: any, value: any, offset: any): void; - function writeVarInt(buffer: any, number: any, offset: any): any; -} -export namespace crypto { - function hash160(buffer: any): any; - function hash256(buffer: any): any; - function ripemd160(buffer: any): any; - function sha1(buffer: any): any; - function sha256(buffer: any): any; -} -export namespace message { - function magicHash(message: any, network: any): any; - function sign(keyPair: any, message: any, network: any): any; - function verify(address: any, signature: any, message: any, network: any): any; -} -export namespace script { - function classifyInput(script: any, allowIncomplete: any): any; - function classifyOutput(script: any): any; - function compile(chunks: any): any; - function decompile(buffer: any): any; - function fromASM(asm: any): any; - function isCanonicalPubKey(buffer: any): any; - function isCanonicalSignature(buffer: any): any; - function isDefinedHashType(hashType: any): any; - function isMultisigInput(script: any, allowIncomplete: any): any; - function isMultisigOutput(script: any): any; - function isNullDataOutput(script: any): any; - function isPubKeyHashInput(script: any): any; - function isPubKeyHashOutput(script: any): any; - function isPubKeyInput(script: any): any; - function isPubKeyOutput(script: any): any; - function isScriptHashInput(script: any, allowIncomplete: any): any; - function isScriptHashOutput(script: any): any; - function isWitnessPubKeyHashOutput(script: any): any; - function isWitnessScriptHashOutput(script: any): any; - function multisigInput(signatures: any, scriptPubKey: any): any; - function multisigOutput(m: any, pubKeys: any, ...args: any[]): any; - function nullDataOutput(data: any): any; - function pubKeyHashInput(signature: any, pubKey: any, ...args: any[]): any; - function pubKeyHashOutput(pubKeyHash: any): any; - function pubKeyInput(signature: any): any; - function pubKeyOutput(pubKey: any): any; - function scriptHashInput(scriptSig: any, scriptPubKey: any): any; - function scriptHashOutput(scriptHash: any): any; - function toASM(chunks: any): any; - function witnessPubKeyHashOutput(pubKeyHash: any): any; - function witnessScriptHashInput(scriptSig: any, scriptPubKey: any): any; - function witnessScriptHashOutput(scriptHash: any): any; - namespace number { - function decode(buffer: any, maxLength: any, minimal: any): any; - function encode(number: any): any; + function fromBase58Check(address: string): string; + + function fromOutputScript(outputScript: Buffer, network: Network): string; + + function toBase58Check(hash: Buffer, version: number, ...args: any[]): any; + + function toOutputScript(address: string, network: Network): any; + + namespace fromBase58Check { + const prototype: { + }; + } + + namespace fromOutputScript { + const prototype: { + }; + + } + + namespace toBase58Check { + const prototype: { + }; + + } + + namespace toOutputScript { + const prototype: { + }; + + } + +} + +export namespace bufferutils { + function pushDataSize(i: any): any; + + function readPushDataInt(buffer: Buffer, offset: any): any; + + function readUInt64LE(buffer: Buffer, offset: any): any; + + function readVarInt(buffer: Buffer, offset: any): any; + + function varIntBuffer(number: number, buffer: Buffer, offset: any): any; + + function varIntSize(number: number): any; + + function writePushDataInt(buffer: Buffer, number: number, offset: any): any; + + function writeUInt64LE(buffer: Buffer, value: any, offset: any): any; + + function writeVarInt(buffer: Buffer, number: number, offset: any): any; + + namespace pushDataSize { + const prototype: { + }; + + } + + namespace readPushDataInt { + const prototype: { + }; + + } + + namespace readUInt64LE { + const prototype: { + }; + + } + + namespace readVarInt { + const prototype: { + }; + + } + + namespace varIntBuffer { + const prototype: { + }; + + } + + namespace varIntSize { + const prototype: { + }; + + } + + namespace writePushDataInt { + const prototype: { + }; + + } + + namespace writeUInt64LE { + const prototype: { + }; + + } + + namespace writeVarInt { + const prototype: { + }; + + } + +} + +export namespace crypto { + function hash160(buffer: Buffer): Buffer; + + function hash256(buffer: Buffer): any; + + function ripemd160(buffer: Buffer): any; + + function sha1(buffer: Buffer): any; + + function sha256(buffer: Buffer): any; + + namespace hash160 { + const prototype: { + }; + + } + + namespace hash256 { + const prototype: { + }; + + } + + namespace ripemd160 { + const prototype: { + }; + + } + + namespace sha1 { + const prototype: { + }; + + } + + namespace sha256 { + const prototype: { + }; + + } + +} + +export namespace script { + const multisig: { + input: { + check: any; + decode: any; + decodeStack: any; + encode: any; + encodeStack: any; + }; + output: { + check: any; + decode: any; + encode: any; + }; + }; + + const nullData: { + output: { + check: any; + decode: any; + encode: any; + }; + }; + + const pubKey: { + input: { + check: any; + decode: any; + decodeStack: any; + encode: any; + encodeStack: any; + }; + output: { + check: any; + decode: any; + encode: any; + }; + }; + + const pubKeyHash: { + input: { + check: any; + decode: any; + decodeStack: any; + encode: any; + encodeStack: any; + }; + output: { + check: any; + decode: any; + encode: any; + }; + }; + + const scriptHash: { + input: { + check: any; + decode: any; + decodeStack: any; + encode: any; + encodeStack: any; + }; + output: { + check: any; + decode: any; + encode: any; + }; + }; + + const types: { + MULTISIG: string; + NONSTANDARD: string; + NULLDATA: string; + P2PK: string; + P2PKH: string; + P2SH: string; + P2WPKH: string; + P2WSH: string; + WITNESS_COMMITMENT: string; + }; + + const witnessCommitment: { + output: { + check: any; + decode: any; + encode: any; + }; + }; + + const witnessPubKeyHash: { + input: { + check: any; + decodeStack: any; + encodeStack: any; + }; + output: { + check: any; + decode: any; + encode: any; + }; + }; + + const witnessScriptHash: { + input: { + check: any; + decodeStack: any; + encodeStack: any; + }; + output: { + check: any; + decode: any; + encode: any; + }; + }; + + function classifyInput(script: any, allowIncomplete: any): any; + + function classifyOutput(script: any): any; + + function classifyWitness(script: any, allowIncomplete: any): any; + + function compile(chunks: any): any; + + function decompile(buffer: Buffer): any; + + function fromASM(asm: any): any; + + function isCanonicalPubKey(buffer: Buffer): any; + + function isCanonicalSignature(buffer: Buffer): any; + + function isDefinedHashType(hashType: any): any; + + function isPushOnly(value: any): any; + + function toASM(chunks: any): any; + + function toStack(chunks: any): any; + + namespace classifyInput { + const prototype: { + }; + + } + + namespace classifyOutput { + const prototype: { + }; + + } + + namespace classifyWitness { + const prototype: { + }; + + } + + namespace compile { + const prototype: { + }; + + } + + namespace decompile { + const prototype: { + }; + + } + + namespace fromASM { + const prototype: { + }; + + } + + namespace isCanonicalPubKey { + const prototype: { + }; + + } + + namespace isCanonicalSignature { + const prototype: { + }; + + } + + namespace isDefinedHashType { + const prototype: { + }; + + } + + namespace isPushOnly { + const prototype: { + }; + + } + + namespace number { + function decode(buffer: Buffer, maxLength: any, minimal: any): any; + + function encode(number: number): any; + + namespace decode { + const prototype: { + }; + + } + + namespace encode { + const prototype: { + }; + + } + + } + + namespace toASM { + const prototype: { + }; + + } + + namespace toStack { + const prototype: { + }; + + } + } diff --git a/types/bitcoinjs-lib/tsconfig.json b/types/bitcoinjs-lib/tsconfig.json index 7a9a4cf261..d1f5ec75b6 100644 --- a/types/bitcoinjs-lib/tsconfig.json +++ b/types/bitcoinjs-lib/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "bitcoinjs-lib-tests.ts" ] -} \ No newline at end of file +} From 50f37e2318f586bec8f75e922c3c6078c907c794 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Tue, 4 Jul 2017 02:41:15 +0300 Subject: [PATCH 0134/1618] Added cloudflare-apps types. --- .../cloudflare-apps/cloudflare-apps-tests.ts | 73 +++++++++++ types/cloudflare-apps/index.d.ts | 114 ++++++++++++++++++ types/cloudflare-apps/tsconfig.json | 24 ++++ types/cloudflare-apps/tslint.json | 3 + 4 files changed, 214 insertions(+) create mode 100644 types/cloudflare-apps/cloudflare-apps-tests.ts create mode 100644 types/cloudflare-apps/index.d.ts create mode 100644 types/cloudflare-apps/tsconfig.json create mode 100644 types/cloudflare-apps/tslint.json diff --git a/types/cloudflare-apps/cloudflare-apps-tests.ts b/types/cloudflare-apps/cloudflare-apps-tests.ts new file mode 100644 index 0000000000..35216331ee --- /dev/null +++ b/types/cloudflare-apps/cloudflare-apps-tests.ts @@ -0,0 +1,73 @@ +import * as cloudflareApps from "cloudflare-apps"; + +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; + +describe("Globals", () => { + it("INSTALL_OPTIONS returns InstallOptions (dictionary)", () => { + const options: cloudflareApps.InstallOptions = INSTALL_OPTIONS; + }); + + it("INSTALL_ID should return string", () => { + const id: string = INSTALL_ID; + }); + + it("INSTALL_SCOPE returns InstallScope (dictionary)", () => { + const scope: cloudflareApps.InstallScope = INSTALL_SCOPE; + }); + + it("INSTALL_PRODUCT returns InstallProduct", () => { + const product: cloudflareApps.InstallProduct | undefined = INSTALL_PRODUCT; + + if (product != null) { + const id = product.id; + } + }); + + it("INSTALL", () => { + const id: string = INSTALL.siteId; + }); + + it("CloudflareApps is CloudflareApps object", () => { + const apps: cloudflareApps.CloudflareApps = CloudflareApps; + }); +}); + +describe("CloudflareApps methods", () => { + it("createElement", () => { + const element = CloudflareApps.createElement({ + method: "replace", + selector: "body > *" + }); + }); + + it("matchPage", () => { + // Example: domain.com + const truthyMatch: boolean = CloudflareApps.matchPage(["domain"]); + const falsyMatch: boolean = CloudflareApps.matchPage(["foobar"]); + }); + + it("querySelector", () => { + const element: Element = CloudflareApps.querySelector("body > *"); + }); +}); + +describe("CloudflareApps properties", () => { + it("installs", () => { + const appId = "preview"; + const app: cloudflareApps.App | undefined = CloudflareApps.installs[appId]; + + if (app != null) { + const id: string = app.appId; + } + }); + + it("proxy", () => { + const proxy: cloudflareApps.CloudflareAppsProxy = CloudflareApps.proxy; + const siteId: string = proxy.embedSiteId; + }); + + it("siteId", () => { + const siteId: string = CloudflareApps.siteId; + }); +}); diff --git a/types/cloudflare-apps/index.d.ts b/types/cloudflare-apps/index.d.ts new file mode 100644 index 0000000000..9436a568d9 --- /dev/null +++ b/types/cloudflare-apps/index.d.ts @@ -0,0 +1,114 @@ +// Type definitions for cloudflare-apps 0.1 +// Project: https://www.cloudflare.com/apps/ +// Definitions by: MartynasZilinskas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +declare global { + /** + * An object which contains all of the options the installer specified, + * based on the structure given in the options section of your `install.json`. + */ + const INSTALL_OPTIONS: InstallOptions; + + /** + * A string ID which is equal to the ID of this install. + * Its primary purpose is to allow you to easily distinguish between your app being loaded + * in the Cloudflare Preview or the installer’s live website. + */ + const INSTALL_ID: string; + + /** + * An object which you can use to store arbitrary values + * which you would like to be accessable from other Cloudflare scripts, + * without polluting the global scope. + * For example, it’s commonly used to share an update function with its update handler. + */ + const INSTALL_SCOPE: InstallScope; + + /** + * This object is specific to paid apps. It allows you to know which product the user has purchased. + * When you create a paid app you will be given product ids for each of the plans you wish to sell the product for. + * `INSTALL_PRODUCT.id` will then be that id for the plan the user has purchased. + * This value is absent for free apps and will always be set for paid apps even if the user is on a free plan. + */ + const INSTALL_PRODUCT: InstallProduct | undefined; + + /** + * It's the same as CloudflareApps variable. + * + * DON'T use this variable directly. + * BAD Example: + * ```ts + * const apps: cloudflareApps.CloudflareApps = INSTALL; + * ``` + * ------------------------------------------------- + * Use directly properties and methods. + * GOOD Example: + * ```ts + * const siteId: string = INSTALL.siteId; + * ``` + */ + const INSTALL: CloudflareApps; + + /** + * This is undocumented global variable. + * The documentation may arrive later. + */ + const CloudflareApps: CloudflareApps; +} + +export interface InstallOptions { + [key: string]: any; +} + +export interface InstallScope { + [key: string]: any; +} + +export interface InstallProduct { + id: string; +} + +export interface CloudflareApps { + createElement(options: ElementLocation, previousElement?: Element): Element; + matchPage(patterns: string[]): boolean; + querySelector(selector: string): Element; + installs: { [id: string]: App | undefined }; + proxy: CloudflareAppsProxy; + siteId: string; +} + +export interface App { + appId: string; + options: InstallOptions; + scope: InstallScope; +} + +export interface CloudflareAppsProxy { + embedSiteId: string; + hasRocketEmbed: boolean; + originalURL: OriginalURL; +} + +export interface OriginalURL { + raw: string; + parsed: OriginalURLParsed; +} + +export interface OriginalURLParsed { + fragment: string; + host: string; + path: string; + scheme: "https" | "http"; + query: URLQuery; +} + +export interface URLQuery { + [key: string]: string[]; +} + +export interface ElementLocation { + method: "before" | "prepend" | "append" | "after" | "replace"; + selector: string; +} diff --git a/types/cloudflare-apps/tsconfig.json b/types/cloudflare-apps/tsconfig.json new file mode 100644 index 0000000000..9f3ed2ece7 --- /dev/null +++ b/types/cloudflare-apps/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts", + "cloudflare-apps-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } +} diff --git a/types/cloudflare-apps/tslint.json b/types/cloudflare-apps/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cloudflare-apps/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From c4091e488889ecd59e09c520c07c4d87752182cf Mon Sep 17 00:00:00 2001 From: Diogo Franco Date: Tue, 4 Jul 2017 11:28:17 +0900 Subject: [PATCH 0135/1618] Improve type of HandlebarsTemplateDelegate Adds an optional type argument that should be useful for .hbs.d.ts files. The RuntimeOptions were specified by looking at https://github.com/wycats/handlebars.js/blob/680ec96/lib/handlebars/runtime.js#L131-L171 -- these don't seem to be documented anywhere. --- types/handlebars/index.d.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/types/handlebars/index.d.ts b/types/handlebars/index.d.ts index 71cc0a2cfe..7572d19824 100644 --- a/types/handlebars/index.d.ts +++ b/types/handlebars/index.d.ts @@ -96,8 +96,8 @@ interface HandlebarsTemplatable { template: HandlebarsTemplateDelegate; } -interface HandlebarsTemplateDelegate { - (context: any, options?: any): string; +interface HandlebarsTemplateDelegate { + (context: T, options?: RuntimeOptions): string; } interface HandlebarsTemplates { @@ -108,6 +108,14 @@ interface TemplateSpecification { } +interface RuntimeOptions { + partial?: boolean; + depths?: any[]; + helpers?: { [name: string]: Function } + partials?: { [name: string]: HandlebarsTemplateDelegate } + decorators?: { [name: string]: Function } +} + interface CompileOptions { data?: boolean; compat?: boolean; From 6af5d2a55f506eeb2304904371e465f05b6ba5fe Mon Sep 17 00:00:00 2001 From: Diogo Franco Date: Tue, 4 Jul 2017 11:35:54 +0900 Subject: [PATCH 0136/1618] Update TypeScript version --- types/handlebars/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/handlebars/index.d.ts b/types/handlebars/index.d.ts index 7572d19824..f4cba279bf 100644 --- a/types/handlebars/index.d.ts +++ b/types/handlebars/index.d.ts @@ -2,6 +2,7 @@ // Project: http://handlebarsjs.com/ // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace Handlebars { From 7259fc89f93797f084f019725c808549f95d92f9 Mon Sep 17 00:00:00 2001 From: "Diogo Franco (Kovensky)" Date: Tue, 4 Jul 2017 11:43:41 +0900 Subject: [PATCH 0137/1618] Update the minimum required version on affected files --- types/handlebars/index.d.ts | 1 - types/koa-hbs/index.d.ts | 3 ++- types/swag/index.d.ts | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/handlebars/index.d.ts b/types/handlebars/index.d.ts index f4cba279bf..17014d464a 100644 --- a/types/handlebars/index.d.ts +++ b/types/handlebars/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 - declare namespace Handlebars { export function registerHelper(name: string, fn: Function, inverse?: boolean): void; export function registerHelper(name: Object): void; diff --git a/types/koa-hbs/index.d.ts b/types/koa-hbs/index.d.ts index 481738efc3..cace80c852 100644 --- a/types/koa-hbs/index.d.ts +++ b/types/koa-hbs/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gilt/koa-hbs // Definitions by: Jacob Malone , Mudkip // Definitions: https://github.com/jcbmln/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== @@ -57,4 +58,4 @@ declare module "koa" { export interface Context { render(tpl: string, locals?: {[key: string]: any}): Promise; } -} \ No newline at end of file +} diff --git a/types/swag/index.d.ts b/types/swag/index.d.ts index 29ba129fe5..cd7bb6ccaa 100644 --- a/types/swag/index.d.ts +++ b/types/swag/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/elving/swag // Definitions by: Shogo Iwano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// From fda59743791dd3c720ec557eefc47a0109b89c39 Mon Sep 17 00:00:00 2001 From: "Diogo Franco (Kovensky)" Date: Tue, 4 Jul 2017 11:47:10 +0900 Subject: [PATCH 0138/1618] Use the typed HandlebarsTemplateDelegate in tests --- types/handlebars/handlebars-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/handlebars/handlebars-tests.ts b/types/handlebars/handlebars-tests.ts index 71215b5294..f5105c2122 100644 --- a/types/handlebars/handlebars-tests.ts +++ b/types/handlebars/handlebars-tests.ts @@ -36,7 +36,7 @@ var post = { url: '/hello-world', body: 'Hello World!' }; var context2 = { posts: [post] }; var source2 = '
    {{#posts}}
  • {{{link_to this}}}
  • {{/posts}}
'; -var template2 = Handlebars.compile(source2); +var template2: HandlebarsTemplateDelegate<{ posts: { url: string, body: string }[] }> = Handlebars.compile(source2); template2(context2); Handlebars.registerHelper('link_to', (title: string, context: typeof post) => { From 272655e30dd7f80b65872de270610e4844a6d0be Mon Sep 17 00:00:00 2001 From: Chris Krycho Date: Mon, 3 Jul 2017 22:47:31 -0400 Subject: [PATCH 0139/1618] Add ember-testing lib helpers. --- .../ember-testing-helpers-tests.ts | 79 +++++++++++++++++++ types/ember-testing-helpers/index.d.ts | 63 +++++++++++++++ types/ember-testing-helpers/tsconfig.json | 21 +++++ 3 files changed, 163 insertions(+) create mode 100644 types/ember-testing-helpers/ember-testing-helpers-tests.ts create mode 100644 types/ember-testing-helpers/index.d.ts create mode 100644 types/ember-testing-helpers/tsconfig.json diff --git a/types/ember-testing-helpers/ember-testing-helpers-tests.ts b/types/ember-testing-helpers/ember-testing-helpers-tests.ts new file mode 100644 index 0000000000..9088097b25 --- /dev/null +++ b/types/ember-testing-helpers/ember-testing-helpers-tests.ts @@ -0,0 +1,79 @@ +function testAndThen() { + const result: RSVP.Promise = andThen(() => "some string"); + result.then(s => s.length); +} + +function testClick() { + const result: RSVP.Promise = click('someString'); + result.then(() => {}); +} + +function testCurrentPath() { + const path = currentPath(); + const chars = path.split(''); +} + +function testCurrentRouteName() { + const routeName = currentRouteName(); + const isIndex = routeName === 'index'; +} + +function testCurrentURL() { + const url = currentURL(); + const isIndex = url.match(/^\/$/); +} + +function testFillIn() { + const textResult = fillIn('.foo', 'waffles'); + textResult.then(() => true); + const contextResult = fillIn('.bar', { }, 'pancakes'); + contextResult.catch(reason => false); +} + +function testFind() { + const found = find('#quux'); + found.addClass('has-ducks'); + + const foundInAContext = find('#baz', {}); + foundInAContext.removeClass('can-cluck'); +} + +function testFindWithAssert() { + const found = findWithAssert('#quux'); + found.addClass('has-ducks'); + + const foundInAContext = findWithAssert('#baz', {}); + foundInAContext.removeClass('can-cluck'); +} + +function testKeyEvent() { + keyEvent('.some-button', 'keydown', 11).then(() => 11); + keyEvent('.some-button', 'keypress', 101).then(() => 101); + keyEvent('.some-button', 'keyup', 1001).then(() => 1001); +} + +function testPauseTest() { + pauseTest().finally(() => { + const foo = 'fighters'; + }) +} + +function testResumeTest() { + resumeTest(); +} + +function testTriggerEvent() { + triggerEvent('.something', {}, 'click', {}).then(() => 'yay'); + triggerEvent('.something', 'mousedown').then(() => 'no'); + triggerEvent('.something', {}, 'fetch').then(() => 'huzzah'); + triggerEvent('.something', 'keydown').then(() => 'whomp whomp'); +} + +function testVisit() { + visit('some/url').then(() => {}) +} + +function testWait() { + const waited = wait('whatever'); + waited.then((s: string) => s.length); +} diff --git a/types/ember-testing-helpers/index.d.ts b/types/ember-testing-helpers/index.d.ts new file mode 100644 index 0000000000..c61eff40e8 --- /dev/null +++ b/types/ember-testing-helpers/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for ember-testing/lib/helpers +// Project: Ember.js Testing Helpers: https://github.com/emberjs/ember.js/tree/master/packages/ember-testing/lib/helpers +// Definitions by: Chris Krycho +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript version: 2.3 +// +// Note that these are distributed separately because they represent a discrete +// set of functionality, and as globally-injected items (as of Ember 2.13), are +// not easily or straightforwardly exported from the Ember type definitions. + +/// +/// + +type KeyEventType = 'keydown' | 'keyup' | 'keypress'; +type VoidWaitResult = RSVP.Promise; + +declare global { + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/and_then.js + function andThen(callback: (...args: any[]) => T): RSVP.Promise; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/click.js + function click(selector: string, context?: Object): VoidWaitResult; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_path.js + function currentPath(): string; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_route_name.js + function currentRouteName(): string; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_url.js + function currentURL(): string; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/fill_in.js + function fillIn(selector: string, context: Object, text: string): VoidWaitResult; + function fillIn(selector: string, text: string): VoidWaitResult; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find.js + function find(selector: string, context?: Object): JQuery; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find_with_assert.js + function findWithAssert(selector: string, context?: Object): JQuery; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/key_event.js + function keyEvent(selector: string, type: KeyEventType, keyCode: number): VoidWaitResult; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/pause_test.js + function pauseTest(): RSVP.Promise<{}>; + function resumeTest(): void; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/trigger_event.js + function triggerEvent(selector: string, context: Object, type: string, options: Object): VoidWaitResult; + function triggerEvent(selector: string, context: Object, type: string): VoidWaitResult; + function triggerEvent(selector: string, type: string, options: Object): VoidWaitResult; + function triggerEvent(selector: string, type: string): VoidWaitResult; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/visit.js + function visit(route: string): VoidWaitResult; + + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/wait.js + function wait(value: T): RSVP.Promise; +} + +export {}; diff --git a/types/ember-testing-helpers/tsconfig.json b/types/ember-testing-helpers/tsconfig.json new file mode 100644 index 0000000000..e4aa9692bf --- /dev/null +++ b/types/ember-testing-helpers/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-testing-helpers-tests.ts" + ] +} From 729a3d6985090700675ed46549496d4b5c749d4a Mon Sep 17 00:00:00 2001 From: "Diogo Franco (Kovensky)" Date: Tue, 4 Jul 2017 11:48:48 +0900 Subject: [PATCH 0140/1618] Also add template arguments to Handlebars.compile and Handlebars.template --- types/handlebars/handlebars-tests.ts | 4 ++-- types/handlebars/index.d.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/handlebars/handlebars-tests.ts b/types/handlebars/handlebars-tests.ts index f5105c2122..95342c2e63 100644 --- a/types/handlebars/handlebars-tests.ts +++ b/types/handlebars/handlebars-tests.ts @@ -45,14 +45,14 @@ Handlebars.registerHelper('link_to', (title: string, context: typeof post) => { var context3 = { posts: [{url: '/hello-world', body: 'Hello World!'}] }; var source3 = '
    {{#posts}}
  • {{{link_to "Post" this}}}
  • {{/posts}}
'; -var template3 = Handlebars.compile(source3); +var template3 = Handlebars.compile(source3); template3(context3); var source4 = '
    {{#people}}
  • {{#link}}{{name}}{{/link}}
  • {{/people}}
'; Handlebars.registerHelper('link', function(context: any) { return '' + context.fn(this) + ''; }); -var template4 = Handlebars.compile(source4); +var template4 = Handlebars.compile<{ people: { name: string, id: number }[] }>(source4); var data2 = { 'people': [ { 'name': 'Alan', 'id': 1 }, { 'name': 'Yehuda', 'id': 2 } diff --git a/types/handlebars/index.d.ts b/types/handlebars/index.d.ts index 17014d464a..56c341aa47 100644 --- a/types/handlebars/index.d.ts +++ b/types/handlebars/index.d.ts @@ -19,9 +19,9 @@ declare namespace Handlebars { export function Exception(message: string): void; export function log(level: number, obj: any): void; export function parse(input: string): hbs.AST.Program; - export function compile(input: any, options?: CompileOptions): HandlebarsTemplateDelegate; + export function compile(input: any, options?: CompileOptions): HandlebarsTemplateDelegate; export function precompile(input: any, options?: PrecompileOptions): TemplateSpecification; - export function template(precompilation: TemplateSpecification): HandlebarsTemplateDelegate; + export function template(precompilation: TemplateSpecification): HandlebarsTemplateDelegate; export function create(): typeof Handlebars; From eefba54205ec13b74a6f2f0b8d67a4e218a37c1e Mon Sep 17 00:00:00 2001 From: strajuser Date: Mon, 3 Jul 2017 10:12:12 +0300 Subject: [PATCH 0141/1618] - added esri-leaflet definitions base - definitions for BasemapLayer and TiledMapLayer --- types/esri-leaflet/esri-leaflet-tests.ts | 48 ++++++++ types/esri-leaflet/index.d.ts | 141 +++++++++++++++++++++++ types/esri-leaflet/tsconfig.json | 22 ++++ types/esri-leaflet/tslint.json | 1 + 4 files changed, 212 insertions(+) create mode 100644 types/esri-leaflet/esri-leaflet-tests.ts create mode 100644 types/esri-leaflet/index.d.ts create mode 100644 types/esri-leaflet/tsconfig.json create mode 100644 types/esri-leaflet/tslint.json diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts new file mode 100644 index 0000000000..cd3b6cbcf9 --- /dev/null +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -0,0 +1,48 @@ +import L = require('esri-leaflet'); + +let basemapLayer: L.esri.BasemapLayer; +basemapLayer = L.esri.basemapLayer('Streets'); +basemapLayer = L.esri.basemapLayer('Topographic'); +basemapLayer = L.esri.basemapLayer('NationalGeographic'); +basemapLayer = L.esri.basemapLayer('Oceans'); +basemapLayer = L.esri.basemapLayer('Gray'); +basemapLayer = L.esri.basemapLayer('DarkGray'); +basemapLayer = L.esri.basemapLayer('Imagery'); +basemapLayer = L.esri.basemapLayer('ShadedRelief'); +basemapLayer = L.esri.basemapLayer('Terrain'); +basemapLayer = L.esri.basemapLayer('USATopo'); +basemapLayer = L.esri.basemapLayer('OceansLabels'); +basemapLayer = L.esri.basemapLayer('GrayLabels'); +basemapLayer = L.esri.basemapLayer('DarkGrayLabels'); +basemapLayer = L.esri.basemapLayer('ImageryLabels'); +basemapLayer = L.esri.basemapLayer('ImageryTransportation'); +basemapLayer = L.esri.basemapLayer('ShadedReliefLabels'); +basemapLayer = L.esri.basemapLayer('TerrainLabels'); + +// should be an error +// basemapLayer = L.esri.basemapLayer('Test'); + +basemapLayer = new L.esri.BasemapLayer('Streets'); +basemapLayer = new L.esri.BasemapLayer('Topographic'); +basemapLayer = new L.esri.BasemapLayer('NationalGeographic'); +basemapLayer = new L.esri.BasemapLayer('Oceans'); +basemapLayer = new L.esri.BasemapLayer('Gray'); +basemapLayer = new L.esri.BasemapLayer('DarkGray'); +basemapLayer = new L.esri.BasemapLayer('Imagery'); +basemapLayer = new L.esri.BasemapLayer('ShadedRelief'); +basemapLayer = new L.esri.BasemapLayer('Terrain'); +basemapLayer = new L.esri.BasemapLayer('USATopo'); +basemapLayer = new L.esri.BasemapLayer('OceansLabels'); +basemapLayer = new L.esri.BasemapLayer('GrayLabels'); +basemapLayer = new L.esri.BasemapLayer('DarkGrayLabels'); +basemapLayer = new L.esri.BasemapLayer('ImageryLabels'); +basemapLayer = new L.esri.BasemapLayer('ImageryTransportation'); +basemapLayer = new L.esri.BasemapLayer('ShadedReliefLabels'); +basemapLayer = new L.esri.BasemapLayer('TerrainLabels'); + +// should be an error +// basemapLayer = new L.esri.BasemapLayer('Test'); + +basemapLayer = L.esri.basemapLayer('Streets', { token: 'token' }); +basemapLayer = new L.esri.BasemapLayer('Streets', { token: 'token' }); + diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts new file mode 100644 index 0000000000..fae5e0c8c6 --- /dev/null +++ b/types/esri-leaflet/index.d.ts @@ -0,0 +1,141 @@ +// Type definitions for esri-leaflet 2.0 +// Project: http://esri.github.io/esri-leaflet +// Definitions by: strajuser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + namespace esri { + type CallbackHandlerFn = (error: any, metadata: any) => void; + + type Basemaps = + 'Streets' + | 'Topographic' + | 'NationalGeographic' + | 'Oceans' + | 'Gray' + | 'DarkGray' + | 'Imagery' + | 'ShadedRelief' + | 'Terrain' + | 'USATopo' + | 'OceansLabels' + | 'GrayLabels' + | 'DarkGrayLabels' + | 'ImageryLabels' + | 'ImageryTransportation' + | 'ShadedReliefLabels' + | 'TerrainLabels'; + + interface BasemapLayerOptions extends L.TileLayerOptions { + /** + * Will use this token to authenticate all calls to the service. + * + * @type {string} + * @memberof BasemapLayerOptions + */ + token?: string; + } + + /** + * L.esri.BasemapLayer is used to display Esri hosted basemaps and attributes data providers appropriately. The Terms of Use for Esri hosted services apply to all Leaflet applications. + * + * @class BasemapLayer + * @extends {L.TileLayer} + */ + class BasemapLayer extends L.TileLayer { + constructor(key: Basemaps, options?: BasemapLayerOptions); + } + + /** + * L.esri.basemapLayer is used to display Esri hosted basemaps and attributes data providers appropriately. The Terms of Use for Esri hosted services apply to all Leaflet applications. + * + * @param {Basemaps} key + * @param {BasemapLayerOptions} [options] + * @returns {BasemapLayer} + */ + function basemapLayer(key: Basemaps, options?: BasemapLayerOptions): BasemapLayer; + + interface EsriTileLayerOptions extends L.TileLayerOptions { + /** + * URL of the Map Service with a tile cache. + * + * @type {string} + * @memberof EsriTileLayerOptions + */ + url: string; + /** + * If correctZoomLevels is enabled this controls the amount of tolerance for the difference at each scale level for remapping tile levels. + * Default 0.1 + * + * @type {number} + * @memberof EsriTileLayerOptions + */ + zoomOffsetAllowance?: number; + /** + * URL of an ArcGIS API for JavaScript proxy or ArcGIS Resource Proxy to use for proxying requests. + * + * @type {string} + * @memberof EsriTileLayerOptions + */ + proxy?: string; + /** + * Dictates if the service should use CORS when making GET requests. + * + * @type {boolean} + * @memberof EsriTileLayerOptions + */ + userCors?: boolean; + /** + * Will use this token to authenticate all calls to the service. + * + * @type {string} + * @memberof EsriTileLayerOptions + */ + token?: string; + } + + /** + * Access tiles from ArcGIS Online and ArcGIS Server to visualize and identify features. Copyright text from the service is added to map attribution automatically. + * + * @class TiledMapLayer + * @extends {L.TileLayer} + */ + class TiledMapLayer extends L.TileLayer { + constructor(options: EsriTileLayerOptions); + /** + * Authenticates this service with a new token and runs any pending requests that required a token. + * + * @param {string} token + * @returns {this} + * @memberof TiledMapLayer + */ + authenticate(token: string): this; + /** + * Requests metadata about this Feature Layer. Callback will be called with error and metadata. + * + * @param {CallbackHandlerFn} callback + * @param {*} context + * @returns {this} + * @memberof TiledMapLayer + */ + metadata(callback: CallbackHandlerFn, context: any): this; + identify() : any; + find(): any; + query(): any; + } + + /** + * Access tiles from ArcGIS Online and ArcGIS Server to visualize and identify features. Copyright text from the service is added to map attribution automatically. + * + * @param {EsriTileLayerOptions} options + * @returns {TiledMapLayer} + */ + function tiledMapLayer(options: EsriTileLayerOptions): TiledMapLayer; + } +} + +declare module 'esri-leaflet' { + export = L; +} diff --git a/types/esri-leaflet/tsconfig.json b/types/esri-leaflet/tsconfig.json new file mode 100644 index 0000000000..f342a7b92c --- /dev/null +++ b/types/esri-leaflet/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "esri-leaflet-tests.ts" + ] +} diff --git a/types/esri-leaflet/tslint.json b/types/esri-leaflet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/esri-leaflet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 989d9065591c5c3572a0348f3d6647764eca2457 Mon Sep 17 00:00:00 2001 From: strajuser Date: Mon, 3 Jul 2017 10:26:42 +0300 Subject: [PATCH 0142/1618] - TiledMapLayerOptions insead of EsriTileLayerOptions - tests for TiledMapLayerOptions and TiledMapLayer --- types/esri-leaflet/esri-leaflet-tests.ts | 55 ++++++++++++++++++++++++ types/esri-leaflet/index.d.ts | 20 ++++----- 2 files changed, 65 insertions(+), 10 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index cd3b6cbcf9..2992b18349 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -46,3 +46,58 @@ basemapLayer = new L.esri.BasemapLayer('TerrainLabels'); basemapLayer = L.esri.basemapLayer('Streets', { token: 'token' }); basemapLayer = new L.esri.BasemapLayer('Streets', { token: 'token' }); +let tiledMapLayer: L.esri.TiledMapLayer; + +let tiledMapLayerOptions: L.esri.TiledMapLayerOptions; +tiledMapLayerOptions = { + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', +}; +tiledMapLayerOptions = { + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15 +}; +tiledMapLayerOptions = { + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15, + zoomOffsetAllowance: 0.5 +}; +tiledMapLayerOptions = { + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15, + zoomOffsetAllowance: 0.5, + proxy: '//localhost/proxy' +}; +tiledMapLayerOptions = { + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15, + zoomOffsetAllowance: 0.5, + proxy: '//localhost/proxy', + useCors: true +}; +tiledMapLayerOptions = { + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15, + zoomOffsetAllowance: 0.5, + proxy: '//localhost/proxy', + useCors: true, + token: 'token' +}; + +tiledMapLayer = L.esri.tiledMapLayer(tiledMapLayerOptions); +tiledMapLayer = L.esri.tiledMapLayer({ + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15 +}); + +tiledMapLayer = new L.esri.TiledMapLayer(tiledMapLayerOptions); +tiledMapLayer = new L.esri.TiledMapLayer({ + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15 +}); + +tiledMapLayer.authenticate('secret'); +tiledMapLayer.metadata((err, metadata) => {}); + +tiledMapLayer.identify(); +tiledMapLayer.find(); +tiledMapLayer.query(); \ No newline at end of file diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index fae5e0c8c6..ba23d247e9 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -57,12 +57,12 @@ declare namespace L { */ function basemapLayer(key: Basemaps, options?: BasemapLayerOptions): BasemapLayer; - interface EsriTileLayerOptions extends L.TileLayerOptions { + interface TiledMapLayerOptions extends L.TileLayerOptions { /** * URL of the Map Service with a tile cache. * * @type {string} - * @memberof EsriTileLayerOptions + * @memberof TiledMapLayerOptions */ url: string; /** @@ -70,28 +70,28 @@ declare namespace L { * Default 0.1 * * @type {number} - * @memberof EsriTileLayerOptions + * @memberof TiledMapLayerOptions */ zoomOffsetAllowance?: number; /** * URL of an ArcGIS API for JavaScript proxy or ArcGIS Resource Proxy to use for proxying requests. * * @type {string} - * @memberof EsriTileLayerOptions + * @memberof TiledMapLayerOptions */ proxy?: string; /** * Dictates if the service should use CORS when making GET requests. * * @type {boolean} - * @memberof EsriTileLayerOptions + * @memberof TiledMapLayerOptions */ userCors?: boolean; /** * Will use this token to authenticate all calls to the service. * * @type {string} - * @memberof EsriTileLayerOptions + * @memberof TiledMapLayerOptions */ token?: string; } @@ -103,7 +103,7 @@ declare namespace L { * @extends {L.TileLayer} */ class TiledMapLayer extends L.TileLayer { - constructor(options: EsriTileLayerOptions); + constructor(options: TiledMapLayerOptions); /** * Authenticates this service with a new token and runs any pending requests that required a token. * @@ -120,7 +120,7 @@ declare namespace L { * @returns {this} * @memberof TiledMapLayer */ - metadata(callback: CallbackHandlerFn, context: any): this; + metadata(callback: CallbackHandlerFn, context?: any): this; identify() : any; find(): any; query(): any; @@ -129,10 +129,10 @@ declare namespace L { /** * Access tiles from ArcGIS Online and ArcGIS Server to visualize and identify features. Copyright text from the service is added to map attribution automatically. * - * @param {EsriTileLayerOptions} options + * @param {TiledMapLayerOptions} options * @returns {TiledMapLayer} */ - function tiledMapLayer(options: EsriTileLayerOptions): TiledMapLayer; + function tiledMapLayer(options: TiledMapLayerOptions): TiledMapLayer; } } From 7692a16977f390ce98d5047620270971244a056b Mon Sep 17 00:00:00 2001 From: strajuser Date: Tue, 4 Jul 2017 10:35:54 +0300 Subject: [PATCH 0143/1618] - added definitions for RasterLayer and DynamicMapLayer --- types/esri-leaflet/esri-leaflet-tests.ts | 179 ++++++++++-- types/esri-leaflet/index.d.ts | 344 +++++++++++++++++++++++ 2 files changed, 498 insertions(+), 25 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index 2992b18349..fc51c42b64 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -1,5 +1,8 @@ import L = require('esri-leaflet'); +let latlng : L.LatLng = new L.LatLng(0, 0);; +let latlngbounds : L.LatLngBounds = new L.LatLngBounds(latlng, latlng); + let basemapLayer: L.esri.BasemapLayer; basemapLayer = L.esri.basemapLayer('Streets'); basemapLayer = L.esri.basemapLayer('Topographic'); @@ -52,28 +55,6 @@ let tiledMapLayerOptions: L.esri.TiledMapLayerOptions; tiledMapLayerOptions = { url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', }; -tiledMapLayerOptions = { - url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', - maxZoom: 15 -}; -tiledMapLayerOptions = { - url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', - maxZoom: 15, - zoomOffsetAllowance: 0.5 -}; -tiledMapLayerOptions = { - url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', - maxZoom: 15, - zoomOffsetAllowance: 0.5, - proxy: '//localhost/proxy' -}; -tiledMapLayerOptions = { - url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', - maxZoom: 15, - zoomOffsetAllowance: 0.5, - proxy: '//localhost/proxy', - useCors: true -}; tiledMapLayerOptions = { url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', maxZoom: 15, @@ -86,18 +67,166 @@ tiledMapLayerOptions = { tiledMapLayer = L.esri.tiledMapLayer(tiledMapLayerOptions); tiledMapLayer = L.esri.tiledMapLayer({ url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', - maxZoom: 15 +}); +tiledMapLayer = L.esri.tiledMapLayer({ + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15, + zoomOffsetAllowance: 0.5, + proxy: '//localhost/proxy', + useCors: true, + token: 'token' }); tiledMapLayer = new L.esri.TiledMapLayer(tiledMapLayerOptions); tiledMapLayer = new L.esri.TiledMapLayer({ url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', - maxZoom: 15 +}); +tiledMapLayer = new L.esri.TiledMapLayer({ + url: 'https://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer', + maxZoom: 15, + zoomOffsetAllowance: 0.5, + proxy: '//localhost/proxy', + useCors: true, + token: 'token' }); tiledMapLayer.authenticate('secret'); tiledMapLayer.metadata((err, metadata) => {}); +// TODO: tiledMapLayer.identify(); tiledMapLayer.find(); -tiledMapLayer.query(); \ No newline at end of file +tiledMapLayer.query(); + +let dynamicMapLayer: L.esri.DynamicMapLayer; +let dynamicMapLayerOptions: L.esri.DynamicMapLayerOptions; + +dynamicMapLayerOptions = { + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', +}; +dynamicMapLayerOptions = { + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + opacity: 0.5, + format: 'jpg', + transparent: false, + f: 'html', + attribution: 'MIT', + layers: [1,2,3], + layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, + position: 'front', + maxZoom: 1, + minZoom: 1, + dynamicLayers: [{ + "id": 501, + "source": { + "type": "mapLayer", + "mapLayerId": 0 + }, + "drawingInfo": { + "showLabels": false + }, + "layerTimeOptions": { + "useTime": false + } + }], + proxy: '//localhost/proxy', + useCors: true, + token: 'token' +}; + +dynamicMapLayer = L.esri.dynamicMapLayer(dynamicMapLayerOptions); +dynamicMapLayer = L.esri.dynamicMapLayer({ + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', +}); +dynamicMapLayer = L.esri.dynamicMapLayer({ + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + opacity: 0.5, + format: 'jpg', + transparent: false, + f: 'html', + attribution: 'MIT', + layers: [1,2,3], + layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, + position: 'front', + maxZoom: 1, + minZoom: 1, + dynamicLayers: [{ + "id": 501, + "source": { + "type": "mapLayer", + "mapLayerId": 0 + }, + "drawingInfo": { + "showLabels": false + }, + "layerTimeOptions": { + "useTime": false + } + }], + proxy: '//localhost/proxy', + useCors: true, + token: 'token' +}); + +dynamicMapLayer = new L.esri.DynamicMapLayer(dynamicMapLayerOptions); +dynamicMapLayer = new L.esri.DynamicMapLayer({ + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', +}); +dynamicMapLayer = new L.esri.DynamicMapLayer({ + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + opacity: 0.5, + format: 'jpg', + transparent: false, + f: 'html', + attribution: 'MIT', + layers: [1,2,3], + layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, + position: 'front', + maxZoom: 1, + minZoom: 1, + dynamicLayers: [{ + "id": 501, + "source": { + "type": "mapLayer", + "mapLayerId": 0 + }, + "drawingInfo": { + "showLabels": false + }, + "layerTimeOptions": { + "useTime": false + } + }], + proxy: '//localhost/proxy', + useCors: true, + token: 'token' +}); + +dynamicMapLayer.bindPopup( + function(err, featureCollection, response){ + var count = featureCollection.features.length; + return (count) ? count + ' features' : false; +}); + +dynamicMapLayer.metadata(function(error, metadata){ + // console.log(metadata); +}); + +// TODO: +// dynamicMapLayer.identify() +// .at(latlng) +// .run(function(error, featureCollection){ +// // console.log(featureCollection); +// }); +// dynamicMapLayer.find() +// .layers('18') +// .searchText('Colorado') +// .run(function(error, featureCollection){ +// // console.log(featureCollection); +// }); +// dynamicMapLayer.query() +// .layer(0) +// .within(latlngbounds) +// .run(function(error, featureCollection, response){ +// // console.log(featureCollection); +// }); \ No newline at end of file diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index ba23d247e9..6ce4d4f6b6 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -28,6 +28,12 @@ declare namespace L { | 'ShadedReliefLabels' | 'TerrainLabels'; + /** + * Options for L.esri.BasemapLayer + * + * @interface BasemapLayerOptions + * @extends {L.TileLayerOptions} + */ interface BasemapLayerOptions extends L.TileLayerOptions { /** * Will use this token to authenticate all calls to the service. @@ -57,6 +63,12 @@ declare namespace L { */ function basemapLayer(key: Basemaps, options?: BasemapLayerOptions): BasemapLayer; + /** + * Options for L.esri.TiledMapLayer + * + * @interface TiledMapLayerOptions + * @extends {L.TileLayerOptions} + */ interface TiledMapLayerOptions extends L.TileLayerOptions { /** * URL of the Map Service with a tile cache. @@ -133,6 +145,338 @@ declare namespace L { * @returns {TiledMapLayer} */ function tiledMapLayer(options: TiledMapLayerOptions): TiledMapLayer; + + /** + * Options for RasterLayer + * + * @interface RasterLayerOptions + * @extends {L.ImageOverlayOptions} + */ + interface RasterLayerOptions extends L.ImageOverlayOptions { + /** + * Server response content type. + * Default: 'image' + * + * @type {string} + * @memberof RasterLayerOptions + */ + f?: string; + /** + * Position of the layer relative to other overlays. + * Default: 'front' + * + * @type {string} + * @memberof RasterLayerOptions + */ + position?: string; + /** + * Closest zoom level the layer will be displayed on the map. + * + * @type {number} + * @memberof RasterLayerOptions + */ + maxZoom?: number; + /** + * Furthest zoom level the layer will be displayed on the map. + * + * @type {number} + * @memberof RasterLayerOptions + */ + minZoom?: number; + } + + /** + * A generic class representing an image layer. This class can be extended to provide support for making export requests from ArcGIS REST services. + * + * @class RasterLayer + * @extends {L.ImageOverlay} + */ + abstract class RasterLayer extends L.ImageOverlay { + /** + * Redraws this layer below all other overlay layers. + * + * @returns {this} + * @memberof RasterLayer + */ + bringToBack(): this; + /** + * Redraws this layer above all other overlay layers. + * + * @returns {this} + * @memberof RasterLayer + */ + bringToFront(): this; + /** + * Returns the current opacity of the layer. + * + * @returns {number} + * @memberof RasterLayer + */ + getOpacity(): number; + /** + * Sets the opacity of the layer. + * + * @param {number} opacity + * @returns {this} + * @memberof RasterLayer + */ + setOpacity(opacity: number): this; + /** + * Returns the current time range being used for rendering. Array [from, to]; + * + * @returns {Date[]} + * @memberof RasterLayer + */ + getTimeRange(): Date[]; + /** + * Redraws the layer with he passed time range. + * + * @param {Date} from + * @param {Date} to + * @returns {this} + * @memberof RasterLayer + */ + setTimeRange(from: Date, to: Date): this; + /** + * Used to make a fresh request to the service and draw the response. + * + * @returns {this} + * @memberof RasterLayer + */ + redraw(): this; + /** + * Authenticates this service with a new token and runs any pending requests that required a token. + * + * @param {string} token + * @returns {this} + * @memberof TiledMapLayer + */ + authenticate(token: string): this; + /** + * Requests metadata about this Feature Layer. Callback will be called with error and metadata. + * + * @param {CallbackHandlerFn} callback + * @param {*} context + * @returns {this} + * @memberof TiledMapLayer + */ + metadata(callback: CallbackHandlerFn, context?: any): this; + } + + /** + * Options for L.esri.DynamicMapLayer + * + * @interface DynamicMapLayerOptions + * @extends {RasterLayerOptions} + */ + interface DynamicMapLayerOptions extends RasterLayerOptions { + /** + * URL of the Map Service. + * + * @type {string} + * @memberof TiledMapLayerOptions + */ + url: string; + /** + * Output format of the image. + * Default: 'png24' + * + * @type {string} + * @memberof DynamicMapLayerOptions + */ + format?: string; + /** + * Allow the server to produce transparent images. + * + * @type {boolean} + * @memberof DynamicMapLayerOptions + */ + transparent?: boolean; + /** + * Attribution from service metadata copyright text is automatically displayed in Leaflet's default control. This property can be used for customization. + * + * @type {string} + * @memberof DynamicMapLayerOptions + */ + attribution?: string; + /* + * An array of Layer IDs like [3,4,5] to show from the service. + * + * @type {any[]} + * @memberof DynamicMapLayerOptions + */ + layers?: any[]; + /** + * SQL filters to define what features will be included in the image rendered by the service. An object is used with keys that map each query to its respective layer. + * { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" } + * + * @type {*} + * @memberof DynamicMapLayerOptions + */ + layerDefs?: any; + /** + * JSON object literal used to manipulate the layer symbology defined in the service itself. Requires a 10.1 (or above) map service which supports dynamicLayers requests. + * + * @type {*} + * @memberof DynamicMapLayerOptions + */ + dynamicLayers?: any; + /** + * URL of an ArcGIS API for JavaScript proxy or ArcGIS Resource Proxy to use for proxying requests. + * + * @type {string} + * @memberof TiledMapLayerOptions + */ + proxy?: string; + /** + * Dictates if the service should use CORS when making GET requests. + * + * @type {boolean} + * @memberof TiledMapLayerOptions + */ + useCors?: boolean; + /** + * Will use this token to authenticate all calls to the service. + * + * @type {string} + * @memberof TiledMapLayerOptions + */ + token?: string; + } + + type FeatureRequestCallbackFn = (err: any, featureCollection: any, response: any) => void; + + /** + * Render and visualize Map Services from ArcGIS Online and ArcGIS Server. L.esri.DynamicMapLayer also supports custom popups and identification of features. + * Map Services are used when its preferable to ask the server to draw layers at a particular location and scale and pass back the image which was generated on the fly. They also expose capabilities for querying and identifying individual features. + * + * @class DynamicMapLayer + * @extends {RasterLayer} + */ + class DynamicMapLayer extends RasterLayer { + constructor(options: DynamicMapLayerOptions); + /** + * Uses the provided function to create a popup that will identify features whenever the map is clicked. Your function will be passed a GeoJSON FeatureCollection of the features at the clicked location and should return the appropriate HTML. If you do not want to open the popup when there are no results, return false. + * + * @param {FeatureRequestCallbackFn} fn + * @param {L.PopupOptions} popupOptions + * @returns {this} + * @memberof DynamicMapLayer + */ + bindPopup(fn: FeatureRequestCallbackFn, popupOptions?: L.PopupOptions): this; + /** + * Removes a popup previously bound with bindPopup. + * + * @returns {this} + * @memberof DynamicMapLayer + */ + unbindPopup(): this; + /** + * Returns the current opacity of the layer. + * + * @returns {number} + * @memberof DynamicMapLayer + */ + getOpacity(): number; + /** + * Sets the opacity of the layer. + * + * @param {number} opacity + * @returns {this} + * @memberof DynamicMapLayer + */ + setOpacity(opacity: number): this; + /** + * Returns the array of visible layers specified in the layer constructor. + * + * @returns {Array} + * @memberof DynamicMapLayer + */ + getLayers(): Array; + /** + * Redraws the layer to show the passed array of layer ids. + * + * @param {Array} layers + * @returns {this} + * @memberof DynamicMapLayer + */ + setLayers(layers: Array): this; + /** + * Returns the current layer definition(s) being used for rendering. + * + * @returns {*} + * @memberof DynamicMapLayer + */ + getLayerDefs(): any; + /** + * Redraws the layer with the new layer definitions. Corresponds to the layerDefs option on the export API. + * + * @param {*} layerDefs + * @returns {this} + * @memberof DynamicMapLayer + */ + setLayerDefs(layerDefs: any): this; + /** + * Returns the current time options being used for rendering. + * + * @returns {*} + * @memberof DynamicMapLayer + */ + getTimeOptions(): any + /** + * Sets the current time options being used to render the layer. Corresponds to the layerTimeOptions option on the export API. + * + * @param {*} timeOptions + * @returns {this} + * @memberof DynamicMapLayer + */ + setTimeOptions(timeOptions: any): this; + /** + * Returns a JSON object representing the modified layer symbology being requested from the map service. + * + * @returns {*} + * @memberof DynamicMapLayer + */ + getDynamicLayers(): any; + /** + * Used to insert raw dynamicLayers JSON in situations where you'd like to modify layer symbology defined in the service itself. + * + * @param {*} layers + * @returns {this} + * @memberof DynamicMapLayer + */ + setDynamicLayers(layers: any): this; + /** + * Returns a new L.esri.services.IdentifyFeatures object that can be used to identify features on this layer. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof DynamicMapLayer + */ + identify(): any; + /** + * Returns a new L.esri.services.Find object that can be used to find features. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof DynamicMapLayer + */ + find(): any; + /** + * Returns a new L.esri.Query object that can be used to query this service. + * + * @returns {*} + * @memberof DynamicMapLayer + */ + query(): any; + } + + /** + * Render and visualize Map Services from ArcGIS Online and ArcGIS Server. L.esri.DynamicMapLayer also supports custom popups and identification of features. + * Map Services are used when its preferable to ask the server to draw layers at a particular location and scale and pass back the image which was generated on the fly. They also expose capabilities for querying and identifying individual features. + * + * @param {DynamicMapLayerOptions} options + * @returns {DynamicMapLayer} + */ + function dynamicMapLayer(options: DynamicMapLayerOptions): DynamicMapLayer; } } From 890f0b9101801358f05b5fd1c852eb2586c90b31 Mon Sep 17 00:00:00 2001 From: strajuser Date: Tue, 4 Jul 2017 10:45:42 +0300 Subject: [PATCH 0144/1618] - LayerOptions refactoring --- types/esri-leaflet/index.d.ts | 99 +++++++++++++++-------------------- 1 file changed, 41 insertions(+), 58 deletions(-) diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index 6ce4d4f6b6..84841f36d3 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -9,6 +9,37 @@ declare namespace L { namespace esri { type CallbackHandlerFn = (error: any, metadata: any) => void; + interface LayerOptionsBase { + /** + * URL of the Map Service + * + * @type {string} + * @memberof LayerOptionsBase + */ + url: string; + /** + * URL of an ArcGIS API for JavaScript proxy or ArcGIS Resource Proxy to use for proxying requests. + * + * @type {string} + * @memberof LayerOptionsBase + */ + proxy?: string; + /** + * Dictates if the service should use CORS when making GET requests. + * + * @type {boolean} + * @memberof LayerOptionsBase + */ + useCors?: boolean; + /** + * Will use this token to authenticate all calls to the service. + * + * @type {string} + * @memberof LayerOptionsBase + */ + token?: string; + } + type Basemaps = 'Streets' | 'Topographic' @@ -69,14 +100,7 @@ declare namespace L { * @interface TiledMapLayerOptions * @extends {L.TileLayerOptions} */ - interface TiledMapLayerOptions extends L.TileLayerOptions { - /** - * URL of the Map Service with a tile cache. - * - * @type {string} - * @memberof TiledMapLayerOptions - */ - url: string; + interface TiledMapLayerOptions extends L.TileLayerOptions, LayerOptionsBase { /** * If correctZoomLevels is enabled this controls the amount of tolerance for the difference at each scale level for remapping tile levels. * Default 0.1 @@ -85,27 +109,6 @@ declare namespace L { * @memberof TiledMapLayerOptions */ zoomOffsetAllowance?: number; - /** - * URL of an ArcGIS API for JavaScript proxy or ArcGIS Resource Proxy to use for proxying requests. - * - * @type {string} - * @memberof TiledMapLayerOptions - */ - proxy?: string; - /** - * Dictates if the service should use CORS when making GET requests. - * - * @type {boolean} - * @memberof TiledMapLayerOptions - */ - userCors?: boolean; - /** - * Will use this token to authenticate all calls to the service. - * - * @type {string} - * @memberof TiledMapLayerOptions - */ - token?: string; } /** @@ -269,14 +272,7 @@ declare namespace L { * @interface DynamicMapLayerOptions * @extends {RasterLayerOptions} */ - interface DynamicMapLayerOptions extends RasterLayerOptions { - /** - * URL of the Map Service. - * - * @type {string} - * @memberof TiledMapLayerOptions - */ - url: string; + interface DynamicMapLayerOptions extends RasterLayerOptions, LayerOptionsBase { /** * Output format of the image. * Default: 'png24' @@ -321,27 +317,6 @@ declare namespace L { * @memberof DynamicMapLayerOptions */ dynamicLayers?: any; - /** - * URL of an ArcGIS API for JavaScript proxy or ArcGIS Resource Proxy to use for proxying requests. - * - * @type {string} - * @memberof TiledMapLayerOptions - */ - proxy?: string; - /** - * Dictates if the service should use CORS when making GET requests. - * - * @type {boolean} - * @memberof TiledMapLayerOptions - */ - useCors?: boolean; - /** - * Will use this token to authenticate all calls to the service. - * - * @type {string} - * @memberof TiledMapLayerOptions - */ - token?: string; } type FeatureRequestCallbackFn = (err: any, featureCollection: any, response: any) => void; @@ -480,6 +455,14 @@ declare namespace L { } } +declare namespace L { + namespace esri { + namespace services { + + } + } +} + declare module 'esri-leaflet' { export = L; } From db1d7658e37d79da70208c29787b432e58a0863f Mon Sep 17 00:00:00 2001 From: strajuser Date: Tue, 4 Jul 2017 11:17:32 +0300 Subject: [PATCH 0145/1618] - definitions for Service and MapService --- types/esri-leaflet/esri-leaflet-tests.ts | 255 ++++++++++++++--------- types/esri-leaflet/index.d.ts | 131 +++++++++++- 2 files changed, 290 insertions(+), 96 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index fc51c42b64..25d7230593 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -1,7 +1,8 @@ import L = require('esri-leaflet'); -let latlng : L.LatLng = new L.LatLng(0, 0);; -let latlngbounds : L.LatLngBounds = new L.LatLngBounds(latlng, latlng); +let latlng: L.LatLng = new L.LatLng(0, 0);; +let latlngbounds: L.LatLngBounds = new L.LatLngBounds(latlng, latlng); +let map: L.Map = new L.Map('map'); let basemapLayer: L.esri.BasemapLayer; basemapLayer = L.esri.basemapLayer('Streets'); @@ -91,7 +92,7 @@ tiledMapLayer = new L.esri.TiledMapLayer({ }); tiledMapLayer.authenticate('secret'); -tiledMapLayer.metadata((err, metadata) => {}); +tiledMapLayer.metadata((err, metadata) => { }); // TODO: tiledMapLayer.identify(); @@ -102,114 +103,114 @@ let dynamicMapLayer: L.esri.DynamicMapLayer; let dynamicMapLayerOptions: L.esri.DynamicMapLayerOptions; dynamicMapLayerOptions = { - url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', }; dynamicMapLayerOptions = { - url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', - opacity: 0.5, - format: 'jpg', - transparent: false, - f: 'html', - attribution: 'MIT', - layers: [1,2,3], - layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, - position: 'front', - maxZoom: 1, - minZoom: 1, - dynamicLayers: [{ - "id": 501, - "source": { - "type": "mapLayer", - "mapLayerId": 0 - }, - "drawingInfo": { - "showLabels": false - }, - "layerTimeOptions": { - "useTime": false - } - }], - proxy: '//localhost/proxy', - useCors: true, - token: 'token' + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + opacity: 0.5, + format: 'jpg', + transparent: false, + f: 'html', + attribution: 'MIT', + layers: [1, 2, 3], + layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, + position: 'front', + maxZoom: 1, + minZoom: 1, + dynamicLayers: [{ + "id": 501, + "source": { + "type": "mapLayer", + "mapLayerId": 0 + }, + "drawingInfo": { + "showLabels": false + }, + "layerTimeOptions": { + "useTime": false + } + }], + proxy: '//localhost/proxy', + useCors: true, + token: 'token' }; dynamicMapLayer = L.esri.dynamicMapLayer(dynamicMapLayerOptions); dynamicMapLayer = L.esri.dynamicMapLayer({ - url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', }); dynamicMapLayer = L.esri.dynamicMapLayer({ - url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', - opacity: 0.5, - format: 'jpg', - transparent: false, - f: 'html', - attribution: 'MIT', - layers: [1,2,3], - layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, - position: 'front', - maxZoom: 1, - minZoom: 1, - dynamicLayers: [{ - "id": 501, - "source": { - "type": "mapLayer", - "mapLayerId": 0 - }, - "drawingInfo": { - "showLabels": false - }, - "layerTimeOptions": { - "useTime": false - } - }], - proxy: '//localhost/proxy', - useCors: true, - token: 'token' + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + opacity: 0.5, + format: 'jpg', + transparent: false, + f: 'html', + attribution: 'MIT', + layers: [1, 2, 3], + layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, + position: 'front', + maxZoom: 1, + minZoom: 1, + dynamicLayers: [{ + "id": 501, + "source": { + "type": "mapLayer", + "mapLayerId": 0 + }, + "drawingInfo": { + "showLabels": false + }, + "layerTimeOptions": { + "useTime": false + } + }], + proxy: '//localhost/proxy', + useCors: true, + token: 'token' }); dynamicMapLayer = new L.esri.DynamicMapLayer(dynamicMapLayerOptions); dynamicMapLayer = new L.esri.DynamicMapLayer({ - url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', }); dynamicMapLayer = new L.esri.DynamicMapLayer({ - url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', - opacity: 0.5, - format: 'jpg', - transparent: false, - f: 'html', - attribution: 'MIT', - layers: [1,2,3], - layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, - position: 'front', - maxZoom: 1, - minZoom: 1, - dynamicLayers: [{ - "id": 501, - "source": { - "type": "mapLayer", - "mapLayerId": 0 - }, - "drawingInfo": { - "showLabels": false - }, - "layerTimeOptions": { - "useTime": false - } - }], - proxy: '//localhost/proxy', - useCors: true, - token: 'token' + url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer', + opacity: 0.5, + format: 'jpg', + transparent: false, + f: 'html', + attribution: 'MIT', + layers: [1, 2, 3], + layerDefs: { 3: "STATE_NAME='Kansas'", 9: "POP2007>25000" }, + position: 'front', + maxZoom: 1, + minZoom: 1, + dynamicLayers: [{ + "id": 501, + "source": { + "type": "mapLayer", + "mapLayerId": 0 + }, + "drawingInfo": { + "showLabels": false + }, + "layerTimeOptions": { + "useTime": false + } + }], + proxy: '//localhost/proxy', + useCors: true, + token: 'token' }); dynamicMapLayer.bindPopup( - function(err, featureCollection, response){ - var count = featureCollection.features.length; - return (count) ? count + ' features' : false; -}); + function (err, featureCollection, response) { + var count = featureCollection.features.length; + return (count) ? count + ' features' : false; + }); -dynamicMapLayer.metadata(function(error, metadata){ - // console.log(metadata); +dynamicMapLayer.metadata(function (error, metadata) { + // console.log(metadata); }); // TODO: @@ -229,4 +230,70 @@ dynamicMapLayer.metadata(function(error, metadata){ // .within(latlngbounds) // .run(function(error, featureCollection, response){ // // console.log(featureCollection); -// }); \ No newline at end of file +// }); + +let mapServiceOptions: L.esri.MapServiceOptions; +let mapService: L.esri.MapService; + +mapServiceOptions = { +}; +mapServiceOptions = { + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}; + +mapService = L.esri.mapService(mapServiceOptions); +mapService = L.esri.mapService({}); +mapService = L.esri.mapService({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +mapService = new L.esri.MapService(mapServiceOptions); +mapService = new L.esri.MapService({}); +mapService = new L.esri.MapService({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +// TODO: +// mapService.query() +// .layer(0) +// .within(latlngbounds) +// .run(function(error, featureCollection, response){ +// // console.log(featureCollection); +// }); +// mapService.identify() +// .on(map) +// .at(latlng) +// .run(function(error, featureCollection, response){ +// // console.log(featureCollection) +// }); +// mapService.find() +// .layers('18') +// .text('Colorado') +// .fields('name') +// .run(function(error, featureCollection, response){ +// // console.log(featureCollection) +// }); + +// mapService.identify() +// .on(map) +// .at([45.543, -122.621]) +// .layers('visible:1') +// .run(function(error, featureCollection, response){ +// // console.log("UTC Offset: " + featureCollection.features[0].properties.ZONE); +// }); +// mapService.find() +// .layers('18') +// .searchText('Colorado') +// .searchFields('GNIS_NAME') +// .run(function(error, featureCollection, response){ +// // console.log('Found GNIS ID: ' + featureCollection.features[0].properties.GNIS_ID + ' for the state of ' + featureCollection.features[0].properties.STATE_NAME); +// }); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index 84841f36d3..da670c605b 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -457,9 +457,136 @@ declare namespace L { declare namespace L { namespace esri { - namespace services { - + /** + * Options for L.esri.Service + * + * @interface ServiceOptions + */ + interface ServiceOptions { + /** + * URL of the ArcGIS service you would like to consume. + * + * @type {string} + * @memberof ServiceOptions + */ + url?: string; + /** + * URL of an ArcGIS API for JavaScript proxy or ArcGIS Resource Proxy to use for proxying POST requests. + * + * @type {string} + * @memberof ServiceOptions + */ + proxy?: string; + /** + * If this service should use CORS when making GET requests. + * + * @type {boolean} + * @memberof ServiceOptions + */ + useCors?: boolean; + /** + * Operation timeout + * + * @type {number} + * @memberof ServiceOptions + */ + timeout?: number; } + + /** + * A generic class representing a hosted resource on ArcGIS Online or ArcGIS Server. This class can be extended to provide support for making requests and serves as a standard for authentication and proxying. + * + * @class Service + * @extends {L.Evented} + */ + abstract class Service extends L.Evented { + /** + * Makes a GET request to the service. The service's URL will be combined with the path option and parameters will be serialized to a query string. Accepts an optional function context for the callback. + * + * @param {string} url + * @param {*} [params] + * @param {CallbackHandlerFn} [callback] + * @param {*} [context] + * @returns {this} + * @memberof Service + */ + get(url: string, params?: any, callback?: CallbackHandlerFn, context?: any): this; + /** + * Makes a POST request to the service. The service's URL will be combined with the path option and parameters will be serialized. Accepts an optional function context for the callback. + * + * @param {string} url + * @param {*} [params] + * @param {CallbackHandlerFn} [callback] + * @param {*} [context] + * @returns {this} + * @memberof Service + */ + post(url: string, params?: any, callback?: CallbackHandlerFn, context?: any): this; + /** + * Authenticates this service with a new token and runs any pending requests that required a token. + * + * @param {string} token + * @returns {this} + * @memberof TiledMapLayer + */ + authenticate(token: string): this; + /** + * Requests metadata about this Feature Layer. Callback will be called with error and metadata. + * + * @param {CallbackHandlerFn} callback + * @param {*} context + * @returns {this} + * @memberof TiledMapLayer + */ + metadata(callback: CallbackHandlerFn, context?: any): this; + } + + /** + * Options for MapService + * + * @interface MapServiceOptions + * @extends {ServiceOptions} + */ + interface MapServiceOptions extends ServiceOptions { } + + /** + * L.esri.MapService is an abstraction for interacting with Map Services running on ArcGIS Online and ArcGIS Server that allows you to make requests to the API, as well as query and identify published features. + * + * @class MapService + * @extends {Service} + */ + class MapService extends Service { + constructor(options: MapServiceOptions); + /** + * Returns a new L.esri.services.IdentifyFeatures object that can be used to identify features on this layer. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof MapService + */ + identify(): any; + /** + * Returns a new L.esri.services.Find object that can be used to find features. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof MapService + */ + find(): any; + /** + * Returns a new L.esri.Query object that can be used to query this service. + * + * @returns {*} + * @memberof MapService + */ + query(): any; + } + + /** + * L.esri.MapService is an abstraction for interacting with Map Services running on ArcGIS Online and ArcGIS Server that allows you to make requests to the API, as well as query and identify published features. + * + * @param {MapServiceOptions} options + * @returns {MapService} + */ + function mapService(options: MapServiceOptions): MapService; } } From e9eedf9c6ea3fc3346c7be37f10e23baf8e97d6c Mon Sep 17 00:00:00 2001 From: strajuser Date: Tue, 4 Jul 2017 13:35:44 +0300 Subject: [PATCH 0146/1618] - Incorrect bindPopup inheritance fix --- types/esri-leaflet/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index da670c605b..36fadf940d 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -333,12 +333,12 @@ declare namespace L { /** * Uses the provided function to create a popup that will identify features whenever the map is clicked. Your function will be passed a GeoJSON FeatureCollection of the features at the clicked location and should return the appropriate HTML. If you do not want to open the popup when there are no results, return false. * - * @param {FeatureRequestCallbackFn} fn + * @param {any} fn * @param {L.PopupOptions} popupOptions * @returns {this} * @memberof DynamicMapLayer */ - bindPopup(fn: FeatureRequestCallbackFn, popupOptions?: L.PopupOptions): this; + bindPopup(fn: any, popupOptions?: L.PopupOptions): this; /** * Removes a popup previously bound with bindPopup. * From 5c9a773db9d88c9adcec8dd577425807bb7b9ea8 Mon Sep 17 00:00:00 2001 From: Chris Krycho Date: Tue, 4 Jul 2017 08:13:26 -0400 Subject: [PATCH 0147/1618] Fix ember-testing-helpers tsconfig for CI. --- types/ember-testing-helpers/tsconfig.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/ember-testing-helpers/tsconfig.json b/types/ember-testing-helpers/tsconfig.json index e4aa9692bf..aaf474ecba 100644 --- a/types/ember-testing-helpers/tsconfig.json +++ b/types/ember-testing-helpers/tsconfig.json @@ -5,7 +5,9 @@ "es6", "dom" ], - "strict": true, + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From 257300c98d265858ff5520349bbaab2db40c70e3 Mon Sep 17 00:00:00 2001 From: Mariusz Wiktorczyk Date: Tue, 27 Jun 2017 14:20:55 +0200 Subject: [PATCH 0148/1618] Node.js v8.0.0 Stream --- types/node/index.d.ts | 10 ++++++++++ types/node/node-tests.ts | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index f9716e3e83..a573effeb0 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -9,6 +9,7 @@ // Nicolas Voigt // Chigozirim C. // Flarna +// Mariusz Wiktorczyk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -3744,6 +3745,7 @@ declare module "stream" { encoding?: string; objectMode?: boolean; read?: (this: Readable, size?: number) => any; + destroy?: (error?: Error) => any; } export class Readable extends Stream implements NodeJS.ReadableStream { @@ -3760,6 +3762,7 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): Readable; push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; /** * Event emitter @@ -3827,12 +3830,15 @@ declare module "stream" { objectMode?: boolean; write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + destroy?: (error?: Error) => any; } export class Writable extends Stream implements NodeJS.WritableStream { writable: boolean; constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error, callback: Function): void; + _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; setDefaultEncoding(encoding: string): this; @@ -3841,6 +3847,7 @@ declare module "stream" { end(chunk: any, encoding?: string, cb?: Function): void; cork(): void; uncork(): void; + destroy(error?: Error): void; /** * Event emitter @@ -3920,6 +3927,8 @@ declare module "stream" { writable: boolean; constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error, callback: Function): void; + _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; setDefaultEncoding(encoding: string): this; @@ -3938,6 +3947,7 @@ declare module "stream" { export class Transform extends Duplex { constructor(opts?: TransformOptions); _transform(chunk: any, encoding: string, callback: Function): void; + destroy(error?: Error): void; } export class PassThrough extends Transform { } diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 84625061a2..b24154c454 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -617,6 +617,9 @@ function simplified_stream_ctor_test() { new stream.Readable({ read: function(size) { size.toFixed(); + }, + destroy: function(error) { + error.stack; } }); @@ -630,6 +633,9 @@ function simplified_stream_ctor_test() { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); + }, + destroy: function(error) { + error.stack; } }); @@ -673,6 +679,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, + destroy: function(error) { + error.stack; + }, allowHalfOpen: true, readableObjectMode: true, writableObjectMode: true From 0d800bb63eda443ed517164ba50a1c906f3ca1a6 Mon Sep 17 00:00:00 2001 From: Mariusz Wiktorczyk Date: Thu, 29 Jun 2017 09:57:43 +0200 Subject: [PATCH 0149/1618] Fix destroy method definition in simple-peer --- types/simple-peer/index.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/simple-peer/index.d.ts b/types/simple-peer/index.d.ts index e03e5b3372..ed40ed2d5b 100644 --- a/types/simple-peer/index.d.ts +++ b/types/simple-peer/index.d.ts @@ -51,7 +51,11 @@ declare namespace SimplePeer { send(data: SimplePeerData): void; // https://github.com/feross/simple-peer/tree/v6.1.5#peersenddata - destroy(onclose?: () => void): void; + // TODO: https://github.com/feross/simple-peer/issues/187 + // destroy(onclose?: () => void): void; + // https://nodejs.org/api/stream.html#stream_writable_destroy_error + // https://nodejs.org/api/stream.html#stream_readable_destroy_error + destroy(error?: Error): void; // methods which are not documented readonly bufferSize: number; From 662c4e6185d95bc33b7c6dd803be91dba639e356 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Tue, 4 Jul 2017 19:26:04 +0300 Subject: [PATCH 0150/1618] Updated CloudflareAppsMethods. --- types/cloudflare-apps/cloudflare-apps-tests.ts | 11 +++++++++-- types/cloudflare-apps/index.d.ts | 12 +++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/types/cloudflare-apps/cloudflare-apps-tests.ts b/types/cloudflare-apps/cloudflare-apps-tests.ts index 35216331ee..a24570e857 100644 --- a/types/cloudflare-apps/cloudflare-apps-tests.ts +++ b/types/cloudflare-apps/cloudflare-apps-tests.ts @@ -35,10 +35,16 @@ describe("Globals", () => { describe("CloudflareApps methods", () => { it("createElement", () => { - const element = CloudflareApps.createElement({ + const element: Element = CloudflareApps.createElement({ method: "replace", selector: "body > *" }); + + const div: HTMLDivElement = document.createElement("div"); + const divElement: HTMLDivElement = CloudflareApps.createElement({ + method: "replace", + selector: "body > *" + }, div); }); it("matchPage", () => { @@ -48,7 +54,8 @@ describe("CloudflareApps methods", () => { }); it("querySelector", () => { - const element: Element = CloudflareApps.querySelector("body > *"); + const element: Element | null = CloudflareApps.querySelector("body > *"); + const bodyElement: HTMLBodyElement | null = CloudflareApps.querySelector("body"); }); }); diff --git a/types/cloudflare-apps/index.d.ts b/types/cloudflare-apps/index.d.ts index 9436a568d9..2b0d397f5a 100644 --- a/types/cloudflare-apps/index.d.ts +++ b/types/cloudflare-apps/index.d.ts @@ -70,10 +70,16 @@ export interface InstallProduct { id: string; } -export interface CloudflareApps { - createElement(options: ElementLocation, previousElement?: Element): Element; +export interface CloudflareAppsMethods { + createElement(options: ElementLocation, previousElement?: T): T; + matchPage(patterns: string[]): boolean; - querySelector(selector: string): Element; + + querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: string): Element | null; +} + +export interface CloudflareApps extends CloudflareAppsMethods { installs: { [id: string]: App | undefined }; proxy: CloudflareAppsProxy; siteId: string; From bebdfcd94179143f9ff992c8288d3129de759b27 Mon Sep 17 00:00:00 2001 From: sqwk Date: Wed, 5 Jul 2017 01:02:48 +0200 Subject: [PATCH 0151/1618] fix: Add Types for Match Method --- types/paper/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 197707058b..812e6d4aad 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1382,7 +1382,7 @@ declare module 'paper' { * @param options.guides - hit-test items that have Item#guide set to true. * @param options.selected - only hit selected items. */ - hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; }): HitResult; + hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; match: (hit: HitResult) => boolean; }): HitResult; /** * Checks whether the item matches the criteria described by the given object, by iterating over all of its properties and matching against their values through matches(name, compare). From 41d890085589e635f99d458e9a1bd6dac52a4baf Mon Sep 17 00:00:00 2001 From: sqwk Date: Wed, 5 Jul 2017 01:04:08 +0200 Subject: [PATCH 0152/1618] fix: Update Return Type for Include Method --- types/paper/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 812e6d4aad..f7c93d4797 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -787,7 +787,7 @@ declare module 'paper' { * The rectangle.contains(point) method does not return true for points on the right or bottom edges of a rectangle. Therefore, if the added point falls on the left or bottom edge of the enlarged rectangle, rectangle.contains(point) returns false for that point. * @param point - the point to add to the rectangle */ - include(point: Point): Point; + include(point: Point): Rectangle; /** * Expands the rectangle by the specified amount in horizontal and vertical directions. From da9805b795074f4c813474b71d5a570ddbd003f7 Mon Sep 17 00:00:00 2001 From: "Adrian (Grim) Roach" Date: Tue, 4 Jul 2017 19:59:31 -0700 Subject: [PATCH 0153/1618] Added ebongarde-root type definition. --- types/ebongarde-root/ebongarde-root-tests.ts | 3 +++ types/ebongarde-root/index.d.ts | 8 +++++++ types/ebongarde-root/tsconfig.json | 22 ++++++++++++++++++++ types/ebongarde-root/tslint.json | 1 + 4 files changed, 34 insertions(+) create mode 100644 types/ebongarde-root/ebongarde-root-tests.ts create mode 100644 types/ebongarde-root/index.d.ts create mode 100644 types/ebongarde-root/tsconfig.json create mode 100644 types/ebongarde-root/tslint.json diff --git a/types/ebongarde-root/ebongarde-root-tests.ts b/types/ebongarde-root/ebongarde-root-tests.ts new file mode 100644 index 0000000000..ae5c35d85d --- /dev/null +++ b/types/ebongarde-root/ebongarde-root-tests.ts @@ -0,0 +1,3 @@ +import {ROOT} from 'ebongarde-root' + +console.log(ROOT) diff --git a/types/ebongarde-root/index.d.ts b/types/ebongarde-root/index.d.ts new file mode 100644 index 0000000000..6e923ffa3c --- /dev/null +++ b/types/ebongarde-root/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for ebongarde-root 1.7 +// Project: https://github.com/Ebongarde/ebongarde-root#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export declare var ROOT: string; diff --git a/types/ebongarde-root/tsconfig.json b/types/ebongarde-root/tsconfig.json new file mode 100644 index 0000000000..f34a4dc97f --- /dev/null +++ b/types/ebongarde-root/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ebongarde-root-tests.ts" + ] +} diff --git a/types/ebongarde-root/tslint.json b/types/ebongarde-root/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ebongarde-root/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From b37032d386a0ce68903f1136aabfad345a064eaa Mon Sep 17 00:00:00 2001 From: "Adrian (Grim) Roach" Date: Tue, 4 Jul 2017 20:15:13 -0700 Subject: [PATCH 0154/1618] fixed a few errors --- types/ebongarde-root/ebongarde-root-tests.ts | 4 ++-- types/ebongarde-root/index.d.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/ebongarde-root/ebongarde-root-tests.ts b/types/ebongarde-root/ebongarde-root-tests.ts index ae5c35d85d..f40eec7172 100644 --- a/types/ebongarde-root/ebongarde-root-tests.ts +++ b/types/ebongarde-root/ebongarde-root-tests.ts @@ -1,3 +1,3 @@ -import {ROOT} from 'ebongarde-root' +import {ROOT} from 'ebongarde-root'; -console.log(ROOT) +console.log(ROOT); diff --git a/types/ebongarde-root/index.d.ts b/types/ebongarde-root/index.d.ts index 6e923ffa3c..bd9563f991 100644 --- a/types/ebongarde-root/index.d.ts +++ b/types/ebongarde-root/index.d.ts @@ -5,4 +5,4 @@ /// -export declare var ROOT: string; +export const ROOT: string; From 9a3dd52efa751e6281222b8d3d2f1d765b552f6d Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Wed, 5 Jul 2017 11:37:14 +0100 Subject: [PATCH 0155/1618] Update restify to v5 --- types/restify-plugins/index.d.ts | 18 +- types/restify/index.d.ts | 1743 ++++++++++++++++++++++-------- types/restify/restify-tests.ts | 233 +--- 3 files changed, 1346 insertions(+), 648 deletions(-) diff --git a/types/restify-plugins/index.d.ts b/types/restify-plugins/index.d.ts index 5f6be60f38..d461358bdc 100644 --- a/types/restify-plugins/index.d.ts +++ b/types/restify-plugins/index.d.ts @@ -79,17 +79,10 @@ export interface AuditLoggerOptions { body?: boolean; } -export interface AuditLoggerReturns { - req: Request; - res: Response; - route: Route; - err: Error; -} - /** * An audit logger for recording all handled requests */ -export function auditLogger(options: AuditLoggerOptions): AuditLoggerReturns; +export function auditLogger(options: AuditLoggerOptions): (...args: any[]) => void; /** * Authorization header @@ -395,13 +388,6 @@ export interface MetricsCallbackOptions { connectionState: TMetricsCallback; } -export interface MetricsReturns { - req: Request; - res: Response; - route: Route; - err: Error; -} - /** * Listens to the server's after event and emits information about that request (5.x compatible only). * @@ -412,7 +398,7 @@ export interface MetricsReturns { * })); * ``` */ -export function metrics(opts: {server: Server}, callback: (options: MetricsCallback) => any ): MetricsReturns; +export function metrics(opts: {server: Server}, callback: (options: MetricsCallback) => any ): (...args: any[]) => void; /** * Parse the client's request for an OAUTH2 access tokensTable diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index a7781f933c..1e440b7eb7 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for restify 4.3 -// Project: https://github.com/mcavage/node-restify +// Type definitions for restify 5.0 +// Project: https://github.com/restify/node-restify // Definitions by: Bret Little , Steve Hipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -9,22 +9,427 @@ import http = require('http'); import Logger = require('bunyan'); import url = require('url'); +import restifyPlugins = require('restify-plugins'); -export interface addressInterface { +export interface BunyanOptions { + properties: any; + + serializers: any; + + headers: any; + + log: Logger; +} + +export interface ServerOptions { + ca?: any; + + certificate?: any; + + key?: any; + + passphrase?: string; + + requestCert?: boolean; + + ciphers?: string; + + formatters?: any; + + log?: Logger; + + name?: string; + + spdy?: any; + + version?: string; + + versions?: string[]; + + handleUpgrades?: boolean; + + httpsServerOptions?: any; + + handleUncaughtExceptions?: boolean; + + router?: Router; + + socketio?: boolean; + + noWriteContinue?: boolean; + + rejectUnauthorized?: boolean; +} + +export interface AddressInterface { port: number; + family: string; + address: string; } -export interface requestFileInterface { +export class Server { + /** + * Creates a new Server. + * @public + * @class + * @param {Object} options an options object + */ + new(options?: ServerOptions): Server +} + +export interface Server extends http.Server { + /** + * Returns the server address. Wraps node's address(). + * @public + * @function address + * @returns {String} + */ + address(): AddressInterface; + + /** + * Gets the server up and listening. Wraps node's listen(). + * + * You can call like: + * server.listen(80) + * server.listen(80, '127.0.0.1') + * server.listen('/tmp/server.sock') + * + * @public + * @function listen + * @throws {TypeError} + * @param {Function} callback optionally get notified when listening. + * @returns {undefined} + */ + listen(...args: any[]): any; + + /** + * Shuts down this server, and invokes callback (optionally) when done. + * Wraps node's close(). + * @public + * @function close + * @param {Function} callback optional callback to invoke when done. + * @returns {undefined} + */ + close(...args: any[]): any; + + /** + * Returns the number of currently inflight requests. + * @public + * @function inflightRequests + * @returns {Number} + */ + inflightRequests(): number; + + /** + * Mounts a chain on the given path against this HTTP verb + * + * @public + * @function del + * @param {String | Object} opts if string, the URL to handle. + * if options, the URL to handle, at minimum. + * @returns {Route} the newly created route. + */ + del(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; + + /** + * Mounts a chain on the given path against this HTTP verb + * + * @public + * @function get + * @param {String | Object} opts if string, the URL to handle. + * if options, the URL to handle, at minimum. + * @returns {Route} the newly created route. + */ + get(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; + + /** + * Mounts a chain on the given path against this HTTP verb + * + * @public + * @function head + * @param {String | Object} opts if string, the URL to handle. + * if options, the URL to handle, at minimum. + * @returns {Route} the newly created route. + */ + head(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; + + /** + * Mounts a chain on the given path against this HTTP verb + * + * @public + * @function opts + * @param {String | Object} opts if string, the URL to handle. + * if options, the URL to handle, at minimum. + * @returns {Route} the newly created route. + */ + opts(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; + + /** + * Mounts a chain on the given path against this HTTP verb + * + * @public + * @function post + * @param {String | Object} opts if string, the URL to handle. + * if options, the URL to handle, at minimum. + * @returns {Route} the newly created route. + */ + post(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; + + /** + * Mounts a chain on the given path against this HTTP verb + * + * @public + * @function put + * @param {String | Object} opts if string, the URL to handle. + * if options, the URL to handle, at minimum. + * @returns {Route} the newly created route. + */ + put(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; + + /** + * Mounts a chain on the given path against this HTTP verb + * + * @public + * @function patch + * @param {String | Object} opts if string, the URL to handle. + * if options, the URL to handle, at minimum. + * @returns {Route} the newly created route. + */ + patch(opts: string | RegExp | RouteOptions, ...handlers: RequestHandlerType[]): Route | boolean; + + /** + * Minimal port of the functionality offered by Express.js Route Param + * Pre-conditions + * @link http://expressjs.com/guide.html#route-param%20pre-conditions + * + * This basically piggy-backs on the `server.use` method. It attaches a + * new middleware function that only fires if the specified parameter exists + * in req.params + * + * Exposes an API: + * server.param("user", function (req, res, next) { + * // load the user's information here, always making sure to call next() + * }); + * + * @public + * @function param + * @param {String} name The name of the URL param to respond to + * @param {Function} fn The middleware function to execute + * @returns {Object} returns self + */ + param(name: string, fn: RequestHandler): Server; + + /** + * Piggy-backs on the `server.use` method. It attaches a new middleware + * function that only fires if the specified version matches the request. + * + * Note that if the client does not request a specific version, the middleware + * function always fires. If you don't want this set a default version with a + * pre handler on requests where the client omits one. + * + * Exposes an API: + * server.versionedUse("version", function (req, res, next, ver) { + * // do stuff that only applies to routes of this API version + * }); + * + * @public + * @function versionedUse + * @param {String|Array} versions the version(s) the URL to respond to + * @param {Function} fn the middleware function to execute, the + * fourth parameter will be the selected + * version + * @returns {undefined} + */ + versionedUse(versions: string | string[], fn: RequestHandler): Server; + + /** + * Removes a route from the server. + * You pass in the route 'blob' you got from a mount call. + * @public + * @function rm + * @throws {TypeError} on bad input. + * @param {String} route the route name. + * @returns {Boolean} true if route was removed, false if not. + */ + rm(route: string): boolean; + + /** + * Installs a list of handlers to run _before_ the "normal" handlers of all + * routes. + * + * You can pass in any combination of functions or array of functions. + * @public + * @function use + * @returns {Object} returns self + */ + use(...handlers: RequestHandlerType[]): Server; + + /** + * Gives you hooks to run _before_ any routes are located. This gives you + * a chance to intercept the request and change headers, etc., that routing + * depends on. Note that req.params will _not_ be set yet. + * @public + * @function pre + * @returns {Object} returns self + */ + pre(...pre: RequestHandlerType[]): Server; + + /** + * toString() the server for easy reading/output. + * @public + * @function toString + * @returns {String} + */ + toString(): string; + + /** + * Return debug information about the server. + * @public + * @method getDebugInfo + * @returns {Object} + */ + getDebugInfo(): any; + + /** Name of the server. */ + name: string; + + /** Default version(s) to use in all routes. */ + versions: string[]; + + /** bunyan instance. */ + log: Logger; + + /** List of content-types this server can respond with. */ + acceptable: string[]; + + /** Once listen() is called, this will be filled in with where the server is running. */ + url: string; +} + +export interface RouterOptions { + contentType?: string | string[]; + + strictRouting?: boolean; + + log?: Logger; + + version?: string; + + versions?: string[]; +} + +export class Router { + new(options: RouterOptions): Router; +} + +export interface Router { + /** + * takes an object of route params and query params, and 'renders' a URL. + * @public + * @function render + * @param {String} routeName the route name + * @param {Object} params an object of route params + * @param {Object} query an object of query params + * @returns {String} + */ + render(routeName: string, params: any, query?: any): string; + + /** + * adds a route. + * @public + * @function mount + * @param {Object} options an options object + * @returns {String} returns the route name if creation is successful. + */ + mount(options: RouteOptions): string | boolean; + + /** + * unmounts a route. + * @public + * @function unmount + * @param {String} name the route name + * @returns {String} the name of the deleted route. + */ + unmount(name: string): string; + + /** + * get a route from the router. + * @public + * @function get + * @param {String} name the name of the route to retrieve + * @param {Object} req the request object + * @param {Function} cb callback function + * @returns {undefined} + */ + get(name: string, req: Request, cb: FindRouteCallback): void; + + /** + * find a route from inside the router, handles versioned routes. + * @public + * @function find + * @param {Object} req the request object + * @param {Object} res the response object + * @param {Function} callback callback function + * @returns {undefined} + */ + find(req: Request, res: Response, callback: FindRouteCallback): void; + + /** + * Find a route by path. Scans the route list for a route with the same RegEx. + * i.e. /foo/:param1/:param2 would match an existing route with different + * parameter names /foo/:id/:name since the compiled RegExs match. + * @public + * @function findByPath + * @param {String | RegExp} path a path to find a route for. + * @param {Object} options an options object + * @returns {Object} returns the route if a match is found + */ + findByPath(path: string | RegExp): Route; + + /** + * toString() serialization. + * @public + * @function toString + * @returns {String} + */ + toString(): string; + + /** + * Return information about the routes registered in the router. + * @public + * @returns {object} The routes in the router. + */ + getDebugInfo(): any; + + name: string; + + mounts: { [routeName: string]: Route }; + + versions: string[]; + + contentType: string[]; + + routes: { + DELETE: Route[]; + GET: Route[]; + HEAD: Route[]; + OPTIONS: Route[]; + PATCH: Route[]; + POST: Route[]; + PUT: Route[]; + }; + + log?: Logger; +} + +export interface RequestFileInterface { path: string; type: string; } -/** - * Comes from authorizationParser plugin - */ -export interface requestAuthorization { +export interface RequestAuthorization { scheme: string; credentials: string; basic?: { @@ -35,13 +440,160 @@ export interface requestAuthorization { export interface Request extends http.IncomingMessage { /** - * builds an absolute URI for the request. - * @private - * @function absoluteUri - * @param {String} path a url path + * checks if the accept header is present and has the value requested. + * e.g., req.accepts('html'); + * @public + * @function accepts + * @param {String | Array} types an array of accept type headers + * @returns {Boolean} + */ + accepts(types: string | string[]): boolean; + + /** + * checks if the request accepts the encoding types. + * @public + * @function acceptsEncoding + * @param {String | Array} types an array of accept type headers + * @returns {Boolean} + */ + acceptsEncoding(types: string | string[]): boolean; + + /** + * gets the content-length header off the request. + * @public + * @function getContentLength + * @returns {Number} + */ + getContentLength(): number; + + /** + * pass through to getContentLength. + * @public + * @function contentLength + * @returns {Number} + */ + contentLength(): number; + + /** + * gets the content-type header. + * @public + * @function getContentType + * @returns {String} + */ + getContentType(): string; + + /** + * pass through to getContentType. + * @public + * @function contentType + * @returns {Number} + */ + contentType(): string; + + /** + * retrieves the complete URI requested by the client. + * @public + * @function getHref + * @returns {String} + */ + getHref(): string; + + /** + * pass through to getHref. + * @public + * @function href + * @returns {String} + */ + href(): string; + + /** + * retrieves the request uuid. was created when the request was setup. + * @public + * @function getId * @returns {String} */ - absoluteUri(path: string): string; + getId(): string; + + /** + * pass through to getId. + * @public + * @function id + * @returns {String} + */ + id(): string; + + /** + * retrieves the cleaned up url path. + * e.g., /foo?a=1 => /foo + * @public + * @function getPath + * @returns {String} + */ + getPath(): string; + + /** + * pass through to getPath. + * @public + * @function path + * @returns {String} + */ + path(): string; + + /** + * returns the raw query string + * @public + * @function getQuery + * @returns {String} + */ + getQuery(): string; + + // /** + // * pass through to getQuery. + // * @public + // * @function query + // * @returns {String} + // */ + // query(): string; + + /** + * returns ms since epoch when request was setup. + * @public + * @function time + * @returns {Number} + */ + time(): number; + + /** + * returns a parsed URL object. + * @public + * @function getUrl + * @returns {Object} + */ + getUrl(): url.Url; + + /** + * returns the accept-version header. + * @public + * @function getVersion + * @returns {String} + */ + getVersion(): string; + + /** + * pass through to getVersion. + * @public + * @function version + * @returns {String} + */ + version(): string; + + /** + * returns the version of the route that matched. + * @public + * @function matchedVersion + * @returns {String} + */ + matchedVersion(): string; /** * returns any header off the request. also, 'correct' any @@ -65,25 +617,6 @@ export interface Request extends http.IncomingMessage { */ trailer(name: string, value?: string): string; - /** - * checks if the accept header is present and has the value requested. - * e.g., req.accepts('html'); - * @public - * @function accepts - * @param {String | Array} types an array of accept type headers - * @returns {Boolean} - */ - accepts(types: string | string[]): boolean; - - /** - * checks if the request accepts the encoding types. - * @public - * @function acceptsEncoding - * @param {String | Array} types an array of accept type headers - * @returns {Boolean} - */ - acceptsEncoding(types: string | string[]): boolean; - /** * Check if the incoming request contains the Content-Type header field, and * if it contains the given mime type. @@ -110,6 +643,14 @@ export interface Request extends http.IncomingMessage { */ isKeepAlive(): boolean; + /** + * Check if the incoming request is encrypted. + * @public + * @function isSecure + * @returns {Boolean} + */ + isSecure(): boolean; + /** * Check if the incoming request has been upgraded. * @public @@ -126,6 +667,14 @@ export interface Request extends http.IncomingMessage { */ isUpload(): boolean; + /** + * toString serialization + * @public + * @function toString + * @returns {String} + */ + toString(): string; + /** * retrieves the user-agent header. * @public @@ -154,165 +703,289 @@ export interface Request extends http.IncomingMessage { */ endHandlerTimer(handlerName: string): void; - getLogger(component: string): any; - /** - * gets the content-length header off the request. + * returns the connection state of the request. current valid values are + * 'close' and 'aborted'. * @public - * @function getContentLength - * @returns {Number} - */ - getContentLength(): number; - - /** - * @see getContentLength - * @function contentLength - */ - contentLength(): number; - - /** - * gets the content-type header. - * @public - * @function getContentType + * @function connectionState * @returns {String} */ - getContentType(): string; + connectionState(): string; /** - * @see getContentType - */ - contentType(): string; - - /** - * retrieves the complete URI requested by the client. + * returns the route object to which the current request was matched to. + * Route info object structure: + * { + * path: '/ping/:name', + * method: 'GET', + * versions: [], + * name: 'getpingname' + } * @public - * @function getHref - * @returns {String} + * @function getRoute + * @returns {Object} */ - getHref(): string; - - /** - * @see getHref - */ - href(): string; + getRoute(): RouteSpec; + /**bunyan logger you can piggyback on. */ log: Logger; - /** - * retrieves the request uuid. was created when the request was setup. - * @public - * @function getId - * @returns {String} - */ - getId(): string; - /** - * @see getId - */ - id(): string; + /** available when queryParser plugin is used. */ + query?: any; - /** - * retrieves the cleaned up url path. - * e.g., /foo?a=1 => /foo - * @public - * @function getPath - * @returns {String} - */ - getPath(): string; - - /** - * @see getPath - */ - path(): string; - - /** - * returns the raw query string - * @public - * @function getQuery - * @returns {String} - */ - getQuery(): string; - - /** - * @see getQuery - */ - query: any; - - secure: boolean; - - /** - * returns ms since epoch when request was setup. - * @public - * @function time - * @returns {Number} - */ - time(): number; - - /** - * returns a parsed URL object. - * @public - * @function getUrl - * @returns {Object} - */ - getUrl(): url.Url; - - /** - * returns the accept-version header. - * @public - * @function getVersion - * @returns {String} - */ - getVersion(): string; - - /** - * @see getVersion - */ - version(): string; - params: any; - files?: { [name: string]: requestFileInterface }; - - /** - * Check if the incoming request is encrypted. - * @public - * @function isSecure - * @returns {Boolean} - */ - isSecure(): boolean; - /** available when bodyParser plugin is used */ + /** available when bodyParser plugin is used. */ body?: any; + + /** available when queryParser or bodyParser plugin is used with mapParams enabled. */ + params?: any; + + /** available when serveStatic plugin is used. */ + files?: { [name: string]: RequestFileInterface }; + /** available when authorizationParser plugin is used */ username?: string; - /** available when authorizationParser plugin is used */ - authorization?: requestAuthorization; - timers: HandlerTiming[]; + /** available when authorizationParser plugin is used */ + authorization?: RequestAuthorization; } -/** - * Timer object used to identify how long a specific handler took to run - * - * @property {String} name The name of the handler. - * @property {Array} time A tuple of [seconds, nanoseconds], how long the handler took. - */ -export interface HandlerTiming { - name: string; - time: [number, number]; +export interface CacheOptions { + maxAge: number; } export interface Response extends http.ServerResponse { - header(key: string, value?: any): any; - cache(type?: any, options?: any): any; - noCache(): any; - status(code: number): any; - send(status?: any, body?: any, headers?: { [header: string]: string }): any; - json(status?: any, body?: any, headers?: { [header: string]: string }): any; + /** + * sets the cache-control header. `type` defaults to _public_, + * and options currently only takes maxAge. + * @public + * @function cache + * @param {String} type value of the header + * @param {Object} [options] an options object + * @returns {String} the value set to the header + */ + cache(type: string, options?: CacheOptions): string; + + /** + * sets the cache-control header. `type` defaults to _public_, + * and options currently only takes maxAge. + * @public + * @function cache + * @param {Object} [options] an options object + * @returns {String} the value set to the header + */ + cache(options?: CacheOptions): string; + + /** + * turns off all cache related headers. + * @public + * @function noCache + * @returns {Object} self, the response object + */ + noCache(): Response; + + /** + * Appends the provided character set to the response's Content-Type. + * e.g., res.charSet('utf-8'); + * @public + * @function charSet + * @param {String} type char-set value + * @returns {Object} self, the response object + */ + charSet(type: string): Response; + + /** + * retrieves a header off the response. + * @public + * @function get + * @param {Object} name the header name + * @returns {String} + */ + get(name: string): string; + + /** + * retrieves all headers off the response. + * @public + * @function getHeaders + * @returns {Object} + */ + getHeaders(): any; + + /** + * pass through to getHeaders. + * @public + * @function headers + * @returns {Object} + */ + headers(): any; + + /** + * sets headers on the response. + * @public + * @function header + * @param {String} name the name of the header + * @param {String} value the value of the header + * @returns {Object} + */ + header(name: string, value?: any): any; + + /** + * short hand method for: + * res.contentType = 'json'; + * res.send({hello: 'world'}); + * @public + * @function json + * @param {Number} code http status code + * @param {Object} object value to json.stringify + * @param {Object} [headers] headers to set on the response + * @returns {Object} + */ + json(code: number, object: any, headers?: { [header: string]: string }): any; + + /** + * short hand method for: + * res.contentType = 'json'; + * res.send({hello: 'world'}); + * @public + * @function json + * @param {Object} object value to json.stringify + * @param {Object} [headers] headers to set on the response + * @returns {Object} + */ + json(object: any, headers?: { [header: string]: string }): any; + + /** + * sets the link heaader. + * @public + * @function link + * @param {String} l the link key + * @param {String} rel the link value + * @returns {String} the header value set to res + */ + link(l: string, rel: string): string + + /** + * sends the response object. pass through to internal __send that uses a + * formatter based on the content-type header. + * @public + * @function send + * @param {Number} [code] http status code + * @param {Object | Buffer | Error} [body] the content to send + * @param {Object} [headers] any add'l headers to set + * @returns {Object} the response object + */ + send(code?: any, body?: any, headers?: { [header: string]: string }): any; + + /** + * sends the response object. pass through to internal __send that skips + * formatters entirely and sends the content as is. + * @public + * @function sendRaw + * @param {Number} [code] http status code + * @param {Object | Buffer | Error} [body] the content to send + * @param {Object} [headers] any add'l headers to set + * @returns {Object} the response object + */ + sendRaw(code?: any, body?: any, headers?: { [header: string]: string }): any; + + /** + * sets a header on the response. + * @public + * @function set + * @param {String} name name of the header + * @param {String} val value of the header + * @returns {Object} self, the response object + */ + set(name: string, val: string): Response; + + /** + * sets the http status code on the response. + * @public + * @function status + * @param {Number} code http status code + * @returns {Number} the status code passed in + */ + status(code: number): number; + + /** + * toString() serialization. + * @public + * @function toString + * @returns {String} + */ + toString(): string; + + /** + * pass through to native response.writeHead(). + * @public + * @function writeHead + * @emits header + * @returns {undefined} + */ + writeHead(): void; + + /** redirect is sugar method for redirecting. + * res.redirect(301, 'www.foo.com', next); + * `next` is mandatory, to complete the response and trigger audit logger. + * @public + * @param {Number} code the status code + * @param {String} url to redirect to + * @param {Function} next fn + * @emits redirect + * @function redirect + * @return {undefined} + */ + redirect(code: number, url: string, next: Next): void; + + /** redirect is sugar method for redirecting. + * res.redirect('www.foo.com', next); + * `next` is mandatory, to complete the response and trigger audit logger. + * @public + * @param {String} url to redirect to + * @param {Function} next fn + * @emits redirect + * @function redirect + * @return {undefined} + */ + redirect(url: string, next: Next): void; + + /** redirect is sugar method for redirecting. + * res.redirect({...}, next); + * `next` is mandatory, to complete the response and trigger audit logger. + * @public + * @param {Object} options the status code + * @param {Function} next fn + * @emits redirect + * @function redirect + * @return {undefined} + */ + redirect(options: any, next: Next): void; + + /** HTTP status code. */ code: number; + + /** short hand for the header content-length. */ contentLength: number; - charSet(value: string): void; + + /** short hand for the header content-type. */ contentType: string; + + /** response headers. */ headers: any; + + /** A unique request id (x-request-id). */ id: string; } +export interface Next { + (err?: any): void; + + ifError(err?: any): void; +} + +export interface RoutePathRegex extends RegExp { + restifyParams: string[]; +} + export interface RouteSpec { method: string; name: string; @@ -331,282 +1004,510 @@ export interface Route { export interface RouteOptions { name: string; + method: string; + path?: string | RegExp; + url?: string | RegExp; + urlParamPattern?: RegExp; + contentType?: string | string[]; - versions?: string | string[]; -} -export interface RoutePathRegex extends RegExp { - restifyParams: string[]; -} - -export interface Router { - name: string; - mounts: { [routeName: string]: Route }; - versions: string[]; - contentType: string[]; - routes: { - DELETE: Route[]; - GET: Route[]; - HEAD: Route[]; - OPTIONS: Route[]; - PATCH: Route[]; - POST: Route[]; - PUT: Route[]; - }; - log?: any; - toString(): string; - - /** - * Takes an object of route params and query params, and 'renders' a URL - * @param {String} routeName the route name - * @param {Object} params an object of route params - * @param {Object} query an object of query params - * @returns {String} - */ - render(routeName: string, params: any, query?: any): string; - - /** - * adds a route. - * @param {Object} options an options object - * @returns {String} returns the route name if creation is successful. - */ - mount(options: any): string | boolean; - - /** - * unmounts a route. - * @param {String} name the route name - * @returns {String} the name of the deleted route (or false if it was not matched) - */ - unmount(name: string): string | boolean; - - /** - * finds the route for a given request and response. - * @param {Request} req the request object - * @param {Response} res the response object - * @param {Function} callback operation callback - * @returns {undefined} - */ - find(req: Request, res: Response, callback: (err: Error, route: Route) => void): void; -} - -export interface Server extends http.Server { - use(handler: RequestHandler | RequestHandler[], ...handlers: RequestHandler[]): Server; - // tslint:disable-next-line unified-signatures - use(handler: RequestHandler | RequestHandler[], ...handlers: RequestHandler[][]): Server; - - post(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; - // tslint:disable-next-line unified-signatures - post(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; - - patch(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; - // tslint:disable-next-line unified-signatures - patch(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; - - put(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; - // tslint:disable-next-line unified-signatures - put(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; - - del(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; - // tslint:disable-next-line unified-signatures - del(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; - - get(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; - // tslint:disable-next-line unified-signatures - get(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; - - head(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; - // tslint:disable-next-line unified-signatures - head(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; - - opts(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; - // tslint:disable-next-line unified-signatures - opts(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; - - name: string; - version: string; - log: any; - acceptable: string[]; - url: string; - address(): addressInterface; - listen(...args: any[]): any; - close(...args: any[]): any; - pre(routeCallBack: RequestHandler): Server; - server: http.Server; - router: Router; - routes: Route[]; - toString(): string; -} - -export interface ServerOptions { - ca?: string; - certificate?: string | string[] | Buffer | Buffer[]; - key?: string | string[] | Buffer | Buffer[]; - formatters?: any; - log?: any; - name?: string; - spdy?: any; version?: string; - responseTimeHeader?: string; - responseTimeFormatter?(durationInMilliseconds: number): any; - handleUpgrades?: boolean; - router?: Router; - httpsServerOptions?: any; - socketio?: boolean; + + versions?: string[]; } -export interface ClientOptions { - accept?: string; - connectTimeout?: number; - requestTimeout?: number; - dtrace?: any; - gzip?: any; - headers?: any; - log?: any; - retry?: any; - signRequest?(): void; - url?: string; - userAgent?: string; - version?: string; -} - -export interface Client { - get(opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; - head(opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any): any; - post(opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; - put(opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; - patch(opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; - del(opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any): any; - basicAuth(username: string, password: string): any; -} - -export interface HttpClient { - get(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; - head(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; - post(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; - put(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; - patch(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; - del(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; - basicAuth(username: string, password: string): any; -} - -export interface ThrottleOptions { - burst?: number; - rate?: number; - ip?: boolean; - xff?: boolean; - username?: boolean; - tokensTable?: any; - maxKeys?: number; - overrides?: any; -} - -export interface Next { - (err?: any): any; - ifError(err?: any): any; -} +type FindRouteCallback = (err: Error, route?: Route, params?: any) => void; export type RequestHandler = (req: Request, res: Response, next: Next) => any; +type RequestHandlerType = RequestHandler | RequestHandler[]; + +export function bunyan(options?: BunyanOptions): RequestHandler; export function createServer(options?: ServerOptions): Server; -export function createJsonClient(options?: ClientOptions): Client; -export function createStringClient(options?: ClientOptions): Client; -export function createClient(options?: ClientOptions): HttpClient; - -export class HttpError { constructor(cause: any, message?: any); } - -export class DefiniteHttpError { - constructor(message?: any); - - // tslint:disable-next-line unified-signatures - constructor(cause: any, message?: any); +export const formatters: { + [name: string]: RequestHandler } -export class BadRequestError extends DefiniteHttpError { } -export class UnauthorizedError extends DefiniteHttpError { } -export class PaymentRequiredError extends DefiniteHttpError { } -export class ForbiddenError extends DefiniteHttpError { } -export class NotFoundError extends DefiniteHttpError { } -export class MethodNotAllowedError extends DefiniteHttpError { } -export class NotAcceptableError extends DefiniteHttpError { } -export class ProxyAuthenticationRequiredError extends DefiniteHttpError { } -export class RequestTimeoutError extends DefiniteHttpError { } -export class ConflictError extends DefiniteHttpError { } -export class GoneError extends DefiniteHttpError { } -export class LengthRequiredError extends DefiniteHttpError { } -export class RequestEntityTooLargeError extends DefiniteHttpError { } -export class RequesturiTooLargeError extends DefiniteHttpError { } -export class UnsupportedMediaTypeError extends DefiniteHttpError { } -export class RequestedRangeNotSatisfiableError extends DefiniteHttpError { } -export class ExpectationFailedError extends DefiniteHttpError { } -export class ImATeapotError extends DefiniteHttpError { } -export class UnprocessableEntityError extends DefiniteHttpError { } -export class LockedError extends DefiniteHttpError { } -export class FailedDependencyError extends DefiniteHttpError { } -export class UnorderedCollectionError extends DefiniteHttpError { } -export class UpgradeRequiredError extends DefiniteHttpError { } -export class PreconditionRequiredError extends DefiniteHttpError { } -export class TooManyRequestsError extends DefiniteHttpError { } -export class RequestHeaderFieldsTooLargeError extends DefiniteHttpError { } -export class InternalServerError extends DefiniteHttpError { } -export class NotImplementedError extends DefiniteHttpError { } -export class BadGatewayError extends DefiniteHttpError { } -export class ServiceUnavailableError extends DefiniteHttpError { } -export class GatewayTimeoutError extends DefiniteHttpError { } -export class HttpVersionNotSupportedError extends DefiniteHttpError { } -export class VariantAlsoNegotiatesError extends DefiniteHttpError { } -export class InsufficientStorageError extends DefiniteHttpError { } -export class BandwidthLimitExceededError extends DefiniteHttpError { } -export class NotExtendedError extends DefiniteHttpError { } -export class NetworkAuthenticationRequiredError extends DefiniteHttpError { } -export class RestError extends DefiniteHttpError { } +export namespace plugins { + export namespace pre { + /** + * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request. + */ + function context(): RequestHandler; -export class PreconditionFailedError extends RestError { } -export class BadDigestError extends RestError { } -export class BadMethodError extends RestError { } -export class InternalError extends RestError { } -export class InvalidArgumentError extends RestError { } -export class InvalidContentError extends RestError { } -export class InvalidCredentialsError extends RestError { } -export class InvalidHeaderError extends RestError { } -export class InvalidVersionError extends RestError { } -export class MissingParameterError extends RestError { } -export class NotAuthorizedError extends RestError { } -export class RequestExpiredError extends RestError { } -export class RequestThrottledError extends RestError { } -export class ResourceNotFoundError extends RestError { } -export class WrongAcceptError extends RestError { } + /** + * + */ + function dedupeSlashes(): RequestHandler; -export function acceptParser(parser: any): RequestHandler; -export function authorizationParser(): RequestHandler; -export function dateParser(skew?: number): RequestHandler; -export function queryParser(options?: any): RequestHandler; -export function urlEncodedBodyParser(options?: any): RequestHandler[]; -export function jsonp(): RequestHandler; -export function gzipResponse(options?: any): RequestHandler; -export function bodyParser(options?: any): RequestHandler[]; -export function requestLogger(options?: any): RequestHandler; -export function serveStatic(options?: any): RequestHandler; -export function throttle(options?: ThrottleOptions): RequestHandler; -export function conditionalRequest(): RequestHandler[]; -export function auditLogger(options: { log: any }): (req: Request, res: Response, route: Route, err: any) => void; -export function fullResponse(): RequestHandler; -// tslint:disable-next-line no-var -export var defaultResponseHeaders: any; + /** + * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser. + */ + function pause(): RequestHandler; -export function CORS(options?: CORSOptions): RequestHandler; -export interface CORSOptions { - origins?: string[]; - credentials?: boolean; - headers?: string[]; + /** + * Cleans up duplicate or trailing / on the URL + */ + function sanitizePath(): RequestHandler; + + /** + * Automatically reuse incoming request header as the request id. + */ + function reqIdHeaders(options: { headers: string[] }): RequestHandler; + + /** + * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400. + */ + function strictQueryParams(options?: { message: string }): RequestHandler; + + /** + * Regexp to capture curl user-agents + */ + function userAgentConnection(options?: { userAgentRegExp: any }): RequestHandler; + } + + // *************** This module includes the following header parser plugins: + + /** + * Check the client's Accept header can be handled by this server. + */ + export function acceptParser(accepts: string[]): RequestHandler; + + export interface AuditLoggerOptions { + /** + * Bunyan logger + */ + log: Logger; + + /** + * Restify server. If passed in, causes server to emit 'auditlog' event after audit logs are flushed + */ + server?: Server; + + /** + * Ringbuffer which is written to if passed in + */ + logBuffer?: any; + + /** + * When true, prints audit logs. default true. + */ + printLog?: boolean; + + /** + * + */ + body?: boolean; + } + + /** + * An audit logger for recording all handled requests + */ + export function auditLogger(options: AuditLoggerOptions): (...args: any[]) => void; + + /** + * Authorization header + */ + export function authorizationParser(options?: any): RequestHandler; + + /** + * Conditional headers (If-*) + */ + export function conditionalRequest(): RequestHandler[]; + + /** + * Handles disappeared CORS headers + */ + export function fullResponse(): RequestHandler; + + // ************ This module includes the following data parsing plugins: + + export interface BodyParserOptions { + /** + * The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory. + */ + maxBodySize?: number; + + /** + * If req.params should be filled with parsed parameters from HTTP body. + */ + mapParams?: boolean; + + /** + * If req.params should be filled with the contents of files sent through a multipart request. + * Formidable is used internally for parsing, and a file is denoted as a multipart part with the filename option set in its Content-Disposition. + * This will only be performed if mapParams is true. + */ + mapFiles?: boolean; + + /** + * If an entry in req.params should be overwritten by the value in the body if the names are the same. + * For instance, if you have the route /:someval, and someone posts an x-www-form-urlencoded Content-Type with the body someval=happy to /sad, + * the value will be happy if overrideParams is true, sad otherwise. + */ + overrideParams?: boolean; + + /** + * A callback to handle any multipart part which is not a file. + * If this is omitted, the default handler is invoked which may or may not map the parts into req.params, depending on the mapParams-option. + */ + multipartHandler?(): void; + + /** + * A callback to handle any multipart file. + * It will be a file if the part have a Content-Disposition with the filename parameter set. + * This typically happens when a browser sends a form and there is a parameter similar to . + * If this is not provided, the default behaviour is to map the contents into req.params. + */ + multipartFileHandler?(): void; + + /** + * If you want the uploaded files to include the extensions of the original files (multipart uploads only). Does nothing if multipartFileHandler is defined. + */ + keepExtensions?: boolean; + + /** + * Where uploaded files are intermediately stored during transfer before the contents is mapped into req.params. Does nothing if multipartFileHandler is defined. + */ + uploadDir?: string; + + /** + * If you want to support html5 multiple attribute in upload fields. + */ + multiples?: boolean; + + /** + * If you want checksums calculated for incoming files, set this to either sha1 or md5. + */ + hash?: string; + + /** + * Set to true if you want to end the request with a UnsupportedMediaTypeError when none of the supported content types was given. + */ + rejectUnknown?: boolean; + + /** + * + */ + reviver?: any; + + /** + * + */ + maxFieldsSize?: number; + } + + /** + * Parses POST bodies to req.body. automatically uses one of the following parsers based on content type. + */ + export function bodyParser(options?: BodyParserOptions): RequestHandler[]; + + /** + * Reads the body of the request. + */ + export function bodyReader(options?: { maxBodySize?: number }): RequestHandler; + + export interface UrlEncodedBodyParser { + mapParams?: boolean; + overrideParams?: boolean; + } + + /** + * Parse the HTTP request body IFF the contentType is application/x-www-form-urlencoded. + * + * If req.params already contains a given key, that key is skipped and an + * error is logged. + */ + export function urlEncodedBodyParser(options?: UrlEncodedBodyParser): RequestHandler[]; + + /** + * Parses JSON POST bodies + */ + export function jsonBodyParser(options?: { mapParams?: boolean, reviver?: any, overrideParams?: boolean }): RequestHandler[]; + + /** + * Parses JSONP callback + */ + export function jsonp(): RequestHandler; + + export interface MultipartBodyParser { + overrideParams?: boolean; + multiples?: boolean; + keepExtensions?: boolean; + uploadDir?: string; + maxFieldsSize?: number; + hash?: string; + multipartFileHandler?: any; + multipartHandler?: any; + mapParams?: boolean; + mapFiles?: boolean; + } + + /** + * Parses JSONP callback + */ + export function multipartBodyParser(options?: MultipartBodyParser): RequestHandler; + + export interface QueryParserOptions { + /** + * Default `false`. Copies parsed query parameters into `req.params`. + */ + mapParams?: boolean; + + /** + * Default `false`. Only applies when if mapParams true. When true, will stomp on req.params field when existing value is found. + */ + overrideParams?: boolean; + + /** + * Default false. Transform `?foo.bar=baz` to a nested object: `{foo: {bar: 'baz'}}`. + */ + allowDots?: boolean; + + /** + * Default 20. Only transform `?a[$index]=b` to an array if `$index` is less than `arrayLimit`. + */ + arrayLimit?: number; + + /** + * Default 5. The depth limit for parsing nested objects, e.g. `?a[b][c][d][e][f][g][h][i]=j`. + */ + depth?: number; + + /** + * Default 1000. Maximum number of query params parsed. Additional params are silently dropped. + */ + parameterLimit?: number; + + /** + * Default true. Whether to parse `?a[]=b&a[1]=c` to an array, e.g. `{a: ['b', 'c']}`. + */ + parseArrays?: boolean; + + /** + * Default false. Whether `req.query` is a "plain" object -- does not inherit from `Object`. + * This can be used to allow query params whose names collide with Object methods, e.g. `?hasOwnProperty=blah`. + */ + plainObjects?: boolean; + + /** + * Default false. If true, `?a&b=` results in `{a: null, b: ''}`. Otherwise, `{a: '', b: ''}`. + */ + strictNullHandling?: boolean; + } + + /** + * Parses URL query paramters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) + */ + export function queryParser(options?: QueryParserOptions): RequestHandler; + + export interface RequestLogger { + properties?: any; + serializers?: any; + headers?: any; + log?: any; + } + + /** + * Adds timers for each handler in your request chain + * + * `options.properties` properties to pass to bunyan's `log.child()` method + */ + export function requestLogger(options?: RequestLogger): RequestHandler; + + // ******************** The module includes the following response plugins: + + /** + * expires requests based on current time + delta + * @param delta - age in seconds + */ + export function dateParser(delta?: number): RequestHandler; + + /** + * gzips the response if client send `accept-encoding: gzip` + * @param options options to pass to gzlib + */ + export function gzipResponse(options?: any): RequestHandler; + + export interface ServeStatic { + appendRequestPath?: boolean | undefined; + directory?: string; + maxAge?: number; + match?: any; + charSet?: string; + file?: string; + etag?: string; + default?: any; + gzip?: boolean; + } + + /** + * Used to serve static files + */ + export function serveStatic(options?: ServeStatic): RequestHandler; + + export interface ThrottleOptions { + burst?: number; + rate?: number; + ip?: boolean; + username?: boolean; + xff?: boolean; + tokensTable?: any; + maxKeys?: number; + overrides?: any; // any + } + + export interface MetricsCallback { + /** + * An error if the request had an error + */ + err: Error; + + /** + * + */ + metrics: MetricsCallbackOptions; + + req: Request; + res: Response; + + /** + * The route obj that serviced the request + */ + route: Route; + } + + export type TMetricsCallback = 'close' | 'aborted' | undefined; + + export interface MetricsCallbackOptions { + /** + * Status code of the response. Can be undefined in the case of an `uncaughtException`. + * Otherwise, in most normal scenarios, even calling `res.send()` or `res.end()` should result in a 200 by default. + */ + statusCode: number; + + /** + * HTTP request verb + */ + method: string; + + /** + * Request latency + */ + latency: number; + + /** + * req.path() value + */ + path: string; + + /** + * If this value is set, err will be a corresponding `RequestCloseError` or `RequestAbortedError`. + * + * If connectionState is either 'close' or 'aborted', then the statusCode is not applicable since the connection was severed before a response was written. + */ + connectionState: TMetricsCallback; + } + + /** + * Listens to the server's after event and emits information about that request (5.x compatible only). + * + * ``` + * server.on('after', plugins.metrics( (err, metrics) => + * { + * // metrics is an object containing information about the request + * })); + * ``` + */ + export function metrics(opts: { server: Server }, callback: (options: MetricsCallback) => any): (...args: any[]) => void; + + /** + * Parse the client's request for an OAUTH2 access tokensTable + * + * Subsequent handlers will see `req.oauth2`, which looks like: + * ``` + * { + * oauth2: {accessToken: 'mF_9.B5f-4.1JqM&p=q'} + * } + * ``` + */ + export function oauth2TokenParser(): RequestHandler; + + /** + * throttles responses + */ + export function throttle(options?: ThrottleOptions): RequestHandler; + + export interface RequestExpiryOptions { + /** + * Header name of the absolute time for request expiration + */ + absoluteHeader?: string; + + /** + * Header name for the start time of the request + */ + startHeader?: string; + + /** + * The header name for the time in milliseconds that should ellapse before the request is considered expired. + */ + timeoutHeader?: string; + } + + /** + * A request expiry will use headers to tell if the incoming request has expired or not. + * + * There are two options for this plugin: + * 1. Absolute Time + * * Time in Milliseconds since the Epoch when this request should be considered expired + * 2. Timeout + * * The request start time is supplied + * * A timeout, in milliseconds, is given + * * The timeout is added to the request start time to arrive at the absolute time + * in which the request is considered expires + */ + export function requestExpiry(options?: RequestExpiryOptions): RequestHandler; } -export const pre: { - pause(): RequestHandler; - sanitizePath(options?: any): RequestHandler; - userAgentConnection(options?: any): RequestHandler; -}; +export namespace pre { + /** + * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request. + */ + function context(): RequestHandler; + + /** + * + */ + function dedupeSlashes(): RequestHandler; + + /** + * This pre handler fixes issues with node hanging when an asyncHandler is used prior to bodyParser. + */ + function pause(): RequestHandler; + + /** + * Cleans up duplicate or trailing / on the URL + */ + function sanitizePath(): RequestHandler; + + /** + * Automatically reuse incoming request header as the request id. + */ + function reqIdHeaders(options: { headers: string[] }): RequestHandler; + + /** + * Checks req.urls query params with strict key/val format and rejects non-strict requests with status code 400. + */ + function strictQueryParams(options?: { message: string }): RequestHandler; + + /** + * Regexp to capture curl user-agents + */ + function userAgentConnection(options?: { userAgentRegExp: any }): RequestHandler; +} diff --git a/types/restify/restify-tests.ts b/types/restify/restify-tests.ts index 15eb8eb868..7e80e5290f 100644 --- a/types/restify/restify-tests.ts +++ b/types/restify/restify-tests.ts @@ -1,7 +1,10 @@ import * as restify from "restify"; import * as url from "url"; +import * as Logger from "bunyan"; -let server = restify.createServer({ +let server = new restify.Server(); + +server = restify.createServer({ formatters: { 'application/foo': function formatFoo(req: restify.Request, res: restify.Response, body: any) { if (body instanceof Error) @@ -15,26 +18,14 @@ let server = restify.createServer({ } }); -server = restify.createServer({ - ca: "test", - certificate: "test", - key: "test", - formatters: {}, - log: {}, - name: "test", - spdy: {}, - version: "", - responseTimeHeader: "", - responseTimeFormatter: (durationInMilliseconds: number) => { }, - socketio: false -}); +server = restify.createServer({}); server.pre(restify.pre.sanitizePath()); server.on('someEvent', () => { }); server.use((req: restify.Request, res: restify.Response, next: restify.Next) => { }); -server.use([(req: restify.Request, res: restify.Response, next: restify.Next) => { }]); +server.use([(req: restify.Request, res: restify.Response, next: restify.Next) => { }, (req: restify.Request, res: restify.Response, next: restify.Next) => { }]); server.use((req: restify.Request, res: restify.Response, next: restify.Next) => { }, (req: restify.Request, res: restify.Response, next: restify.Next) => { }); function send(req: restify.Request, res: restify.Response, next: restify.Next) { @@ -56,10 +47,6 @@ function send(req: restify.Request, res: restify.Response, next: restify.Next) { req.userAgent() === 'test'; req.startHandlerTimer('test'); req.endHandlerTimer('test'); - req.absoluteUri('test') === 'test'; - - req.timers.pop() === { name: 'test', time: [0, 1234] }; - req.getLogger('test'); const log = req.log; log.debug({ params: req.params }, 'Hello there %s', 'foo'); @@ -76,25 +63,24 @@ function send(req: restify.Request, res: restify.Response, next: restify.Next) { req.path() === 'test'; req.getQuery() === 'test'; req.query === 'test'; - req.secure === true; req.time() === 1463518410080; - req.getUrl() === url.parse('http://test.test.test/test'); + req.getUrl() === url.parse('https://test.test.test/test'); req.getVersion() === 'test'; req.version() === 'test'; req.params; - res.header('test'); res.header('test', {}); res.header('test', new Date()); res.cache(); - res.cache('testst', {}); + res.cache('testst', { maxAge: 60 }); + res.cache({ maxAge: 60 }); res.status(344); res.send({ hello: 'world' }); res.send(201, { hello: 'world' }); - res.send(new restify.BadRequestError('meh')); + res.send(new Error('meh')); res.json(201, { hello: 'world' }); res.json({ hello: 'world' }); @@ -107,6 +93,7 @@ function send(req: restify.Request, res: restify.Response, next: restify.Next) { res.id === 'test'; res.send('hello ' + req.params.name); + res.writeHead(); return next(); } @@ -124,119 +111,8 @@ server.get(/(.*)/, send); server.head(/(.*)/, send); server.opts(/(.*)/, send); -new restify.BadRequestError(); -new restify.UnauthorizedError(); -new restify.PaymentRequiredError(); -new restify.ForbiddenError(); -new restify.NotFoundError(); -new restify.MethodNotAllowedError(); -new restify.NotAcceptableError(); -new restify.ProxyAuthenticationRequiredError(); -new restify.RequestTimeoutError(); -new restify.ConflictError(); -new restify.GoneError(); -new restify.LengthRequiredError(); -new restify.RequestEntityTooLargeError(); -new restify.RequesturiTooLargeError(); -new restify.UnsupportedMediaTypeError(); -new restify.RequestedRangeNotSatisfiableError(); -new restify.ExpectationFailedError(); -new restify.ImATeapotError(); -new restify.UnprocessableEntityError(); -new restify.LockedError(); -new restify.FailedDependencyError(); -new restify.UnorderedCollectionError(); -new restify.UpgradeRequiredError(); -new restify.PreconditionRequiredError(); -new restify.TooManyRequestsError(); -new restify.RequestHeaderFieldsTooLargeError(); -new restify.InternalServerError(); -new restify.NotImplementedError(); -new restify.BadGatewayError(); -new restify.ServiceUnavailableError(); -new restify.GatewayTimeoutError(); -new restify.HttpVersionNotSupportedError(); -new restify.VariantAlsoNegotiatesError(); -new restify.InsufficientStorageError(); -new restify.BandwidthLimitExceededError(); -new restify.NotExtendedError(); -new restify.NetworkAuthenticationRequiredError(); -new restify.RestError(); - -new restify.BadRequestError(new Error(), 'foo'); -new restify.UnauthorizedError(new Error(), 'foo'); -new restify.PaymentRequiredError(new Error(), 'foo'); -new restify.ForbiddenError(new Error(), 'foo'); -new restify.NotFoundError(new Error(), 'foo'); -new restify.MethodNotAllowedError(new Error(), 'foo'); -new restify.NotAcceptableError(new Error(), 'foo'); -new restify.ProxyAuthenticationRequiredError(new Error(), 'foo'); -new restify.RequestTimeoutError(new Error(), 'foo'); -new restify.ConflictError(new Error(), 'foo'); -new restify.GoneError(new Error(), 'foo'); -new restify.LengthRequiredError(new Error(), 'foo'); -new restify.RequestEntityTooLargeError(new Error(), 'foo'); -new restify.RequesturiTooLargeError(new Error(), 'foo'); -new restify.UnsupportedMediaTypeError(new Error(), 'foo'); -new restify.RequestedRangeNotSatisfiableError(new Error(), 'foo'); -new restify.ExpectationFailedError(new Error(), 'foo'); -new restify.ImATeapotError(new Error(), 'foo'); -new restify.UnprocessableEntityError(new Error(), 'foo'); -new restify.LockedError(new Error(), 'foo'); -new restify.FailedDependencyError(new Error(), 'foo'); -new restify.UnorderedCollectionError(new Error(), 'foo'); -new restify.UpgradeRequiredError(new Error(), 'foo'); -new restify.PreconditionRequiredError(new Error(), 'foo'); -new restify.TooManyRequestsError(new Error(), 'foo'); -new restify.RequestHeaderFieldsTooLargeError(new Error(), 'foo'); -new restify.InternalServerError(new Error(), 'foo'); -new restify.NotImplementedError(new Error(), 'foo'); -new restify.BadGatewayError(new Error(), 'foo'); -new restify.ServiceUnavailableError(new Error(), 'foo'); -new restify.GatewayTimeoutError(new Error(), 'foo'); -new restify.HttpVersionNotSupportedError(new Error(), 'foo'); -new restify.VariantAlsoNegotiatesError(new Error(), 'foo'); -new restify.InsufficientStorageError(new Error(), 'foo'); -new restify.BandwidthLimitExceededError(new Error(), 'foo'); -new restify.NotExtendedError(new Error(), 'foo'); -new restify.NetworkAuthenticationRequiredError(new Error(), 'foo'); -new restify.RestError(new Error(), 'foo'); - -new restify.PreconditionFailedError(new Error(), 'foo'); -new restify.BadDigestError(new Error(), 'foo'); -new restify.BadMethodError(new Error(), 'foo'); -new restify.InternalError(new Error(), 'foo'); -new restify.InvalidArgumentError(new Error(), 'foo'); -new restify.InvalidContentError(new Error(), 'foo'); -new restify.InvalidCredentialsError(new Error(), 'foo'); -new restify.InvalidHeaderError(new Error(), 'foo'); -new restify.InvalidVersionError(new Error(), 'foo'); -new restify.MissingParameterError(new Error(), 'foo'); -new restify.NotAuthorizedError(new Error(), 'foo'); -new restify.RequestExpiredError(new Error(), 'foo'); -new restify.RequestThrottledError(new Error(), 'foo'); -new restify.ResourceNotFoundError(new Error(), 'foo'); -new restify.WrongAcceptError(new Error(), 'foo'); - -new restify.PreconditionFailedError(); -new restify.BadDigestError(); -new restify.BadMethodError(); -new restify.InternalError(); -new restify.InvalidArgumentError(); -new restify.InvalidContentError(); -new restify.InvalidCredentialsError(); -new restify.InvalidHeaderError(); -new restify.InvalidVersionError(); -new restify.MissingParameterError(); -new restify.NotAuthorizedError(); -new restify.RequestExpiredError(); -new restify.RequestThrottledError(); -new restify.ResourceNotFoundError(); -new restify.WrongAcceptError(); - server.name = ""; -server.version = ""; -server.log = {}; +server.versions = [""]; server.acceptable = ["test"]; server.url = ""; @@ -247,19 +123,14 @@ server.address().address; server.listen("somePath", send); server.close(); -server.use(restify.acceptParser(server.acceptable)); -server.use(restify.authorizationParser()); -server.use(restify.dateParser()); -server.use(restify.queryParser()); -server.use(restify.jsonp()); -server.use(restify.gzipResponse()); -server.use(restify.bodyParser()); -server.use(restify.CORS({ - origins: ['https://foo.com', 'http://bar.com', 'http://baz.com:8081'], - credentials: true, - headers: ['x-foo'] -})); -server.use(restify.throttle({ +server.use(restify.plugins.acceptParser(server.acceptable)); +server.use(restify.plugins.authorizationParser()); +server.use(restify.plugins.dateParser()); +server.use(restify.plugins.queryParser()); +server.use(restify.plugins.jsonp()); +server.use(restify.plugins.gzipResponse()); +server.use(restify.plugins.bodyParser()); +server.use(restify.plugins.throttle({ burst: 100, rate: 50, ip: true, @@ -271,9 +142,7 @@ server.use(restify.throttle({ } })); -server.on('after', restify.auditLogger({ - log: () => { } -})); +server.on('after', restify.plugins.auditLogger({ log: {} as Logger })); server.on('after', (req: restify.Request, res: restify.Response, route: restify.Route, err: any) => { route.spec.method === 'GET'; @@ -281,67 +150,9 @@ server.on('after', (req: restify.Request, res: restify.Response, route: restify. route.spec.path === '/some/path'; route.spec.path === /\/some\/path\/.*/; route.spec.versions === ['v1']; - restify.auditLogger({ log: () => { } })(req, res, route, err); + restify.plugins.auditLogger({ log: {} as Logger })(req, res, route, err); }); ( restify).defaultResponseHeaders = function(this: restify.Request, data: any) { this.header('Server', 'helloworld'); }; - -( restify).defaultResponseHeaders = false; - -// RESTIFY Client Tests - -let client = restify.createJsonClient({ - url: 'https://api.us-west-1.joyentcloud.com', - version: '*' -}); - -client = restify.createStringClient({ - accept: "test", - connectTimeout: 30, - dtrace: {}, - gzip: {}, - headers: {}, - log: {}, - retry: {}, - signRequest: () => { }, - url: "", - userAgent: "", - version: "" -}); - -client.head('test', (err: any, req: restify.Request, res: restify.Response) => { }); -client.put('path', {}, (err: any, req: restify.Request, res: restify.Response, obj: any) => { }); -client.patch('path', {}, (err: any, req: restify.Request, res: restify.Response, obj: any) => { }); -client.del('path', (err: any, req: restify.Request, res: restify.Response) => { }); - -client.post('/foo', { hello: 'world' }, (err: any, req: restify.Request, res: restify.Response, obj: any) => { - console.log('%d -> %j', res.statusCode, res.headers); - console.log('%j', obj); -}); - -client.get('/foo/bar', (err: any, req: restify.Request, res: restify.Response, data: string) => { - console.log('%s', data); -}); - -let client2 = restify.createClient({ - url: 'http://127.0.0.1' -}); - -client2.get('/str/mcavage', (err: any, req: any) => { - req.on('result', (err: any, res: any) => { - res.body = ''; - res.setEncoding('utf8'); - res.on('data', (chunk: string) => { - res.body += chunk; - }); - - res.on('end', () => { - console.log(res.body); - }); - }); -}); - -client.basicAuth('test', 'password'); -client2.basicAuth('test', 'password'); From b106b41802534683fb74087417ab2e1caa3b0bc6 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Wed, 5 Jul 2017 11:51:47 +0100 Subject: [PATCH 0156/1618] Fix linting issues --- types/restify/index.d.ts | 130 ++++++++++++++++++--------------------- 1 file changed, 59 insertions(+), 71 deletions(-) diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index 1e440b7eb7..f0c698c4bd 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -76,7 +76,7 @@ export class Server { * @class * @param {Object} options an options object */ - new(options?: ServerOptions): Server + constructor(options?: ServerOptions); } export interface Server extends http.Server { @@ -321,7 +321,7 @@ export interface RouterOptions { } export class Router { - new(options: RouterOptions): Router; + constructor(options: RouterOptions); } export interface Router { @@ -720,14 +720,14 @@ export interface Request extends http.IncomingMessage { * method: 'GET', * versions: [], * name: 'getpingname' - } + * } * @public * @function getRoute * @returns {Object} */ getRoute(): RouteSpec; - /**bunyan logger you can piggyback on. */ + /** bunyan logger you can piggyback on. */ log: Logger; /** available when queryParser plugin is used. */ @@ -861,7 +861,7 @@ export interface Response extends http.ServerResponse { * @param {String} rel the link value * @returns {String} the header value set to res */ - link(l: string, rel: string): string + link(l: string, rel: string): string; /** * sends the response object. pass through to internal __send that uses a @@ -924,41 +924,29 @@ export interface Response extends http.ServerResponse { writeHead(): void; /** redirect is sugar method for redirecting. - * res.redirect(301, 'www.foo.com', next); - * `next` is mandatory, to complete the response and trigger audit logger. - * @public - * @param {Number} code the status code - * @param {String} url to redirect to - * @param {Function} next fn - * @emits redirect - * @function redirect - * @return {undefined} - */ + * res.redirect(301, 'www.foo.com', next); + * `next` is mandatory, to complete the response and trigger audit logger. + * @public + * @param {Number} code the status code + * @param {String} url to redirect to + * @param {Function} next fn + * @emits redirect + * @function redirect + * @return {undefined} + */ redirect(code: number, url: string, next: Next): void; /** redirect is sugar method for redirecting. - * res.redirect('www.foo.com', next); - * `next` is mandatory, to complete the response and trigger audit logger. - * @public - * @param {String} url to redirect to - * @param {Function} next fn - * @emits redirect - * @function redirect - * @return {undefined} - */ - redirect(url: string, next: Next): void; - - /** redirect is sugar method for redirecting. - * res.redirect({...}, next); - * `next` is mandatory, to complete the response and trigger audit logger. - * @public - * @param {Object} options the status code - * @param {Function} next fn - * @emits redirect - * @function redirect - * @return {undefined} - */ - redirect(options: any, next: Next): void; + * res.redirect({...}, next); + * `next` is mandatory, to complete the response and trigger audit logger. + * @public + * @param {Object | String} options the options or url to redirect to + * @param {Function} next fn + * @emits redirect + * @function redirect + * @return {undefined} + */ + redirect(options: string | any, next: Next): void; /** HTTP status code. */ code: number; @@ -1031,10 +1019,10 @@ export function createServer(options?: ServerOptions): Server; export const formatters: { [name: string]: RequestHandler -} +}; export namespace plugins { - export namespace pre { + namespace pre { /** * Provide req.set(key, val) and req.get(key) methods for setting and retrieving context to a specific request. */ @@ -1076,9 +1064,9 @@ export namespace plugins { /** * Check the client's Accept header can be handled by this server. */ - export function acceptParser(accepts: string[]): RequestHandler; + function acceptParser(accepts: string[]): RequestHandler; - export interface AuditLoggerOptions { + interface AuditLoggerOptions { /** * Bunyan logger */ @@ -1108,26 +1096,26 @@ export namespace plugins { /** * An audit logger for recording all handled requests */ - export function auditLogger(options: AuditLoggerOptions): (...args: any[]) => void; + function auditLogger(options: AuditLoggerOptions): (...args: any[]) => void; /** * Authorization header */ - export function authorizationParser(options?: any): RequestHandler; + function authorizationParser(options?: any): RequestHandler; /** * Conditional headers (If-*) */ - export function conditionalRequest(): RequestHandler[]; + function conditionalRequest(): RequestHandler[]; /** * Handles disappeared CORS headers */ - export function fullResponse(): RequestHandler; + function fullResponse(): RequestHandler; // ************ This module includes the following data parsing plugins: - export interface BodyParserOptions { + interface BodyParserOptions { /** * The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory. */ @@ -1205,14 +1193,14 @@ export namespace plugins { /** * Parses POST bodies to req.body. automatically uses one of the following parsers based on content type. */ - export function bodyParser(options?: BodyParserOptions): RequestHandler[]; + function bodyParser(options?: BodyParserOptions): RequestHandler[]; /** * Reads the body of the request. */ - export function bodyReader(options?: { maxBodySize?: number }): RequestHandler; + function bodyReader(options?: { maxBodySize?: number }): RequestHandler; - export interface UrlEncodedBodyParser { + interface UrlEncodedBodyParser { mapParams?: boolean; overrideParams?: boolean; } @@ -1223,19 +1211,19 @@ export namespace plugins { * If req.params already contains a given key, that key is skipped and an * error is logged. */ - export function urlEncodedBodyParser(options?: UrlEncodedBodyParser): RequestHandler[]; + function urlEncodedBodyParser(options?: UrlEncodedBodyParser): RequestHandler[]; /** * Parses JSON POST bodies */ - export function jsonBodyParser(options?: { mapParams?: boolean, reviver?: any, overrideParams?: boolean }): RequestHandler[]; + function jsonBodyParser(options?: { mapParams?: boolean, reviver?: any, overrideParams?: boolean }): RequestHandler[]; /** * Parses JSONP callback */ - export function jsonp(): RequestHandler; + function jsonp(): RequestHandler; - export interface MultipartBodyParser { + interface MultipartBodyParser { overrideParams?: boolean; multiples?: boolean; keepExtensions?: boolean; @@ -1251,9 +1239,9 @@ export namespace plugins { /** * Parses JSONP callback */ - export function multipartBodyParser(options?: MultipartBodyParser): RequestHandler; + function multipartBodyParser(options?: MultipartBodyParser): RequestHandler; - export interface QueryParserOptions { + interface QueryParserOptions { /** * Default `false`. Copies parsed query parameters into `req.params`. */ @@ -1304,9 +1292,9 @@ export namespace plugins { /** * Parses URL query paramters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) */ - export function queryParser(options?: QueryParserOptions): RequestHandler; + function queryParser(options?: QueryParserOptions): RequestHandler; - export interface RequestLogger { + interface RequestLogger { properties?: any; serializers?: any; headers?: any; @@ -1318,7 +1306,7 @@ export namespace plugins { * * `options.properties` properties to pass to bunyan's `log.child()` method */ - export function requestLogger(options?: RequestLogger): RequestHandler; + function requestLogger(options?: RequestLogger): RequestHandler; // ******************** The module includes the following response plugins: @@ -1326,15 +1314,15 @@ export namespace plugins { * expires requests based on current time + delta * @param delta - age in seconds */ - export function dateParser(delta?: number): RequestHandler; + function dateParser(delta?: number): RequestHandler; /** * gzips the response if client send `accept-encoding: gzip` * @param options options to pass to gzlib */ - export function gzipResponse(options?: any): RequestHandler; + function gzipResponse(options?: any): RequestHandler; - export interface ServeStatic { + interface ServeStatic { appendRequestPath?: boolean | undefined; directory?: string; maxAge?: number; @@ -1349,9 +1337,9 @@ export namespace plugins { /** * Used to serve static files */ - export function serveStatic(options?: ServeStatic): RequestHandler; + function serveStatic(options?: ServeStatic): RequestHandler; - export interface ThrottleOptions { + interface ThrottleOptions { burst?: number; rate?: number; ip?: boolean; @@ -1362,7 +1350,7 @@ export namespace plugins { overrides?: any; // any } - export interface MetricsCallback { + interface MetricsCallback { /** * An error if the request had an error */ @@ -1382,9 +1370,9 @@ export namespace plugins { route: Route; } - export type TMetricsCallback = 'close' | 'aborted' | undefined; + type TMetricsCallback = 'close' | 'aborted' | undefined; - export interface MetricsCallbackOptions { + interface MetricsCallbackOptions { /** * Status code of the response. Can be undefined in the case of an `uncaughtException`. * Otherwise, in most normal scenarios, even calling `res.send()` or `res.end()` should result in a 200 by default. @@ -1424,7 +1412,7 @@ export namespace plugins { * })); * ``` */ - export function metrics(opts: { server: Server }, callback: (options: MetricsCallback) => any): (...args: any[]) => void; + function metrics(opts: { server: Server }, callback: (options: MetricsCallback) => any): (...args: any[]) => void; /** * Parse the client's request for an OAUTH2 access tokensTable @@ -1436,14 +1424,14 @@ export namespace plugins { * } * ``` */ - export function oauth2TokenParser(): RequestHandler; + function oauth2TokenParser(): RequestHandler; /** * throttles responses */ - export function throttle(options?: ThrottleOptions): RequestHandler; + function throttle(options?: ThrottleOptions): RequestHandler; - export interface RequestExpiryOptions { + interface RequestExpiryOptions { /** * Header name of the absolute time for request expiration */ @@ -1472,7 +1460,7 @@ export namespace plugins { * * The timeout is added to the request start time to arrive at the absolute time * in which the request is considered expires */ - export function requestExpiry(options?: RequestExpiryOptions): RequestHandler; + function requestExpiry(options?: RequestExpiryOptions): RequestHandler; } export namespace pre { From 57c8843b6d2be66199a49e6d08f8c45dbcfb74c3 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Wed, 5 Jul 2017 12:02:55 +0100 Subject: [PATCH 0157/1618] Fix lint errors --- types/restify/index.d.ts | 60 ++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index f0c698c4bd..aaaa7c3a8f 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -1008,10 +1008,10 @@ export interface RouteOptions { versions?: string[]; } -type FindRouteCallback = (err: Error, route?: Route, params?: any) => void; +export type FindRouteCallback = (err: Error, route?: Route, params?: any) => void; export type RequestHandler = (req: Request, res: Response, next: Next) => any; -type RequestHandlerType = RequestHandler | RequestHandler[]; +export type RequestHandlerType = RequestHandler | RequestHandler[]; export function bunyan(options?: BunyanOptions): RequestHandler; @@ -1106,16 +1106,16 @@ export namespace plugins { /** * Conditional headers (If-*) */ - function conditionalRequest(): RequestHandler[]; + function conditionalRequest(): RequestHandler[]; /** * Handles disappeared CORS headers */ - function fullResponse(): RequestHandler; + function fullResponse(): RequestHandler; // ************ This module includes the following data parsing plugins: - interface BodyParserOptions { + interface BodyParserOptions { /** * The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory. */ @@ -1193,14 +1193,14 @@ export namespace plugins { /** * Parses POST bodies to req.body. automatically uses one of the following parsers based on content type. */ - function bodyParser(options?: BodyParserOptions): RequestHandler[]; + function bodyParser(options?: BodyParserOptions): RequestHandler[]; /** * Reads the body of the request. */ - function bodyReader(options?: { maxBodySize?: number }): RequestHandler; + function bodyReader(options?: { maxBodySize?: number }): RequestHandler; - interface UrlEncodedBodyParser { + interface UrlEncodedBodyParser { mapParams?: boolean; overrideParams?: boolean; } @@ -1211,19 +1211,19 @@ export namespace plugins { * If req.params already contains a given key, that key is skipped and an * error is logged. */ - function urlEncodedBodyParser(options?: UrlEncodedBodyParser): RequestHandler[]; + function urlEncodedBodyParser(options?: UrlEncodedBodyParser): RequestHandler[]; /** * Parses JSON POST bodies */ - function jsonBodyParser(options?: { mapParams?: boolean, reviver?: any, overrideParams?: boolean }): RequestHandler[]; + function jsonBodyParser(options?: { mapParams?: boolean, reviver?: any, overrideParams?: boolean }): RequestHandler[]; /** * Parses JSONP callback */ - function jsonp(): RequestHandler; + function jsonp(): RequestHandler; - interface MultipartBodyParser { + interface MultipartBodyParser { overrideParams?: boolean; multiples?: boolean; keepExtensions?: boolean; @@ -1239,9 +1239,9 @@ export namespace plugins { /** * Parses JSONP callback */ - function multipartBodyParser(options?: MultipartBodyParser): RequestHandler; + function multipartBodyParser(options?: MultipartBodyParser): RequestHandler; - interface QueryParserOptions { + interface QueryParserOptions { /** * Default `false`. Copies parsed query parameters into `req.params`. */ @@ -1292,9 +1292,9 @@ export namespace plugins { /** * Parses URL query paramters into `req.query`. Many options correspond directly to option defined for the underlying [qs.parse](https://github.com/ljharb/qs) */ - function queryParser(options?: QueryParserOptions): RequestHandler; + function queryParser(options?: QueryParserOptions): RequestHandler; - interface RequestLogger { + interface RequestLogger { properties?: any; serializers?: any; headers?: any; @@ -1306,7 +1306,7 @@ export namespace plugins { * * `options.properties` properties to pass to bunyan's `log.child()` method */ - function requestLogger(options?: RequestLogger): RequestHandler; + function requestLogger(options?: RequestLogger): RequestHandler; // ******************** The module includes the following response plugins: @@ -1314,15 +1314,15 @@ export namespace plugins { * expires requests based on current time + delta * @param delta - age in seconds */ - function dateParser(delta?: number): RequestHandler; + function dateParser(delta?: number): RequestHandler; /** * gzips the response if client send `accept-encoding: gzip` * @param options options to pass to gzlib */ - function gzipResponse(options?: any): RequestHandler; + function gzipResponse(options?: any): RequestHandler; - interface ServeStatic { + interface ServeStatic { appendRequestPath?: boolean | undefined; directory?: string; maxAge?: number; @@ -1337,9 +1337,9 @@ export namespace plugins { /** * Used to serve static files */ - function serveStatic(options?: ServeStatic): RequestHandler; + function serveStatic(options?: ServeStatic): RequestHandler; - interface ThrottleOptions { + interface ThrottleOptions { burst?: number; rate?: number; ip?: boolean; @@ -1350,7 +1350,7 @@ export namespace plugins { overrides?: any; // any } - interface MetricsCallback { + interface MetricsCallback { /** * An error if the request had an error */ @@ -1370,9 +1370,9 @@ export namespace plugins { route: Route; } - type TMetricsCallback = 'close' | 'aborted' | undefined; + type TMetricsCallback = 'close' | 'aborted' | undefined; - interface MetricsCallbackOptions { + interface MetricsCallbackOptions { /** * Status code of the response. Can be undefined in the case of an `uncaughtException`. * Otherwise, in most normal scenarios, even calling `res.send()` or `res.end()` should result in a 200 by default. @@ -1412,7 +1412,7 @@ export namespace plugins { * })); * ``` */ - function metrics(opts: { server: Server }, callback: (options: MetricsCallback) => any): (...args: any[]) => void; + function metrics(opts: { server: Server }, callback: (options: MetricsCallback) => any): (...args: any[]) => void; /** * Parse the client's request for an OAUTH2 access tokensTable @@ -1424,14 +1424,14 @@ export namespace plugins { * } * ``` */ - function oauth2TokenParser(): RequestHandler; + function oauth2TokenParser(): RequestHandler; /** * throttles responses */ - function throttle(options?: ThrottleOptions): RequestHandler; + function throttle(options?: ThrottleOptions): RequestHandler; - interface RequestExpiryOptions { + interface RequestExpiryOptions { /** * Header name of the absolute time for request expiration */ @@ -1460,7 +1460,7 @@ export namespace plugins { * * The timeout is added to the request start time to arrive at the absolute time * in which the request is considered expires */ - function requestExpiry(options?: RequestExpiryOptions): RequestHandler; + function requestExpiry(options?: RequestExpiryOptions): RequestHandler; } export namespace pre { From c3a65c78e2da9d345fc11a73406bad6fdfe47b20 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Wed, 5 Jul 2017 12:11:12 +0100 Subject: [PATCH 0158/1618] Remove restify require --- types/restify/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index aaaa7c3a8f..c4421ca625 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -9,7 +9,6 @@ import http = require('http'); import Logger = require('bunyan'); import url = require('url'); -import restifyPlugins = require('restify-plugins'); export interface BunyanOptions { properties: any; From 893b6d8f7c10618e1c1a2c8223126698af2f9a39 Mon Sep 17 00:00:00 2001 From: strajuser Date: Wed, 5 Jul 2017 16:43:06 +0300 Subject: [PATCH 0159/1618] - definitions for Task and ImageService --- types/esri-leaflet/esri-leaflet-tests.ts | 30 +++++++++ types/esri-leaflet/index.d.ts | 78 ++++++++++++++++++++++++ 2 files changed, 108 insertions(+) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index 25d7230593..0aa63347cb 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -297,3 +297,33 @@ mapService = new L.esri.MapService({ // .run(function(error, featureCollection, response){ // // console.log('Found GNIS ID: ' + featureCollection.features[0].properties.GNIS_ID + ' for the state of ' + featureCollection.features[0].properties.STATE_NAME); // }); + +let imageServiceOptions : L.esri.ImageServiceOptions; +let imageService: L.esri.ImageService; + +imageServiceOptions = { +}; +imageServiceOptions = { + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}; + +imageService = L.esri.imageService(imageServiceOptions); +imageService = L.esri.imageService({}); +imageService = L.esri.imageService({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +imageService = new L.esri.ImageService(imageServiceOptions); +imageService = new L.esri.ImageService({}); +imageService = new L.esri.ImageService({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index 36fadf940d..60e0f7fbaf 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -587,6 +587,84 @@ declare namespace L { * @returns {MapService} */ function mapService(options: MapServiceOptions): MapService; + + /** + * Options for Task + * + * @interface TaskOptions + * @extends {ServiceOptions} + */ + interface TaskOptions extends ServiceOptions { } + + /** + * L.esri.Task is a generic class that provides the foundation for calling operations on ArcGIS Online and ArcGIS Server Services like query, find and identify. + * + * @class Task + * @extends {L.Class} + */ + class Task extends L.Class { + constructor(options: TaskOptions | Service); + /** + * Makes a request to the associated service. The service's URL will be combined with the path option and parameters will be serialized. Accepts an optional function context for the callback. + * + * @param {string} url + * @param {*} params + * @param {*} callback + * @param {*} context + * @returns {this} + * @memberof Task + */ + request(url: string, params: any, callback: any, context: any): this; + /** + * Adds a token to this request if the service requires authentication. Will be added automatically if used with a service. + * + * @param {string} token + * @returns {this} + * @memberof Task + */ + token(token: string): this; + } + + /** + * L.esri.Task is a generic class that provides the foundation for calling operations on ArcGIS Online and ArcGIS Server Services like query, find and identify. + * + * @param {(TaskOptions | Service)} options + * @returns {Task} + */ + function task(options: TaskOptions | Service): Task; + + /** + * Options for ImageService + * + * @interface ImageServiceOptions + * @extends {ServiceOptions} + */ + interface ImageServiceOptions extends ServiceOptions {} + + /** + * L.esri.ImageService is an abstraction for interacting with Image Services running on ArcGIS Online and ArcGIS Server that allows you to make requests to the API, as well as query and identify features on the service. + * + * @class ImageService + * @extends {Service} + */ + class ImageService extends Service { + constructor(options: ImageServiceOptions); + /** + * Returns a new L.esri.Query object that can be used to query this service. + * + * @returns {this} + * @memberof ImageService + */ + query(): this; + } + + /** + * L.esri.ImageService is an abstraction for interacting with Image Services running on ArcGIS Online and ArcGIS Server that allows you to make requests to the API, as well as query and identify features on the service. + * + * @param {ImageServiceOptions} options + * @returns {ImageService} + */ + function imageService(options: ImageServiceOptions): ImageService; } } From 3a21d4634cfc2a0fed6e4a100711ee0547c93203 Mon Sep 17 00:00:00 2001 From: strajuser Date: Wed, 5 Jul 2017 17:00:06 +0300 Subject: [PATCH 0160/1618] - Definitions for FeatureLayerService --- types/esri-leaflet/esri-leaflet-tests.ts | 80 +++++++++++++++++++++++ types/esri-leaflet/index.d.ts | 83 +++++++++++++++++++++++- 2 files changed, 162 insertions(+), 1 deletion(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index 0aa63347cb..98b9147c23 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -327,3 +327,83 @@ imageService = new L.esri.ImageService({ useCors: true, timeout: 1000 }); + +let featureLayerServiceOptions : L.esri.FeatureLayerServiceOptions; +let featureLayerService: L.esri.FeatureLayerService; + +featureLayerServiceOptions = { +}; +featureLayerServiceOptions = { + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}; + +featureLayerService = L.esri.featureLayerService(featureLayerServiceOptions); +featureLayerService = L.esri.featureLayerService({}); +featureLayerService = L.esri.featureLayerService({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +featureLayerService = new L.esri.FeatureLayerService(featureLayerServiceOptions); +featureLayerService = new L.esri.FeatureLayerService({}); +featureLayerService = new L.esri.FeatureLayerService({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +// TODO: +// featureLayerService.query() +// .within(latlngbounds) +// .where("Direction = 'WEST'") +// .run(function(error, featureCollection, response){ +// // console.log(featureCollection); +// }); + +// let feature = { +// type: 'Feature', +// geometry: { +// type: 'Point', +// coordinates: [-122, 45] +// }, +// properties: { +// name: 'Hello World' +// } +// }; + +// featureLayerService.addFeature(feature, function(error, response){ +// // console.log() +// }); + +// feature2 = { +// type: 'Feature', +// id: 2, +// geometry: { +// type: 'Point', +// coordinates: [-122, 45] +// }, +// properties: { +// name: 'Hi I\'m Feature 2' +// } +// }; + +// featureLayerService.updateFeature(feature2, function(error, response){ +// // console.log() +// }); + +// featureLayerService.deleteFeature(2, function(error, response){ +// // console.log() +// }); + +// featureLayerService +// .query() +// .where("name='Hello World'") +// .run(function(error, featureCollection, response){ +// // console.log() +// }); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index 60e0f7fbaf..bf128f7336 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -614,7 +614,7 @@ declare namespace L { * @returns {this} * @memberof Task */ - request(url: string, params: any, callback: any, context: any): this; + request(url: string, params?: any, callback?: any, context?: any): this; /** * Adds a token to this request if the service requires authentication. Will be added automatically if used with a service. * @@ -665,6 +665,87 @@ declare namespace L { * @returns {ImageService} */ function imageService(options: ImageServiceOptions): ImageService; + + /** + * Options for FeatureLayerService + * + * @interface FeatureLayerServiceOptions + * @extends {ServiceOptions} + */ + interface FeatureLayerServiceOptions extends ServiceOptions { } + + /** + * L.esri.FeatureLayerService is an abstraction for interacting with Feature Layers running on ArcGIS Online and ArcGIS Server that allows you to make requests to the API, as well as query, add, update and remove features from the service. + * + * @class FeatureLayerService + * @extends {Service} + */ + class FeatureLayerService extends Service { + constructor(options: FeatureLayerServiceOptions); + /** + * Returns a new L.esri.Query object that can be used to query this layer. + * + * @returns {this} + * @memberof FeatureLayerService + */ + query(): this; + /** + * Adds a new feature to the feature layer. this also adds the feature to the map if creation is successful. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Create capability be enabled on the service. You can check if creation exists by checking the metadata of your service under capabilities. + * + * @param {GeoJSONFeature} feature + * @param {*} callback + * @param {*} context + * @returns {this} + * @memberof FeatureLayerService + */ + addFeature(feature: GeoJSONFeature, callback?: any, context?: any): this; + /** + * Update the provided feature on the Feature Layer. This also updates the feature on the map. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Update capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. + * + * @param {GeoJSONFeature} feature + * @param {*} callback + * @param {*} context + * @returns {this} + * @memberof FeatureLayerService + */ + updateFeature(feature: GeoJSONFeature, callback?: any, context?: any): this; + /** + * Remove the feature with the provided id from the feature layer. This will also remove the feature from the map if it exists. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Delete capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. + * + * @param {(string | number)} id + * @param {*} callback + * @param {*} context + * @returns {this} + * @memberof FeatureLayerService + */ + deleteFeature(id: string | number, callback?: any, context?: any): this; + /** + * Removes an array of features with the provided ids from the feature layer. This will also remove the features from the map if they exist. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Delete capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. + * + * @param {(Array)} ids + * @param {*} callback + * @param {*} context + * @returns {this} + * @memberof FeatureLayerService + */ + deleteFeatures(ids: Array, callback?: any, context?: any): this; + } + + /** + * L.esri.FeatureLayerService is an abstraction for interacting with Feature Layers running on ArcGIS Online and ArcGIS Server that allows you to make requests to the API, as well as query, add, update and remove features from the service. + * + * @param {FeatureLayerServiceOptions} options + * @returns {FeatureLayerService} + */ + function featureLayerService(options: FeatureLayerServiceOptions): FeatureLayerService; } } From 3f96c68dfe52608bf918c0b0f0fd58470e3cb25f Mon Sep 17 00:00:00 2001 From: Barrokgl Date: Wed, 5 Jul 2017 16:52:20 +0300 Subject: [PATCH 0161/1618] reapop: add definitions for module --- types/reapop/index.d.ts | 165 ++++++++++++++++++++++++++++++++++ types/reapop/reapop-tests.tsx | 38 ++++++++ types/reapop/tsconfig.json | 24 +++++ types/reapop/tslint.json | 1 + 4 files changed, 228 insertions(+) create mode 100644 types/reapop/index.d.ts create mode 100644 types/reapop/reapop-tests.tsx create mode 100644 types/reapop/tsconfig.json create mode 100644 types/reapop/tslint.json diff --git a/types/reapop/index.d.ts b/types/reapop/index.d.ts new file mode 100644 index 0000000000..54d4a46537 --- /dev/null +++ b/types/reapop/index.d.ts @@ -0,0 +1,165 @@ +// Type definitions for reapop 1.1 +// Project: https://github.com/LouisBarranqueiro/reapop#readme +// Definitions by: Barrokgl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1.1 + +import * as React from 'react'; + +/** + * Add a notification (thunk action creator) + * + * We use a thunk here to create an ADD_NOTIFICATION action + * and only return the notification object. + */ +export function addNotification(notification: Notification): Notification; + +/** + * Update a notification (thunk action creator) + * + * We use a thunk here to create an UPDATE_NOTIFICATION action + * and only return the notification object. + */ +export function updateNotification(notification: Notification): Notification; + +/** + * Remove a notification (action creator) + */ +export function removeNotification(notification: Notification): {type: string; payload: Notification}; + +/** + * Remove all notifications (action creator) + */ +export function removeNotifications(): {type: string}; + +// Action creators +interface Actions { + addNotification(notification: Notification): Notification; + updateNotification(notification: Notification): Notification; + removeNotification(notification: Notification): {type: string; payload: Notification}; + removeNotifications(): {type: string}; +} +export const actions: Actions; + +// Action types +type ADD_NOTIFICATION = string; +type UPDATE_NOTIFICATION = string; +type REMOVE_NOTIFICATION = string; +type REMOVE_NOTIFICATIONS = string; +type ActionTypes = ADD_NOTIFICATION | UPDATE_NOTIFICATION | REMOVE_NOTIFICATION | REMOVE_NOTIFICATIONS; + +interface Types { + ADD_NOTIFICATION: ADD_NOTIFICATION; + UPDATE_NOTIFICATION: UPDATE_NOTIFICATION; + REMOVE_NOTIFICATION: REMOVE_NOTIFICATION; + REMOVE_NOTIFICATIONS: REMOVE_NOTIFICATIONS; +} +export const types: Types; + +// Reducers +export type reducer = (defaultNotification?: Notification) => (state: Notification[], notification: {type: ActionTypes; payload: any}) => Notification[]; + +// Constants +type DEFAULT_STATUS = string; +type INFO_STATUS = string; +type SUCCESS_STATUS = string; +type WARNING_STATUS = string; +type ERROR_STATUS = string; +type STATUSES = DEFAULT_STATUS | INFO_STATUS | SUCCESS_STATUS | WARNING_STATUS | ERROR_STATUS; + +interface STATUS_TYPES { + default: DEFAULT_STATUS; + info: INFO_STATUS; + success: SUCCESS_STATUS; + warning: WARNING_STATUS; + error: ERROR_STATUS; +} +export const STATUS: STATUS_TYPES; + +type TOP = string; +type TOP_CENTER = string; +type TOP_LEFT_POSITION = string; +type TOP_RIGHT_POSITION = string; +type BOTTOM = string; +type BOTTOM_CENTER = string; +type BOTTOM_LEFT_POSITION = string; +type BOTTOM_RIGHT_POSITION = string; +type POSITION = TOP | TOP_CENTER | TOP_LEFT_POSITION | TOP_RIGHT_POSITION | BOTTOM | BOTTOM_CENTER | BOTTOM_LEFT_POSITION | BOTTOM_RIGHT_POSITION; + +interface POSITIONS_TYPES { + top: TOP; + topCenter: TOP_CENTER; + topLeft: TOP_LEFT_POSITION; + topRight: TOP_RIGHT_POSITION; + bottom: BOTTOM; + bottomCenter: BOTTOM_CENTER; + bottomLeft: BOTTOM_LEFT_POSITION; + bottomRight: BOTTOM_RIGHT_POSITION; +} +export const POSITIONS: POSITIONS_TYPES; + +interface Button { + name: string; + primary: boolean; + onClick(): void; +} + +export interface Notification { + id?: string|number; + title?: string; + message?: string; + image?: string; + status?: string|number|STATUSES; + position?: string|POSITION; + dismissible?: boolean; + dismissAfter?: number; + closeButton?: boolean; + buttons?: Button[]; + onAdd?(): void; + onRemove?(): void; + allowHTML?: boolean; +} + +// default value for notifications +export const DEFAULT_NOTIFICATION: Notification; + +export interface NotificationSystemTheme { + smallScreenMin?: number; + notificationsSystem?: { + className?: string; + }; + notificationsContainerClassName?: { + main?: string; + position?(position: string): string; + }; + notificationsContainerTransition?: { + enterTimeout?: number; + leaveTimeout?: number; + name?: any; + }; + notificationClassName?: { + wrapper?: string; + main?: string; + meta?: string; + title?: string; + message?: string; + icon?: string; + imageContainer?: string; + image?: string; + status?(status: string): string; + dismissible?: string; + closeButtonContainer?(): string; + closeButton?(): string; + buttons?(): string; + button?: string; + buttonText?: string; + }; +} + +export interface NotificationSystemProps { + theme: NotificationSystemTheme; + filter?(notification: Notification): boolean; +} + +declare class NotificationSystem extends React.Component {} +export default NotificationSystem; diff --git a/types/reapop/reapop-tests.tsx b/types/reapop/reapop-tests.tsx new file mode 100644 index 0000000000..d2dc72e7a7 --- /dev/null +++ b/types/reapop/reapop-tests.tsx @@ -0,0 +1,38 @@ +import * as React from 'react'; +import NotificationSystem, { + addNotification, + updateNotification, + removeNotification, + removeNotifications, + POSITIONS, + reducer, + Notification, + STATUS +} from 'reapop'; + +const theme = { + smallScreenMin: 1000 +}; + +const filter = (notification: Notification) => + notification.title !== 'super-title'; + +let test = ( + +); + +const notification: Notification = { + title: 'some-title', + message: 'message', + status: STATUS.info, + position: POSITIONS.top, + onAdd: () => console.log('on add') +}; + +addNotification(notification); +updateNotification(notification); +removeNotification(notification); +removeNotifications(); diff --git a/types/reapop/tsconfig.json b/types/reapop/tsconfig.json new file mode 100644 index 0000000000..4c80369b31 --- /dev/null +++ b/types/reapop/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "reapop-tests.tsx" + ] +} diff --git a/types/reapop/tslint.json b/types/reapop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/reapop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bce9bc2d660cf953f88f7aa5be65323beee7923b Mon Sep 17 00:00:00 2001 From: Hisham Al-Shurafa Date: Wed, 5 Jul 2017 11:35:04 -0600 Subject: [PATCH 0162/1618] added newly supported optional 'names' argument in chart.load method - see https://github.com/c3js/c3/issues/978 --- c3/c3.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/c3/c3.d.ts b/c3/c3.d.ts index e815b44391..f2dbf1051e 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -824,6 +824,7 @@ declare namespace c3 { keys?: { x?: string; value: Array; } rows?: Array; columns?: Array; + names?: { [key: string]: string }; classes?: { [key: string]: string }; categories?: Array; axes?: { [key: string]: string }; From a975ba1926441bca6306027617bcaaed36492874 Mon Sep 17 00:00:00 2001 From: Michiel de Bruijne Date: Wed, 5 Jul 2017 19:47:24 +0200 Subject: [PATCH 0163/1618] enable autodetection for number of processes when running test --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index c2fef9b679..581aae5b75 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "scripts": { "compile-scripts": "tsc -p scripts", "not-needed": "node scripts/not-needed.js", - "test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 8", + "test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed", "lint": "dtslint types" }, "devDependencies": { From 205aa683dcf659c51e0111e556cd188e46788f6a Mon Sep 17 00:00:00 2001 From: Drew Hays Date: Wed, 5 Jul 2017 10:31:06 -0700 Subject: [PATCH 0164/1618] Add types for next.js --- types/next/index.d.ts | 162 +++++++++++++++++++++++ types/next/next-tests.ts | 54 ++++++++ types/next/tests/next-document-tests.tsx | 12 ++ types/next/tests/next-dynamic-tests.tsx | 23 ++++ types/next/tests/next-error-tests.tsx | 6 + types/next/tests/next-head-tests.tsx | 9 ++ types/next/tests/next-link-tests.tsx | 13 ++ types/next/tests/next-router-tests.tsx | 50 +++++++ types/next/tsconfig.json | 31 +++++ types/next/tslint.json | 18 +++ 10 files changed, 378 insertions(+) create mode 100644 types/next/index.d.ts create mode 100644 types/next/next-tests.ts create mode 100644 types/next/tests/next-document-tests.tsx create mode 100644 types/next/tests/next-dynamic-tests.tsx create mode 100644 types/next/tests/next-error-tests.tsx create mode 100644 types/next/tests/next-head-tests.tsx create mode 100644 types/next/tests/next-link-tests.tsx create mode 100644 types/next/tests/next-router-tests.tsx create mode 100644 types/next/tsconfig.json create mode 100644 types/next/tslint.json diff --git a/types/next/index.d.ts b/types/next/index.d.ts new file mode 100644 index 0000000000..ab57dd6241 --- /dev/null +++ b/types/next/index.d.ts @@ -0,0 +1,162 @@ +// Type definitions for next +// Project: https://github.com/zeit/next.js +// Definitions by: Drew Hays +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'next' { + import * as http from 'http'; + import * as url from 'url'; + + type UrlLike = url.UrlObject | url.Url; + + interface ServerConfig { + // known keys + webpack?: any; + webpackDevMiddleware?: any; + poweredByHeader?: boolean; + distDir?: string; + assetPrefix?: string; + configOrigin?: string; + useFileSystemPublicRoutes?: boolean; + + // and since this is a config, it can take anything else, too. + [key: string]: any; + } + + interface ServerOptions { + dir?: string; + dev?: boolean; + staticMarkup?: boolean; + quiet?: boolean; + conf?: ServerConfig; + } + + interface Server { + handleRequest(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl?: UrlLike): Promise; + getRequestHandler(): (req: http.IncomingMessage, res: http.ServerResponse, parsedUrl?: UrlLike) => Promise; + prepare(): Promise; + close(): Promise; + defineRoutes(): Promise; + start(): Promise; + run(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; + + render(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}, parsedUrl: UrlLike): Promise; + renderError(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}): Promise; + render404(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; + renderToHTML(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}): Promise; + renderErrorToHTML(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}): Promise; + + serveStatic(req: http.IncomingMessage, res: http.ServerResponse, path: string): Promise; + isServeableUrl(path: string): boolean; + isInternalUrl(req: http.IncomingMessage): boolean; + readBuildId(): string; + handleBuildId(buildId: string, res: http.ServerResponse): boolean; + getCompilationError(page: string, req: http.IncomingMessage, res: http.ServerResponse): Promise; + handleBuildHash(filename: string, hash: string, res: http.ServerResponse): void; + send404(res: http.ServerResponse): void; + } + + export default function(options?: ServerOptions): Server; +} + +declare module 'next/error' { + import * as React from 'react'; + export default class extends React.Component<{statusCode: number}, {}> {} +} + +declare module 'next/head' { + import * as React from 'react'; + function defaultHead(): JSX.Element[]; + export default class extends React.Component<{}, {}> {} +} + +declare module 'next/document' { + interface DocumentProps { + __NEXT_DATA__?: any; + dev?: boolean; + chunks?: string[]; + head?: Array>; + styles?: Array>; + [key: string]: any; + } + + class Head extends React.Component {} + class Main extends React.Component<{}, {}> {} + class NextScript extends React.Component<{}, {}> {} + export default class extends React.Component {} +} + +declare module 'next/link' { + import * as url from 'url'; + type UrlLike = url.UrlObject | url.Url; + interface LinkState { + prefetch?: boolean; + shallow?: boolean; + scroll?: boolean; + replace?: boolean; + onError?(error: any): void; + href?: string | UrlLike; + as?: string | UrlLike; + children: React.ReactElement; + } + + export default class extends React.Component {} +} + +declare module 'next/dynamic' { + interface DynamicOptions { + loading?: React.ComponentType; + ssr?: boolean; + modules?(props: TCProps & TLProps): { [key: string]: Promise> }; + render?(props: TCProps & TLProps, modules: { [key: string]: React.ComponentType }): void; + } + + class SameLoopPromise extends Promise { + constructor(executor: (resolve: (value?: T) => void, reject: (reason?: any) => void) => void); + setResult(value: T): void; + setError(value: any): void; + runIfNeeded(): void; + } + export default function(componentPromise: Promise>, options?: DynamicOptions): React.ComponentType; +} + +declare module 'next/router' { + import * as url from 'url'; + + interface EventChangeOptions { + shallow?: boolean; + [key: string]: any; + } + + type RouterCallback = () => void; + interface SingletonRouter { + readyCallbacks: RouterCallback[]; + ready(cb: RouterCallback): void; + + // router properties + readonly components: { [key: string]: { Component: React.ComponentType, err: any } }; + readonly pathname: string; + readonly route: string; + readonly asPath: string; + readonly query: { [key: string]: any }; + + // router methods + reload(route: string): Promise; + back(): void; + push(url: string, as?: string, options?: EventChangeOptions): Promise; + replace(url: string, as?: string, options?: EventChangeOptions): Promise; + prefetch(url: string): Promise>; + + // router events + onAppUpdated?(nextRoute: string): void; + onRouteChangeStart?(url: string): void; + onBeforeHistoryChange?(as: string): void; + onRouteChangeComplete?(url: string): void; + onRouteChangeError?(error: any, url: string): void; + } + + const Singleton: SingletonRouter; + export default Singleton; +} diff --git a/types/next/next-tests.ts b/types/next/next-tests.ts new file mode 100644 index 0000000000..3c216d770d --- /dev/null +++ b/types/next/next-tests.ts @@ -0,0 +1,54 @@ +import createServer from 'next'; +import * as http from 'http'; +import * as url from 'url'; + +const defaultServer = createServer(); +const server = createServer({ + dir: '..', + quiet: true, + conf: { + distDir: './dist', + useFileSystemPublicRoutes: false, + anotherProperty: { + key: true + } + } +}); + +const voidFunc = () => {}; +const stringFunc = (x: string) => x.split('\n'); + +server.prepare().then(voidFunc); +server.close().then(voidFunc); +server.defineRoutes().then(voidFunc); +server.start().then(voidFunc); + +const parsedUrl = url.parse('https://www.example.com'); +const req: http.IncomingMessage = null; +const res: http.ServerResponse = null; +const handler = server.getRequestHandler(); + +handler(req, res); +handler(req, res, parsedUrl).then(voidFunc); +server.run(req, res, parsedUrl).then(voidFunc); + +server.render(req, res, '/path/to/resource', null, parsedUrl).then(voidFunc); +server.render(req, res, '/path/to/resource', { key: 'value' }, parsedUrl).then(voidFunc); +server.renderError(new Error(), req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); +server.renderError('this can be an error, too!', req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); +server.render404(req, res, parsedUrl).then(voidFunc); + +server.renderToHTML(req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); +server.renderErrorToHTML(new Error(), req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); + +server.serveStatic(req, res, '/path/to/thing').then(voidFunc); + +let b: boolean; +b = server.isServeableUrl('/path/to/thing'); +b = server.isInternalUrl(req); +b = server.handleBuildId('{buildId}', res); + +const s: string = server.readBuildId(); +server.getCompilationError('page', req, res).then(err => err.thisIsAnAny); +server.handleBuildHash('filename', 'hash', res); +server.send404(res); diff --git a/types/next/tests/next-document-tests.tsx b/types/next/tests/next-document-tests.tsx new file mode 100644 index 0000000000..4fbb25948b --- /dev/null +++ b/types/next/tests/next-document-tests.tsx @@ -0,0 +1,12 @@ +import Document, * as document from 'next/document'; +import * as React from 'react'; + +const results = ( + + + + + + + +); diff --git a/types/next/tests/next-dynamic-tests.tsx b/types/next/tests/next-dynamic-tests.tsx new file mode 100644 index 0000000000..be10954de9 --- /dev/null +++ b/types/next/tests/next-dynamic-tests.tsx @@ -0,0 +1,23 @@ +import dynamic, * as d from 'next/dynamic'; +import * as React from 'react'; + +// typically you'd use this with an esnext-style import() statement, but we'll make do without +interface DynamicComponentProps { + foo: string; + bar: number; +} +async function getComponent() { + return ( + (props: DynamicComponentProps) =>
I'm an async component! {props.foo} {props.bar}
+ ); +} + +interface LoadingComponentProps { + baz: boolean; +} + +const DynamicComponent = dynamic(getComponent(), { + loading: (props: LoadingComponentProps) =>
Loading! {props.baz}
+}); + +const jsx = (); diff --git a/types/next/tests/next-error-tests.tsx b/types/next/tests/next-error-tests.tsx new file mode 100644 index 0000000000..38692ac6de --- /dev/null +++ b/types/next/tests/next-error-tests.tsx @@ -0,0 +1,6 @@ +import * as React from 'react'; +import ErrorComponent from 'next/error'; + +const result = ( + +); diff --git a/types/next/tests/next-head-tests.tsx b/types/next/tests/next-head-tests.tsx new file mode 100644 index 0000000000..eaf6754b49 --- /dev/null +++ b/types/next/tests/next-head-tests.tsx @@ -0,0 +1,9 @@ +import Head, * as head from 'next/head'; +import * as React from 'react'; + +const elements: JSX.Element[] = head.defaultHead(); +const jsx = ( + + {elements} + +); diff --git a/types/next/tests/next-link-tests.tsx b/types/next/tests/next-link-tests.tsx new file mode 100644 index 0000000000..281c6aff7a --- /dev/null +++ b/types/next/tests/next-link-tests.tsx @@ -0,0 +1,13 @@ +import Link from 'next/link'; +import * as React from 'react'; + +const links = ( +
+ { console.log("Handled error!", e); }} prefetch replace scroll shallow> + Gotta link to somewhere! + + + All props are optional! + +
+); diff --git a/types/next/tests/next-router-tests.tsx b/types/next/tests/next-router-tests.tsx new file mode 100644 index 0000000000..38d091dcc2 --- /dev/null +++ b/types/next/tests/next-router-tests.tsx @@ -0,0 +1,50 @@ +import Router, * as r from 'next/router'; +import * as React from 'react'; +import * as qs from 'querystring'; + +Router.readyCallbacks.push(() => { console.log("I'll get called when the router initializes."); }); +Router.ready(() => { console.log("I'll get called immediately if the router initializes, or when it eventually does."); }); + +// Access readonly properties of the router. + +Object.keys(Router.components).forEach(key => { + const c = Router.components[key]; + c.err.isAnAny; + + return ; +}); + +function split(routeLike: string) { + routeLike.split('/').forEach(part => { + console.log("path part: ", part); + }); +} + +split(Router.pathname); +split(Router.asPath); +split(Router.asPath); + +const query = `?${qs.stringify(Router.query)}`; + +// Assign some callback methods. +Router.onAppUpdated = (nextRoute: string) => console.log(nextRoute); +Router.onRouteChangeStart = (url: string) => console.log("Route is starting to change.", url); +Router.onBeforeHistoryChange = (as: string) => console.log("History hasn't changed yet.", as); +Router.onRouteChangeComplete = (url: string) => console.log("Route chaneg is complete.", url); +Router.onRouteChangeError = (err: any, url: string) => console.log("Route is starting to change.", url, err); + +// Call methods on the router itself. +Router.reload('/route').then(() => console.log('route was reloaded')); +Router.back(); + +Router.push('/route').then((success: boolean) => console.log('route push success: ', success)); +Router.push('/route', '/asRoute').then((success: boolean) => console.log('route push success: ', success)); +Router.push('/route', '/asRoute', {shallow: false}).then((success: boolean) => console.log('route push success: ', success)); + +Router.replace('/route').then((success: boolean) => console.log('route replace success: ', success)); +Router.replace('/route', '/asRoute').then((success: boolean) => console.log('route replace success: ', success)); +Router.replace('/route', '/asRoute', {shallow: false}).then((success: boolean) => console.log('route replace success: ', success)); + +Router.prefetch('/route').then(Component => { + const element = (); +}); diff --git a/types/next/tsconfig.json b/types/next/tsconfig.json new file mode 100644 index 0000000000..7cd8fc1ee6 --- /dev/null +++ b/types/next/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "next-tests.ts", + "tests/next-error-tests.tsx", + "tests/next-head-tests.tsx", + "tests/next-document-tests.tsx", + "tests/next-link-tests.tsx", + "tests/next-dynamic-tests.tsx", + "tests/next-router-tests.tsx" + ] +} diff --git a/types/next/tslint.json b/types/next/tslint.json new file mode 100644 index 0000000000..bf0deaa9f4 --- /dev/null +++ b/types/next/tslint.json @@ -0,0 +1,18 @@ +{ + "extends": "dtslint/dtslint.json", + "rules": { + // All of the different "export default" lines in the index.d.ts + // appear to be triggering this. Remove this when I know of a way + // to declare a default export across multiple packages. + "strict-export-declare-modifiers": false, + + // This is a pretty generic one to have to ignore, but it's because + // of the following error: + // `JSX element type '' does not have any construct or call signatures.` + // In all cases, the element's type is "React.ComponentType`, which is composed of either: + // - React.StatelessComponent, which has a call signature, or + // - React.ComponentClass, which as a construct signature. + // This seems like it might be a bug. + "expect": false + } +} From d12e78563cff4e53d2909cc6347b443eee9d0918 Mon Sep 17 00:00:00 2001 From: Drew Hays Date: Wed, 5 Jul 2017 11:28:43 -0700 Subject: [PATCH 0165/1618] follow pull request template --- types/next/tsconfig.json | 2 +- types/next/tslint.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/next/tsconfig.json b/types/next/tsconfig.json index 7cd8fc1ee6..b5476f610a 100644 --- a/types/next/tsconfig.json +++ b/types/next/tsconfig.json @@ -9,7 +9,7 @@ "jsx": "react", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/next/tslint.json b/types/next/tslint.json index bf0deaa9f4..71bde7f0b6 100644 --- a/types/next/tslint.json +++ b/types/next/tslint.json @@ -3,7 +3,7 @@ "rules": { // All of the different "export default" lines in the index.d.ts // appear to be triggering this. Remove this when I know of a way - // to declare a default export across multiple packages. + // to declare a default export across multiple package/subpackages. "strict-export-declare-modifiers": false, // This is a pretty generic one to have to ignore, but it's because From f7bf7985530eb341cb0abed3e1921ffe0de6aa2f Mon Sep 17 00:00:00 2001 From: Drew Hays Date: Wed, 5 Jul 2017 11:43:50 -0700 Subject: [PATCH 0166/1618] passes tests now --- types/next/index.d.ts | 2 +- types/next/{tests => test}/next-document-tests.tsx | 0 types/next/{tests => test}/next-dynamic-tests.tsx | 0 types/next/{tests => test}/next-error-tests.tsx | 0 types/next/{tests => test}/next-head-tests.tsx | 0 types/next/{tests => test}/next-link-tests.tsx | 0 types/next/{tests => test}/next-router-tests.tsx | 0 types/next/tsconfig.json | 12 ++++++------ types/next/tslint.json | 2 +- 9 files changed, 8 insertions(+), 8 deletions(-) rename types/next/{tests => test}/next-document-tests.tsx (100%) rename types/next/{tests => test}/next-dynamic-tests.tsx (100%) rename types/next/{tests => test}/next-error-tests.tsx (100%) rename types/next/{tests => test}/next-head-tests.tsx (100%) rename types/next/{tests => test}/next-link-tests.tsx (100%) rename types/next/{tests => test}/next-router-tests.tsx (100%) diff --git a/types/next/index.d.ts b/types/next/index.d.ts index ab57dd6241..51024ffc8f 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for next +// Type definitions for next 2.4 // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/next/tests/next-document-tests.tsx b/types/next/test/next-document-tests.tsx similarity index 100% rename from types/next/tests/next-document-tests.tsx rename to types/next/test/next-document-tests.tsx diff --git a/types/next/tests/next-dynamic-tests.tsx b/types/next/test/next-dynamic-tests.tsx similarity index 100% rename from types/next/tests/next-dynamic-tests.tsx rename to types/next/test/next-dynamic-tests.tsx diff --git a/types/next/tests/next-error-tests.tsx b/types/next/test/next-error-tests.tsx similarity index 100% rename from types/next/tests/next-error-tests.tsx rename to types/next/test/next-error-tests.tsx diff --git a/types/next/tests/next-head-tests.tsx b/types/next/test/next-head-tests.tsx similarity index 100% rename from types/next/tests/next-head-tests.tsx rename to types/next/test/next-head-tests.tsx diff --git a/types/next/tests/next-link-tests.tsx b/types/next/test/next-link-tests.tsx similarity index 100% rename from types/next/tests/next-link-tests.tsx rename to types/next/test/next-link-tests.tsx diff --git a/types/next/tests/next-router-tests.tsx b/types/next/test/next-router-tests.tsx similarity index 100% rename from types/next/tests/next-router-tests.tsx rename to types/next/test/next-router-tests.tsx diff --git a/types/next/tsconfig.json b/types/next/tsconfig.json index b5476f610a..0bcbd622d9 100644 --- a/types/next/tsconfig.json +++ b/types/next/tsconfig.json @@ -21,11 +21,11 @@ "files": [ "index.d.ts", "next-tests.ts", - "tests/next-error-tests.tsx", - "tests/next-head-tests.tsx", - "tests/next-document-tests.tsx", - "tests/next-link-tests.tsx", - "tests/next-dynamic-tests.tsx", - "tests/next-router-tests.tsx" + "test/next-error-tests.tsx", + "test/next-head-tests.tsx", + "test/next-document-tests.tsx", + "test/next-link-tests.tsx", + "test/next-dynamic-tests.tsx", + "test/next-router-tests.tsx" ] } diff --git a/types/next/tslint.json b/types/next/tslint.json index 71bde7f0b6..e4a2c8f088 100644 --- a/types/next/tslint.json +++ b/types/next/tslint.json @@ -1,5 +1,5 @@ { - "extends": "dtslint/dtslint.json", + "extends": "dtslint/dt.json", "rules": { // All of the different "export default" lines in the index.d.ts // appear to be triggering this. Remove this when I know of a way From e97722eb0ee7295e97697c2823b46a17ff404d9f Mon Sep 17 00:00:00 2001 From: Drew Hays Date: Wed, 5 Jul 2017 12:30:20 -0700 Subject: [PATCH 0167/1618] fix "expect" in tslint --- types/next/index.d.ts | 16 +++++++++------ types/next/next-tests.ts | 42 ++++++++++++++++++++-------------------- types/next/tslint.json | 11 +---------- 3 files changed, 32 insertions(+), 37 deletions(-) diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 51024ffc8f..7f8eb6b18f 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/zeit/next.js // Definitions by: Drew Hays // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -106,11 +107,13 @@ declare module 'next/link' { } declare module 'next/dynamic' { + type ComponentType = React.StatelessComponent | typeof React.Component; + interface DynamicOptions { - loading?: React.ComponentType; + loading?: ComponentType; ssr?: boolean; - modules?(props: TCProps & TLProps): { [key: string]: Promise> }; - render?(props: TCProps & TLProps, modules: { [key: string]: React.ComponentType }): void; + modules?(props: TCProps & TLProps): { [key: string]: Promise> }; + render?(props: TCProps & TLProps, modules: { [key: string]: ComponentType }): void; } class SameLoopPromise extends Promise { @@ -119,11 +122,12 @@ declare module 'next/dynamic' { setError(value: any): void; runIfNeeded(): void; } - export default function(componentPromise: Promise>, options?: DynamicOptions): React.ComponentType; + export default function(componentPromise: Promise>, options?: DynamicOptions): ComponentType; } declare module 'next/router' { import * as url from 'url'; + type ComponentType = React.StatelessComponent | typeof React.Component; interface EventChangeOptions { shallow?: boolean; @@ -136,7 +140,7 @@ declare module 'next/router' { ready(cb: RouterCallback): void; // router properties - readonly components: { [key: string]: { Component: React.ComponentType, err: any } }; + readonly components: { [key: string]: { Component: ComponentType, err: any } }; readonly pathname: string; readonly route: string; readonly asPath: string; @@ -147,7 +151,7 @@ declare module 'next/router' { back(): void; push(url: string, as?: string, options?: EventChangeOptions): Promise; replace(url: string, as?: string, options?: EventChangeOptions): Promise; - prefetch(url: string): Promise>; + prefetch(url: string): Promise>; // router events onAppUpdated?(nextRoute: string): void; diff --git a/types/next/next-tests.ts b/types/next/next-tests.ts index 3c216d770d..bfa93bfff8 100644 --- a/types/next/next-tests.ts +++ b/types/next/next-tests.ts @@ -24,31 +24,31 @@ server.defineRoutes().then(voidFunc); server.start().then(voidFunc); const parsedUrl = url.parse('https://www.example.com'); -const req: http.IncomingMessage = null; -const res: http.ServerResponse = null; const handler = server.getRequestHandler(); -handler(req, res); -handler(req, res, parsedUrl).then(voidFunc); -server.run(req, res, parsedUrl).then(voidFunc); +function handle(req: http.IncomingMessage, res: http.ServerResponse) { + handler(req, res); + handler(req, res, parsedUrl).then(voidFunc); + server.run(req, res, parsedUrl).then(voidFunc); -server.render(req, res, '/path/to/resource', null, parsedUrl).then(voidFunc); -server.render(req, res, '/path/to/resource', { key: 'value' }, parsedUrl).then(voidFunc); -server.renderError(new Error(), req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); -server.renderError('this can be an error, too!', req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); -server.render404(req, res, parsedUrl).then(voidFunc); + server.render(req, res, '/path/to/resource', {}, parsedUrl).then(voidFunc); + server.render(req, res, '/path/to/resource', { key: 'value' }, parsedUrl).then(voidFunc); + server.renderError(new Error(), req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); + server.renderError('this can be an error, too!', req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); + server.render404(req, res, parsedUrl).then(voidFunc); -server.renderToHTML(req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); -server.renderErrorToHTML(new Error(), req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); + server.renderToHTML(req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); + server.renderErrorToHTML(new Error(), req, res, '/path/to/resource', { foo: 'bar' }).then(x => x.split('\n')); -server.serveStatic(req, res, '/path/to/thing').then(voidFunc); + server.serveStatic(req, res, '/path/to/thing').then(voidFunc); -let b: boolean; -b = server.isServeableUrl('/path/to/thing'); -b = server.isInternalUrl(req); -b = server.handleBuildId('{buildId}', res); + let b: boolean; + b = server.isServeableUrl('/path/to/thing'); + b = server.isInternalUrl(req); + b = server.handleBuildId('{buildId}', res); -const s: string = server.readBuildId(); -server.getCompilationError('page', req, res).then(err => err.thisIsAnAny); -server.handleBuildHash('filename', 'hash', res); -server.send404(res); + const s: string = server.readBuildId(); + server.getCompilationError('page', req, res).then(err => err.thisIsAnAny); + server.handleBuildHash('filename', 'hash', res); + server.send404(res); +} diff --git a/types/next/tslint.json b/types/next/tslint.json index e4a2c8f088..98f9451050 100644 --- a/types/next/tslint.json +++ b/types/next/tslint.json @@ -4,15 +4,6 @@ // All of the different "export default" lines in the index.d.ts // appear to be triggering this. Remove this when I know of a way // to declare a default export across multiple package/subpackages. - "strict-export-declare-modifiers": false, - - // This is a pretty generic one to have to ignore, but it's because - // of the following error: - // `JSX element type '' does not have any construct or call signatures.` - // In all cases, the element's type is "React.ComponentType`, which is composed of either: - // - React.StatelessComponent, which has a call signature, or - // - React.ComponentClass, which as a construct signature. - // This seems like it might be a bug. - "expect": false + "strict-export-declare-modifiers": false } } From 66ad5828444918fa3c68ff4a62d3081e41ae8ffc Mon Sep 17 00:00:00 2001 From: strajuser Date: Thu, 6 Jul 2017 08:54:31 +0300 Subject: [PATCH 0168/1618] - definitions for Query --- types/esri-leaflet/esri-leaflet-tests.ts | 55 ++++++ types/esri-leaflet/index.d.ts | 223 +++++++++++++++++++++++ 2 files changed, 278 insertions(+) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index 98b9147c23..4ce706b9a4 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -407,3 +407,58 @@ featureLayerService = new L.esri.FeatureLayerService({ // .run(function(error, featureCollection, response){ // // console.log() // }); + +let queryOptions: L.esri.QueryOptions; +let query: L.esri.Query; + +queryOptions = { +}; +queryOptions = { + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}; + +query = L.esri.query(queryOptions); +query = L.esri.query({}); +query = L.esri.query({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +query = new L.esri.Query(queryOptions); +query = new L.esri.Query({}); +query = new L.esri.Query({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +query.within(latlngbounds); +query.run(function(error, featureCollection, response){ + // console.log('Found ' + featureCollection.features.length + ' features'); +}); +query.bounds(function(error, latLngBounds, response){ + // map.fitBounds(latLngBounds); +}); + +query.nearby(latlng, 500); +query.run(function(error, featureCollection, response){ + // console.log('Found ' + featureCollection.features.length + ' features'); +}); + +query.nearby(latlng, 2000).where("direction='East'").orderBy('stop_id', 'ASC'); +query.count(function(error, count, response){ + // console.log('Found ' + count + ' features'); +}); +query.ids(function(error, ids, response){ + // console.log(ids.join(', ') + 'match the provided parameters'); +}); + +query.where("zone_id='B'").bounds(function(error, latLngBounds, response){ + // map.fitBounds(latLngBounds); +}); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index bf128f7336..f085f4f17c 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -58,6 +58,10 @@ declare namespace L { | 'ImageryTransportation' | 'ShadedReliefLabels' | 'TerrainLabels'; + + type LeafletGeometry = L.Marker | L.Polygon | L.Polyline | L.LatLng | L.LatLngBounds | L.GeoJSON; + type GeoJSONGeometry = GeoJSON.Point | GeoJSON.Polygon | GeoJSON.LineString; + type Geometry = LeafletGeometry | GeoJSONGeometry; /** * Options for L.esri.BasemapLayer @@ -457,6 +461,8 @@ declare namespace L { declare namespace L { namespace esri { + type FeatureCallbackHandlerFn = (error?: any, featureCollection?: any, response?: any) => void; + /** * Options for L.esri.Service * @@ -746,6 +752,223 @@ declare namespace L { * @returns {FeatureLayerService} */ function featureLayerService(options: FeatureLayerServiceOptions): FeatureLayerService; + + /** + * Options for Query + * + * @interface QueryOptions + * @extends {TaskOptions} + */ + interface QueryOptions extends TaskOptions { } + + /** + * L.esri.Query is an abstraction for the query API included in Feature Layers and Image Services. It provides a chainable API for building request parameters and executing queries. + * Note Depending on the type of service you are querying (Feature Layer, Map Service, Image Service) and the version of ArcGIS Server that hosts the service some of these options may not be available. + * + * @class Query + * @extends {Task} + */ + class Query extends Task { + constructor(options: QueryOptions); + /** + * Queries features from the service within (fully contained by) the passed geometry object. geometry can be an instance of L.Marker, L.Polygon, L.Polyline, L.LatLng, L.LatLngBounds and L.GeoJSON. It can also accept valid GeoJSON Point, Polyline, Polygon objects and GeoJSON Feature objects containing Point, Polyline, Polygon. + * + * @param {Geometry} geometry + * @returns {this} + * @memberof Query + */ + within(geometry: Geometry): this; + /** + * Queries features from the service that fully contain the passed geometry object. geometry can be an instance of L.Marker, L.Polygon, L.Polyline, L.LatLng, L.LatLngBounds and L.GeoJSON. It can also accept valid GeoJSON Point, Polyline, Polygon objects and GeoJSON Feature objects containing Point, Polyline, Polygon. + * + * @param {Geometry} geometry + * @returns {this} + * @memberof Query + */ + contains(geometry: Geometry): this; + /** + * Queries features from the service that intersect (touch anywhere) the passed geometry object. geometry can be an instance of L.Marker, L.Polygon, L.Polyline, L.LatLng, L.LatLngBounds and L.GeoJSON. It can also accept valid GeoJSON Point, Polyline, Polygon objects and GeoJSON Feature objects containing Point, Polyline, Polygon. + * + * @param {Geometry} geometry + * @returns {this} + * @memberof Query + */ + intersects(geometry: Geometry): this; + /** + * Queries features from the service that have a bounding box that intersects the bounding box of the passed geometry object. geometry can be an instance of L.Marker, L.Polygon, L.Polyline, L.LatLng, L.LatLngBounds and L.GeoJSON. It can also accept valid GeoJSON Point, Polyline, Polygon objects and GeoJSON Feature objects containing Point, Polyline, Polygon. + * + * @param {Geometry} geometry + * @returns {this} + * @memberof Query + */ + bboxIntersects(geometry: Geometry): this; + /** + * Queries features from the service that overlap (touch but are not fully contained by) the passed geometry object. geometry can be an instance of L.Marker, L.Polygon, L.Polyline, L.LatLng, L.LatLngBounds and L.GeoJSON. It can also accept valid GeoJSON Point, Polyline, Polygon objects and GeoJSON Feature objects containing Point, Polyline, Polygon. + * + * @param {Geometry} geometry + * @returns {this} + * @memberof Query + */ + overlap(geometry: Geometry): this; + /** + * Queries features a given distance in meters around a LatLng. + * Only available for Feature Layers hosted on ArcGIS Online or ArcGIS Server 10.3 that include the capability supportQueryWithDistance. + * + * @param {L.LatLng} latlng + * @param {number} distance + * @returns {this} + * @memberof Query + */ + nearby(latlng: L.LatLng, distance: number): this; + /** + * Adds a where clause to the query. String values should be denoted using single quotes ie: query.where("FIELDNAME = 'field value'"); More info about valid SQL can be found here. + * + * @param {string} where + * @returns {this} + * @memberof Query + */ + where(where: string): this; + /** + * Define the offset of the results, when combined with limit can be used for paging. + * Only available for Feature Layers hosted on ArcGIS Online or ArcGIS Server 10.3. + * + * @param {number} offset + * @returns {this} + * @memberof Query + */ + offset(offset: number): this; + /** + * Limit the number of results returned by this query, when combined with offset can be used for paging. + * Only available for Feature Layers hosted on ArcGIS Online or ArcGIS Server 10.3. + * + * @param {number} limit + * @returns {this} + * @memberof Query + */ + limit(limit: number): this; + /** + * Queries features within a given time range. Only available for Layers/Services with timeInfo in their metadata. + * + * @param {Date} from + * @param {Date} to + * @returns {this} + * @memberof Query + */ + between(from: Date, to: Date): this; + /** + * An array of associated fields to request for each feature. + * + * @param {(string | Array)} fields + * @returns {this} + * @memberof Query + */ + fields(fields: string | Array): this; + /** + * Return geometry with results. Default is true. + * + * @param {boolean} returnGeometry + * @returns {this} + * @memberof Query + */ + returnGeometry(returnGeometry: boolean): this; + /** + * Simplify the geometries of the output features for the current map view. the factor parameter controls the amount of simplification between 0 (no simplification) and 1 (the most basic shape possible). + * + * @param {L.Map} map + * @param {number} factor + * @returns {this} + * @memberof Query + */ + simplify(map: L.Map, factor: number): this; + /** + * Sort output features using values from an individual field. "ASC" (ascending) is the default sort order, but "DESC" can be passed as an alternative. This method can be called more than once to apply advanced sorting. + * + * @param {string} fieldName + * @param {string} order + * @returns {this} + * @memberof Query + */ + orderBy(fieldName: string, order: string): this; + /** + * Return only specific feature IDs if they match other query parameters. + * + * @param {Array} ids + * @returns {this} + * @memberof Query + */ + featureIds(ids: Array): this; + /** + * Return only this many decimal points of precision in the output geometries. + * + * @param {number} precision + * @returns {this} + * @memberof Query + */ + precision(precision: number): this; + /** + * Used to select which layer inside a Map Service to perform the query on. + * Only available for Map Services. + * + * @param {(number | string)} layer + * @returns {this} + * @memberof Query + */ + layer(layer: number | string): this; + /** + * Override the default pixelSize when querying an Image Service. + * Only available for Image Services. + * + * @param {L.Point} point + * @returns {this} + * @memberof Query + */ + pixelSize(point: L.Point): this; + /** + * Exectues the query request with the current parameters, features will be passed to callback as a GeoJSON FeatureCollection. Accepts an optional function context. + * + * @param {FeatureCallbackHandlerFn} callback + * @param {*} [context] + * @returns {this} + * @memberof Query + */ + run(callback: FeatureCallbackHandlerFn, context?: any): this; + /** + * Exectues the query request with the current parameters, passing only the number of features matching the query to callback as an Integer. Accepts an optional function context. + * + * @param {FeatureCallbackHandlerFn} callback + * @param {*} [context] + * @returns {this} + * @memberof Query + */ + count(callback: FeatureCallbackHandlerFn, context?: any): this; + /** + * Exectues the query request with the current parameters, passing only an array of the feature ids matching the query to callbackcallback. Accepts an optional function context. + * + * @param {FeatureCallbackHandlerFn} callback + * @param {*} [context] + * @returns {this} + * @memberof Query + */ + ids(callback: FeatureCallbackHandlerFn, context?: any): this; + /** + * Executes the query request with the current parameters, passing only the LatLngBounds of all features matching the query in the callback. Accepts an optional function context. Only available for Feature Layers hosted on ArcGIS Online or ArcGIS Server 10.3.1. + * + * @param {FeatureCallbackHandlerFn} callback + * @param {*} [context] + * @returns {this} + * @memberof Query + */ + bounds(callback: FeatureCallbackHandlerFn, context?: any): this; + } + + /** + * L.esri.Query is an abstraction for the query API included in Feature Layers and Image Services. It provides a chainable API for building request parameters and executing queries. + * Note Depending on the type of service you are querying (Feature Layer, Map Service, Image Service) and the version of ArcGIS Server that hosts the service some of these options may not be available. + * + * @param {QueryOptions} options + * @returns {Query} + */ + function query(options: QueryOptions): Query; } } From 21347e1045e0fd7c4d38ba8aa6a934b6adde5ee5 Mon Sep 17 00:00:00 2001 From: strajuser Date: Thu, 6 Jul 2017 09:08:09 +0300 Subject: [PATCH 0169/1618] - Query return type to Service query() methods - Tests updated --- types/esri-leaflet/esri-leaflet-tests.ts | 125 +++++++++-------------- types/esri-leaflet/index.d.ts | 71 +++++++------ 2 files changed, 84 insertions(+), 112 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index 4ce706b9a4..e6feca9aba 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -209,9 +209,7 @@ dynamicMapLayer.bindPopup( return (count) ? count + ' features' : false; }); -dynamicMapLayer.metadata(function (error, metadata) { - // console.log(metadata); -}); +dynamicMapLayer.metadata(function (error, metadata) { }); // TODO: // dynamicMapLayer.identify() @@ -225,12 +223,10 @@ dynamicMapLayer.metadata(function (error, metadata) { // .run(function(error, featureCollection){ // // console.log(featureCollection); // }); -// dynamicMapLayer.query() -// .layer(0) -// .within(latlngbounds) -// .run(function(error, featureCollection, response){ -// // console.log(featureCollection); -// }); +dynamicMapLayer.query() + .layer(0) + .within(latlngbounds) + .run(function(error, featureCollection, response){ }); let mapServiceOptions: L.esri.MapServiceOptions; let mapService: L.esri.MapService; @@ -262,13 +258,11 @@ mapService = new L.esri.MapService({ timeout: 1000 }); +mapService.query() + .layer(0) + .within(latlngbounds) + .run(function(error, featureCollection, response){ }); // TODO: -// mapService.query() -// .layer(0) -// .within(latlngbounds) -// .run(function(error, featureCollection, response){ -// // console.log(featureCollection); -// }); // mapService.identify() // .on(map) // .at(latlng) @@ -358,55 +352,42 @@ featureLayerService = new L.esri.FeatureLayerService({ timeout: 1000 }); -// TODO: -// featureLayerService.query() -// .within(latlngbounds) -// .where("Direction = 'WEST'") -// .run(function(error, featureCollection, response){ -// // console.log(featureCollection); -// }); +featureLayerService.query() + .within(latlngbounds) + .where("Direction = 'WEST'") + .run(function(error, featureCollection, response){ }); -// let feature = { -// type: 'Feature', -// geometry: { -// type: 'Point', -// coordinates: [-122, 45] -// }, -// properties: { -// name: 'Hello World' -// } -// }; +let feature = { + type: 'Feature', + geometry: { + type: 'Point', + coordinates: [-122, 45] + }, + properties: { + name: 'Hello World' + } +}; +featureLayerService.addFeature(feature, function(error, response){ }); -// featureLayerService.addFeature(feature, function(error, response){ -// // console.log() -// }); +let feature2 = { + type: 'Feature', + id: 2, + geometry: { + type: 'Point', + coordinates: [-122, 45] + }, + properties: { + name: 'Hi I\'m Feature 2' + } +}; +featureLayerService.updateFeature(feature2, function(error, response){ }); -// feature2 = { -// type: 'Feature', -// id: 2, -// geometry: { -// type: 'Point', -// coordinates: [-122, 45] -// }, -// properties: { -// name: 'Hi I\'m Feature 2' -// } -// }; +featureLayerService.deleteFeature(2, function(error, response){ }); -// featureLayerService.updateFeature(feature2, function(error, response){ -// // console.log() -// }); - -// featureLayerService.deleteFeature(2, function(error, response){ -// // console.log() -// }); - -// featureLayerService -// .query() -// .where("name='Hello World'") -// .run(function(error, featureCollection, response){ -// // console.log() -// }); +featureLayerService + .query() + .where("name='Hello World'") + .run(function(error, featureCollection, response){ }); let queryOptions: L.esri.QueryOptions; let query: L.esri.Query; @@ -439,26 +420,14 @@ query = new L.esri.Query({ }); query.within(latlngbounds); -query.run(function(error, featureCollection, response){ - // console.log('Found ' + featureCollection.features.length + ' features'); -}); -query.bounds(function(error, latLngBounds, response){ - // map.fitBounds(latLngBounds); -}); +query.run(function(error, featureCollection, response){ }); +query.bounds(function(error, latLngBounds, response){ }); query.nearby(latlng, 500); -query.run(function(error, featureCollection, response){ - // console.log('Found ' + featureCollection.features.length + ' features'); -}); +query.run(function(error, featureCollection, response){ }); query.nearby(latlng, 2000).where("direction='East'").orderBy('stop_id', 'ASC'); -query.count(function(error, count, response){ - // console.log('Found ' + count + ' features'); -}); -query.ids(function(error, ids, response){ - // console.log(ids.join(', ') + 'match the provided parameters'); -}); +query.count(function(error, count, response){ }); +query.ids(function(error, ids, response){ }); -query.where("zone_id='B'").bounds(function(error, latLngBounds, response){ - // map.fitBounds(latLngBounds); -}); +query.where("zone_id='B'").bounds(function(error, latLngBounds, response){ }); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index f085f4f17c..e74511f5c7 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -7,7 +7,7 @@ declare namespace L { namespace esri { - type CallbackHandlerFn = (error: any, metadata: any) => void; + type CallbackHandler = (error: any, metadata: any) => void; interface LayerOptionsBase { /** @@ -134,15 +134,15 @@ declare namespace L { /** * Requests metadata about this Feature Layer. Callback will be called with error and metadata. * - * @param {CallbackHandlerFn} callback + * @param {CallbackHandler} callback * @param {*} context * @returns {this} * @memberof TiledMapLayer */ - metadata(callback: CallbackHandlerFn, context?: any): this; + metadata(callback: CallbackHandler, context?: any): this; identify() : any; find(): any; - query(): any; + query(): Query; } /** @@ -262,12 +262,12 @@ declare namespace L { /** * Requests metadata about this Feature Layer. Callback will be called with error and metadata. * - * @param {CallbackHandlerFn} callback + * @param {CallbackHandler} callback * @param {*} context * @returns {this} * @memberof TiledMapLayer */ - metadata(callback: CallbackHandlerFn, context?: any): this; + metadata(callback: CallbackHandler, context?: any): this; } /** @@ -342,7 +342,7 @@ declare namespace L { * @returns {this} * @memberof DynamicMapLayer */ - bindPopup(fn: any, popupOptions?: L.PopupOptions): this; + bindPopup(fn: FeatureCallbackHandler, popupOptions?: L.PopupOptions): this; /** * Removes a popup previously bound with bindPopup. * @@ -445,7 +445,7 @@ declare namespace L { * @returns {*} * @memberof DynamicMapLayer */ - query(): any; + query(): Query; } /** @@ -461,7 +461,8 @@ declare namespace L { declare namespace L { namespace esri { - type FeatureCallbackHandlerFn = (error?: any, featureCollection?: any, response?: any) => void; + type FeatureCallbackHandler = (error?: any, featureCollection?: any, response?: any) => void; + type ResponseCallbackHandler = (error?: any, response?: any) => void; /** * Options for L.esri.Service @@ -511,23 +512,23 @@ declare namespace L { * * @param {string} url * @param {*} [params] - * @param {CallbackHandlerFn} [callback] + * @param {CallbackHandler} [callback] * @param {*} [context] * @returns {this} * @memberof Service */ - get(url: string, params?: any, callback?: CallbackHandlerFn, context?: any): this; + get(url: string, params?: any, callback?: CallbackHandler, context?: any): this; /** * Makes a POST request to the service. The service's URL will be combined with the path option and parameters will be serialized. Accepts an optional function context for the callback. * * @param {string} url * @param {*} [params] - * @param {CallbackHandlerFn} [callback] + * @param {CallbackHandler} [callback] * @param {*} [context] * @returns {this} * @memberof Service */ - post(url: string, params?: any, callback?: CallbackHandlerFn, context?: any): this; + post(url: string, params?: any, callback?: CallbackHandler, context?: any): this; /** * Authenticates this service with a new token and runs any pending requests that required a token. * @@ -539,12 +540,12 @@ declare namespace L { /** * Requests metadata about this Feature Layer. Callback will be called with error and metadata. * - * @param {CallbackHandlerFn} callback + * @param {CallbackHandler} callback * @param {*} context * @returns {this} * @memberof TiledMapLayer */ - metadata(callback: CallbackHandlerFn, context?: any): this; + metadata(callback: CallbackHandler, context?: any): this; } /** @@ -583,7 +584,7 @@ declare namespace L { * @returns {*} * @memberof MapService */ - query(): any; + query(): Query; } /** @@ -661,7 +662,7 @@ declare namespace L { * @returns {this} * @memberof ImageService */ - query(): this; + query(): Query; } /** @@ -694,55 +695,57 @@ declare namespace L { * @returns {this} * @memberof FeatureLayerService */ - query(): this; + query(): Query; /** * Adds a new feature to the feature layer. this also adds the feature to the map if creation is successful. * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. * Requires the Create capability be enabled on the service. You can check if creation exists by checking the metadata of your service under capabilities. * * @param {GeoJSONFeature} feature - * @param {*} callback + * @param {ResponseCallbackHandler} [callback] * @param {*} context * @returns {this} * @memberof FeatureLayerService */ - addFeature(feature: GeoJSONFeature, callback?: any, context?: any): this; + // TODO: GeoJSONFeature + addFeature(feature: any, callback?: ResponseCallbackHandler, context?: any): this; /** * Update the provided feature on the Feature Layer. This also updates the feature on the map. * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. * Requires the Update capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. * * @param {GeoJSONFeature} feature - * @param {*} callback + * @param {ResponseCallbackHandler} [callback] * @param {*} context * @returns {this} * @memberof FeatureLayerService */ - updateFeature(feature: GeoJSONFeature, callback?: any, context?: any): this; + // TODO: GeoJSONFeature + updateFeature(feature: any, callback?: ResponseCallbackHandler, context?: any): this; /** * Remove the feature with the provided id from the feature layer. This will also remove the feature from the map if it exists. * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. * Requires the Delete capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. * * @param {(string | number)} id - * @param {*} callback + * @param {ResponseCallbackHandler} [callback] * @param {*} context * @returns {this} * @memberof FeatureLayerService */ - deleteFeature(id: string | number, callback?: any, context?: any): this; + deleteFeature(id: string | number, callback?: ResponseCallbackHandler, context?: any): this; /** * Removes an array of features with the provided ids from the feature layer. This will also remove the features from the map if they exist. * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. * Requires the Delete capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. * * @param {(Array)} ids - * @param {*} callback + * @param {ResponseCallbackHandler} [callback] * @param {*} context * @returns {this} * @memberof FeatureLayerService */ - deleteFeatures(ids: Array, callback?: any, context?: any): this; + deleteFeatures(ids: Array, callback?: ResponseCallbackHandler, context?: any): this; } /** @@ -926,39 +929,39 @@ declare namespace L { /** * Exectues the query request with the current parameters, features will be passed to callback as a GeoJSON FeatureCollection. Accepts an optional function context. * - * @param {FeatureCallbackHandlerFn} callback + * @param {FeatureCallbackHandler} callback * @param {*} [context] * @returns {this} * @memberof Query */ - run(callback: FeatureCallbackHandlerFn, context?: any): this; + run(callback: FeatureCallbackHandler, context?: any): this; /** * Exectues the query request with the current parameters, passing only the number of features matching the query to callback as an Integer. Accepts an optional function context. * - * @param {FeatureCallbackHandlerFn} callback + * @param {FeatureCallbackHandler} callback * @param {*} [context] * @returns {this} * @memberof Query */ - count(callback: FeatureCallbackHandlerFn, context?: any): this; + count(callback: FeatureCallbackHandler, context?: any): this; /** * Exectues the query request with the current parameters, passing only an array of the feature ids matching the query to callbackcallback. Accepts an optional function context. * - * @param {FeatureCallbackHandlerFn} callback + * @param {FeatureCallbackHandler} callback * @param {*} [context] * @returns {this} * @memberof Query */ - ids(callback: FeatureCallbackHandlerFn, context?: any): this; + ids(callback: FeatureCallbackHandler, context?: any): this; /** * Executes the query request with the current parameters, passing only the LatLngBounds of all features matching the query in the callback. Accepts an optional function context. Only available for Feature Layers hosted on ArcGIS Online or ArcGIS Server 10.3.1. * - * @param {FeatureCallbackHandlerFn} callback + * @param {FeatureCallbackHandler} callback * @param {*} [context] * @returns {this} * @memberof Query */ - bounds(callback: FeatureCallbackHandlerFn, context?: any): this; + bounds(callback: FeatureCallbackHandler, context?: any): this; } /** From abf3f82b727b80fc73e20641f24af02e5451b2f8 Mon Sep 17 00:00:00 2001 From: Drew Hays Date: Thu, 6 Jul 2017 07:34:14 -0700 Subject: [PATCH 0170/1618] Use native React.ComponentType definition --- types/next/index.d.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 7f8eb6b18f..436914fd5d 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -107,13 +107,11 @@ declare module 'next/link' { } declare module 'next/dynamic' { - type ComponentType = React.StatelessComponent | typeof React.Component; - interface DynamicOptions { - loading?: ComponentType; + loading?: React.ComponentType; ssr?: boolean; - modules?(props: TCProps & TLProps): { [key: string]: Promise> }; - render?(props: TCProps & TLProps, modules: { [key: string]: ComponentType }): void; + modules?(props: TCProps & TLProps): { [key: string]: Promise> }; + render?(props: TCProps & TLProps, modules: { [key: string]: React.ComponentType }): void; } class SameLoopPromise extends Promise { @@ -122,12 +120,11 @@ declare module 'next/dynamic' { setError(value: any): void; runIfNeeded(): void; } - export default function(componentPromise: Promise>, options?: DynamicOptions): ComponentType; + export default function(componentPromise: Promise>, options?: DynamicOptions): React.ComponentType; } declare module 'next/router' { import * as url from 'url'; - type ComponentType = React.StatelessComponent | typeof React.Component; interface EventChangeOptions { shallow?: boolean; @@ -140,7 +137,7 @@ declare module 'next/router' { ready(cb: RouterCallback): void; // router properties - readonly components: { [key: string]: { Component: ComponentType, err: any } }; + readonly components: { [key: string]: { Component: React.ComponentType, err: any } }; readonly pathname: string; readonly route: string; readonly asPath: string; @@ -151,7 +148,7 @@ declare module 'next/router' { back(): void; push(url: string, as?: string, options?: EventChangeOptions): Promise; replace(url: string, as?: string, options?: EventChangeOptions): Promise; - prefetch(url: string): Promise>; + prefetch(url: string): Promise>; // router events onAppUpdated?(nextRoute: string): void; From 8855c7daa351b05f66b250036233299e0fc89cea Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 6 Jul 2017 11:03:45 -0400 Subject: [PATCH 0171/1618] Implement supercluster type definition --- types/supercluster/index.d.ts | 94 ++++++++++++++++++++++++ types/supercluster/supercluster-tests.ts | 30 ++++++++ types/supercluster/tsconfig.json | 22 ++++++ types/supercluster/tslint.json | 1 + 4 files changed, 147 insertions(+) create mode 100644 types/supercluster/index.d.ts create mode 100644 types/supercluster/supercluster-tests.ts create mode 100644 types/supercluster/tsconfig.json create mode 100644 types/supercluster/tslint.json diff --git a/types/supercluster/index.d.ts b/types/supercluster/index.d.ts new file mode 100644 index 0000000000..e2b44dae53 --- /dev/null +++ b/types/supercluster/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for supercluster 2.3 +// Project: https://github.com/mapbox/supercluster +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as GeoJSON from 'geojson' + +interface Options { + /** + * Minimum zoom level at which clusters are generated. + */ + minZoom?: number + /** + * Maximum zoom level at which clusters are generated. + */ + maxZoom?: number + /** + * Cluster radius, in pixels. + */ + radius?: number + /** + * (Tiles) Tile extent. Radius is calculated relative to this value. + */ + extent?: number + /** + * Size of the KD-tree leaf node. Affects performance. + */ + nodeSize?: number + /** + * Whether timing info should be logged. + */ + log?: boolean +} + +declare class Supercluster { + /** + * Loads an array of GeoJSON.Feature objects. Each feature's geometry must be a GeoJSON.Point. Once loaded, index is immutable. + */ + load(points: supercluster.Points): Supercluster + /** + * For the given bbox array ([westLng, southLat, eastLng, northLat]) and integer zoom, returns an array of clusters and points as GeoJSON.Feature objects. + */ + getClusters(bbox: supercluster.BBox, zoom: number): supercluster.Clusters + + /** + * For a given zoom and x/y coordinates, returns a geojson-vt-compatible JSON tile object with cluster/point features. + */ + getTile(z: number, x: number, y: number): supercluster.Tile + + /** + * Returns the children of a cluster (on the next zoom level) given its id (cluster_id value from feature properties) and zoom the cluster was from. + */ + getChildren(clusterId: number, clusterZoom: number): supercluster.Clusters + + /** + * Returns all the points of a cluster (given its cluster_id and zoom), with pagination support: limit is the number of points to return (set to Infinity for all points), and offset is the amount of points to skip (for pagination). + */ + getLeaves(clusterId: number, clusterZoom: number, limit?: number, offset?: number): supercluster.Clusters + + /** + * Returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature), given the cluster's cluster_id and zoom. + */ + getClusterExpansionZoom(clusterId: number, clusterZoom: number): number +} + +/** + * A very fast JavaScript library for geospatial point clustering for browsers and Node. + */ +declare function supercluster(options: Options): Supercluster +declare namespace supercluster { + export type Point = GeoJSON.Feature + export type Points = Point[] + export type Clusters = Cluster[] + export type TileFeatures = TileFeature[] + export type BBox = [number, number, number, number] + export interface ClusterProperties { + cluster?: boolean + cluster_id?: number + point_count?: number + point_count_abbreviated?: number + } + export interface Cluster extends Point { + properties: any + } + export interface TileFeature { + type: 1, + geometry: [number, number][] + tags: any + } + export interface Tile { + features: TileFeatures + } +} +export = supercluster diff --git a/types/supercluster/supercluster-tests.ts b/types/supercluster/supercluster-tests.ts new file mode 100644 index 0000000000..21aa4506f5 --- /dev/null +++ b/types/supercluster/supercluster-tests.ts @@ -0,0 +1,30 @@ +import * as supercluster from 'supercluster'; +import {Point, Points, Cluster, ClusterProperties} from 'supercluster'; + +const point1: Cluster = { + type: 'Feature', + properties: { + foo: 'fesf' + }, + geometry: { type: 'Point', coordinates: [0, 0] } +}; +const point2: Point = { + type: 'Feature', + properties: {}, + geometry: { type: 'Point', coordinates: [0, 0] } +}; +const points: Points = [point1, point2]; + +const index = supercluster({ + radius: 40, + maxZoom: 16, + extent: 256, + log: true +}); +index.load(points); +index.getClusters([-180, -85, 180, 85], 2); +index.getTile(0, 0, 0); +index.getChildren(0, 0); +index.getLeaves(0, 0, 10, 5); +index.getClusterExpansionZoom(0, 0); +index.getTile(0, 0, 0).features[0].tags.sum; diff --git a/types/supercluster/tsconfig.json b/types/supercluster/tsconfig.json new file mode 100644 index 0000000000..b5cc84208d --- /dev/null +++ b/types/supercluster/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "supercluster-tests.ts" + ] +} diff --git a/types/supercluster/tslint.json b/types/supercluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/supercluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 59d421824f54378a7722aba00d9d55409056babd Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 6 Jul 2017 11:09:41 -0400 Subject: [PATCH 0172/1618] Linting issues resolved --- types/supercluster/index.d.ts | 70 ++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/types/supercluster/index.d.ts b/types/supercluster/index.d.ts index e2b44dae53..98a3b247c6 100644 --- a/types/supercluster/index.d.ts +++ b/types/supercluster/index.d.ts @@ -3,92 +3,94 @@ // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import * as GeoJSON from 'geojson' +import * as GeoJSON from 'geojson'; interface Options { /** * Minimum zoom level at which clusters are generated. */ - minZoom?: number + minZoom?: number; /** * Maximum zoom level at which clusters are generated. */ - maxZoom?: number + maxZoom?: number; /** * Cluster radius, in pixels. */ - radius?: number + radius?: number; /** * (Tiles) Tile extent. Radius is calculated relative to this value. */ - extent?: number + extent?: number; /** * Size of the KD-tree leaf node. Affects performance. */ - nodeSize?: number + nodeSize?: number; /** * Whether timing info should be logged. */ - log?: boolean + log?: boolean; } declare class Supercluster { /** * Loads an array of GeoJSON.Feature objects. Each feature's geometry must be a GeoJSON.Point. Once loaded, index is immutable. */ - load(points: supercluster.Points): Supercluster + load(points: supercluster.Points): Supercluster; /** * For the given bbox array ([westLng, southLat, eastLng, northLat]) and integer zoom, returns an array of clusters and points as GeoJSON.Feature objects. */ - getClusters(bbox: supercluster.BBox, zoom: number): supercluster.Clusters + getClusters(bbox: supercluster.BBox, zoom: number): supercluster.Clusters; /** * For a given zoom and x/y coordinates, returns a geojson-vt-compatible JSON tile object with cluster/point features. */ - getTile(z: number, x: number, y: number): supercluster.Tile + getTile(z: number, x: number, y: number): supercluster.Tile; /** * Returns the children of a cluster (on the next zoom level) given its id (cluster_id value from feature properties) and zoom the cluster was from. */ - getChildren(clusterId: number, clusterZoom: number): supercluster.Clusters + getChildren(clusterId: number, clusterZoom: number): supercluster.Clusters; /** - * Returns all the points of a cluster (given its cluster_id and zoom), with pagination support: limit is the number of points to return (set to Infinity for all points), and offset is the amount of points to skip (for pagination). + * Returns all the points of a cluster (given its cluster_id and zoom), + * with pagination support: limit is the number of points to return (set to Infinity for all points), + * and offset is the amount of points to skip (for pagination). */ - getLeaves(clusterId: number, clusterZoom: number, limit?: number, offset?: number): supercluster.Clusters + getLeaves(clusterId: number, clusterZoom: number, limit?: number, offset?: number): supercluster.Clusters; /** * Returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature), given the cluster's cluster_id and zoom. */ - getClusterExpansionZoom(clusterId: number, clusterZoom: number): number + getClusterExpansionZoom(clusterId: number, clusterZoom: number): number; } /** * A very fast JavaScript library for geospatial point clustering for browsers and Node. */ -declare function supercluster(options: Options): Supercluster +declare function supercluster(options: Options): Supercluster; declare namespace supercluster { - export type Point = GeoJSON.Feature - export type Points = Point[] - export type Clusters = Cluster[] - export type TileFeatures = TileFeature[] - export type BBox = [number, number, number, number] - export interface ClusterProperties { - cluster?: boolean - cluster_id?: number - point_count?: number - point_count_abbreviated?: number + type Point = GeoJSON.Feature; + type Points = Point[]; + type Clusters = Cluster[]; + type TileFeatures = TileFeature[]; + type BBox = [number, number, number, number]; + interface ClusterProperties { + cluster?: boolean; + cluster_id?: number; + point_count?: number; + point_count_abbreviated?: number; } - export interface Cluster extends Point { - properties: any + interface Cluster extends Point { + properties: any; } - export interface TileFeature { - type: 1, - geometry: [number, number][] - tags: any + interface TileFeature { + type: 1; + geometry: Array<[number, number]>; + tags: any; } - export interface Tile { - features: TileFeatures + interface Tile { + features: TileFeatures; } } -export = supercluster +export = supercluster; From 6727bde8488873088e56d6292818ccf8bfcd9152 Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 6 Jul 2017 11:22:00 -0400 Subject: [PATCH 0173/1618] Add ClusterProperties to Cluster --- types/supercluster/index.d.ts | 6 ++++-- types/supercluster/supercluster-tests.ts | 17 ++++++++--------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/types/supercluster/index.d.ts b/types/supercluster/index.d.ts index 98a3b247c6..6d3e6c3895 100644 --- a/types/supercluster/index.d.ts +++ b/types/supercluster/index.d.ts @@ -80,14 +80,16 @@ declare namespace supercluster { cluster_id?: number; point_count?: number; point_count_abbreviated?: number; + sum?: number; + [key: string]: any; } interface Cluster extends Point { - properties: any; + properties: ClusterProperties; } interface TileFeature { type: 1; geometry: Array<[number, number]>; - tags: any; + tags: ClusterProperties; } interface Tile { features: TileFeatures; diff --git a/types/supercluster/supercluster-tests.ts b/types/supercluster/supercluster-tests.ts index 21aa4506f5..267d2df4fd 100644 --- a/types/supercluster/supercluster-tests.ts +++ b/types/supercluster/supercluster-tests.ts @@ -1,19 +1,17 @@ import * as supercluster from 'supercluster'; -import {Point, Points, Cluster, ClusterProperties} from 'supercluster'; +import {Point} from 'supercluster'; -const point1: Cluster = { +const point1: Point = { type: 'Feature', - properties: { - foo: 'fesf' - }, - geometry: { type: 'Point', coordinates: [0, 0] } + properties: {}, + geometry: { type: 'Point', coordinates: [10, 20] } }; const point2: Point = { type: 'Feature', properties: {}, - geometry: { type: 'Point', coordinates: [0, 0] } + geometry: { type: 'Point', coordinates: [20, 30] } }; -const points: Points = [point1, point2]; +const points = [point1, point2]; const index = supercluster({ radius: 40, @@ -22,7 +20,8 @@ const index = supercluster({ log: true }); index.load(points); -index.getClusters([-180, -85, 180, 85], 2); +const clusters = index.getClusters([-180, -85, 180, 85], 2); +clusters[0].properties.cluster_id; index.getTile(0, 0, 0); index.getChildren(0, 0); index.getLeaves(0, 0, 10, 5); From 5adc31cb7c723619c11dcf3ce81645943c275f75 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Thu, 6 Jul 2017 23:25:38 +0800 Subject: [PATCH 0174/1618] =?UTF-8?q?=E5=BC=95=E5=85=A5bootstrap,messager,?= =?UTF-8?q?store,datetimepicker,modaltrigger=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- types/zui/boostrap.datetimepicker/index.d.ts | 123 ++++++++++++ .../zui/boostrap.datetimepicker/package.json | 5 + .../zui/boostrap.datetimepicker/tsconfig.json | 27 +++ types/zui/bootstrap.d.ts | 126 +++++++++++++ types/zui/index.d.ts | 33 ++++ types/zui/messager.d.ts | 45 +++++ types/zui/modal.d.ts | 19 ++ types/zui/modal.trigger.d.ts | 50 +++++ types/zui/store.d.ts | 25 +++ types/zui/tsconfig.json | 22 +++ types/zui/tslint.json | 1 + types/zui/zui-tests.ts | 176 ++++++++++++++++++ 12 files changed, 652 insertions(+) create mode 100644 types/zui/boostrap.datetimepicker/index.d.ts create mode 100644 types/zui/boostrap.datetimepicker/package.json create mode 100644 types/zui/boostrap.datetimepicker/tsconfig.json create mode 100644 types/zui/bootstrap.d.ts create mode 100644 types/zui/index.d.ts create mode 100644 types/zui/messager.d.ts create mode 100644 types/zui/modal.d.ts create mode 100644 types/zui/modal.trigger.d.ts create mode 100644 types/zui/store.d.ts create mode 100644 types/zui/tsconfig.json create mode 100644 types/zui/tslint.json create mode 100644 types/zui/zui-tests.ts diff --git a/types/zui/boostrap.datetimepicker/index.d.ts b/types/zui/boostrap.datetimepicker/index.d.ts new file mode 100644 index 0000000000..129d77491a --- /dev/null +++ b/types/zui/boostrap.datetimepicker/index.d.ts @@ -0,0 +1,123 @@ +// Type definitions for Bootstrap datetimepicker v3 3.x +// Project: http://eonasdan.github.io/bootstrap-datetimepicker +// Definitions by: Jesica N. Fera +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** + * bootstrap-datetimepicker.js 3.0.0 Copyright (c) 2014 Jonathan Peterson + * Available via the MIT license. + * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. + */ + +/// + +import * as moment from 'moment'; + +export as namespace BootstrapV3DatetimePicker; + +export interface DatetimepickerChangeEventObject extends DatetimepickerEventObject { + oldDate: moment.Moment; +} + +export interface DatetimepickerEventObject extends JQueryEventObject { + date: moment.Moment; +} + +export interface DatetimepickerIcons { + time?: string; + date?: string; + up?: string; + down?: string; +} + +export interface DatetimepickerOptions { + weekStart?: number; + todayBtn?: number | boolean; + autoclose?: number | boolean; + todayHighlight?: number | boolean; + startView?: number; + forceParse?: number | boolean; + showMeridian?: boolean | number, + minView?: number; + maxView?: number; + pickDate?: boolean; + pickTime?: boolean; + useMinutes?: boolean; + useSeconds?: boolean; + useCurrent?: boolean; + minuteStepping?: number; + minDate?: moment.Moment | Date | string; + maxDate?: moment.Moment | Date | string; + showToday?: boolean; + collapse?: boolean; + language?: string; + defaultDate?: moment.Moment | Date | string; + disabledDates?: Array; + enabledDates?: Array; + icons?: DatetimepickerIcons; + useStrict?: boolean; + direction?: string; + sideBySide?: boolean; + daysOfWeekDisabled?: Array; + calendarWeeks?: boolean; + format?: string | boolean; + locale?: string; + showTodayButton?: boolean; + viewMode?: string; + inline?: boolean; + toolbarPlacement?: string; + showClear?: boolean; + ignoreReadonly?: boolean; +} + +export interface Datetimepicker { + date(date: moment.Moment | Date | string): void; + date(): moment.Moment; + minDate(date: moment.Moment | Date | string): void; + minDate(): moment.Moment | boolean; + maxDate(date: moment.Moment | Date | string): void; + maxDate(): moment.Moment | boolean; + show(): void; + disable(): void; + enable(): void; + destroy(): void; + toggle(): void; +} + +declare global { + interface JQuery { + datetimepicker(): JQuery; + datetimepicker(options: DatetimepickerOptions): JQuery; + + off(events: "dp.change", selector?: string, handler?: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; + off(events: "dp.change", handler: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; + + on(events: "dp.change", selector: string, data: any, handler?: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; + on(events: "dp.change", selector: string, handler: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; + on(events: 'dp.change', handler: (eventObject: DatetimepickerChangeEventObject) => any): JQuery; + + off(events: "dp.show", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + off(events: "dp.show", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.show", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: "dp.show", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.show', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; + + off(events: "dp.hide", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + off(events: "dp.hide", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: "dp.hide", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.hide', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; + + off(events: "dp.error", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + off(events: "dp.error", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.error", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: "dp.error", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.error', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; + + data(key: 'DateTimePicker'): Datetimepicker; + } +} diff --git a/types/zui/boostrap.datetimepicker/package.json b/types/zui/boostrap.datetimepicker/package.json new file mode 100644 index 0000000000..4c6d24a445 --- /dev/null +++ b/types/zui/boostrap.datetimepicker/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": ">=2.14.0" + } +} \ No newline at end of file diff --git a/types/zui/boostrap.datetimepicker/tsconfig.json b/types/zui/boostrap.datetimepicker/tsconfig.json new file mode 100644 index 0000000000..c81098be9e --- /dev/null +++ b/types/zui/boostrap.datetimepicker/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "bootstrap.v3.datetimepicker": [ + "bootstrap.v3.datetimepicker/v3" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/types/zui/bootstrap.d.ts b/types/zui/bootstrap.d.ts new file mode 100644 index 0000000000..3976b53886 --- /dev/null +++ b/types/zui/bootstrap.d.ts @@ -0,0 +1,126 @@ +// Type definitions for Bootstrap 3.3.5 +// Project: http://twitter.github.com/bootstrap/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +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; + keyboard?: 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 TransitionEventNames { + end: string; +} + +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, params?: 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; + + emulateTransitionEnd(duration: number): JQuery; +} + +interface JQuerySupport { + transition: boolean | TransitionEventNames; +} + diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts new file mode 100644 index 0000000000..da8e423a85 --- /dev/null +++ b/types/zui/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +/// +/// +/// + +/// + + +/*~ If this module is a UMD module that exposes a global variable 'myLib' when + *~ loaded outside a module loader environment, declare that global here. + *~ Otherwise, delete this declaration. + */ + + +interface ZuiStatic { + //$.zui.messager + messager: Messager; + Messager: MessagerStatic; + + store: StoreStatic; +} +interface JQueryStatic { + zui: ZuiStatic; + +} \ No newline at end of file diff --git a/types/zui/messager.d.ts b/types/zui/messager.d.ts new file mode 100644 index 0000000000..91878a3232 --- /dev/null +++ b/types/zui/messager.d.ts @@ -0,0 +1,45 @@ +declare enum MessagerTypeEnum { + 'default', 'primary', 'success', 'info', 'warning', 'danger', 'important', 'special' +} +interface Action { + name?: string, + icon?: string, + text?: string + html?: string + action?: ActionFunc; +} + +interface ActionFunc { + (): boolean; +} +interface OnActionFunc { + (name: string, action: string, messager: Messager): any +} + +interface MessagerOption { + type?: MessagerTypeEnum | string; + placement?: string, + time?: number; + message?: string, + parent?: string, + icon?: string, + close?: boolean; + fade?: boolean; + scale?: boolean; + actions?: Array; + onAction?: OnActionFunc; + cssClass?: string, + contentClass?: string, + show?: boolean +} +interface Messager { + show(cb?: Function): any; + show(message: string, cb?: Function): any; + + hide(cb?: Function): any; +} +interface MessagerStatic { + new (option?: MessagerOption): Messager; + new (message: string, option?: MessagerOption): Messager; +} +//sdeclare var messager: Messager; diff --git a/types/zui/modal.d.ts b/types/zui/modal.d.ts new file mode 100644 index 0000000000..5f7a903f4f --- /dev/null +++ b/types/zui/modal.d.ts @@ -0,0 +1,19 @@ + +interface ModalOptions { + backdrop?: boolean | string; + keyboard?: boolean; + show?: boolean; + remote?: string; +} + +interface ModalOptionsBackdropString { + backdrop?: string; // for "static" + keyboard?: boolean; + show?: boolean; + remote?: string; +} +interface JQuery { + modal(options?: ModalOptions): JQuery; + modal(options?: ModalOptionsBackdropString): JQuery; + modal(command: string): JQuery; +} \ No newline at end of file diff --git a/types/zui/modal.trigger.d.ts b/types/zui/modal.trigger.d.ts new file mode 100644 index 0000000000..fee8161ce0 --- /dev/null +++ b/types/zui/modal.trigger.d.ts @@ -0,0 +1,50 @@ +interface ModalTriggerOption { + name?: string, + className?: string, + type?: string, + url?: string, + remote?: string, + iframe?: string, + size?: string, + width?: string, + height?: string, + showHeader?: boolean, + title?: string, + icon?: string, + fade?: boolean, + postion?: string, + backdrop?: boolean, + keyboard?: boolean, + moveable?: boolean, + rememberPos?: boolean, + waittime?: number, + loadingIcon?: string, + + show?(): any; + onShow?(): any; + onHide?(): any; + hidden?(): any; + loaded?(): any; + broken?(): any; +} + +interface ModalTrigger { + show(option?: ModalTriggerOption): any; + close(): any; + toggle(option?: ModalTriggerOption): any; + adjustPostion(option?: ModalTriggerOption): any; + +} +interface ModalTriggerStatic { + new (option?: ModalTriggerOption): ModalTrigger +} + +interface JQuery { + modalTrigger(option?: ModalTriggerOption): JQuery //$('#modal').modalTrigger() + data(value: string): JQuery; +} + +interface ZuiStatic { + ModalTrigger: ModalTriggerStatic; + modalTrigger: ModalTrigger; +} \ No newline at end of file diff --git a/types/zui/store.d.ts b/types/zui/store.d.ts new file mode 100644 index 0000000000..3544cbdd60 --- /dev/null +++ b/types/zui/store.d.ts @@ -0,0 +1,25 @@ + +interface StoreStatic { + enable: boolean; + storage: any; + length(): number; + remove(key: string): any; + get(key: string): T; + set(key: string, value?: T): any; + key(index: number): string; + forEach(cb: (key: string, value: T) => any): any; + serialize(value: any): string; + deserialize(value: string): T; + getAll(): T; + removeItem(key: string): any; + getItem(key: string): string; + setItem(key: string, value: any): any; + clear(): void; + + page: any; + pageGet(key: string): any; + pageSet(key: string, value: any): any; + pageRemove(key: string): any; + pageSave(): any; + pageClear(): any; +} \ No newline at end of file diff --git a/types/zui/tsconfig.json b/types/zui/tsconfig.json new file mode 100644 index 0000000000..83e99ace31 --- /dev/null +++ b/types/zui/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "zui-tests.ts" + ] +} diff --git a/types/zui/tslint.json b/types/zui/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/zui/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts new file mode 100644 index 0000000000..51437097a6 --- /dev/null +++ b/types/zui/zui-tests.ts @@ -0,0 +1,176 @@ +/// +new $.zui.Messager(); + +new $.zui.Messager('提示消息:成功', { + type: 'success' // 定义颜色主题 +}).show(); +new $.zui.Messager("message") +let messagarOption: MessagerOption = {}; +new $.zui.Messager(messagarOption) +new $.zui.Messager("message", messagarOption); +$.zui.messager.show("ok"); + +/******** store *****/ +$.zui.store.set('name', 'catouse'); // 使用本地存储设置'name'值为'catouse' +$.zui.store.set('date', { year: 2014, month: 8, day: 6 }); // 将一个对象存储到本地存储 + +console.log($.zui.store.get('name')); // 从本地存储获取'name'的值 +console.log($.zui.store.get('date').year); // 从本地存储获取'date'值的year属性 + +$.zui.store.forEach(function (key, value) { // 遍历所有本地存储的条目 + console.log(value); +}); + +console.log($.zui.store.key(0)); // 获取本地存储第一个条目的名称 + +$.zui.store.remove('name'); // 从本地存储移除‘name’的值 +$.zui.store.clear(); // 清空所有本地存储的条目 + +/* 以下操作的键值仅针对当前页面 */ +$.zui.store.pageSet('name', 'catouse'); // 使用本地存储设置'name'值为'catouse' +$.zui.store.pageSet('date', { year: 2014, month: 8, day: 6 }); // 将一个对象存储到本地存储 + +console.log($.zui.store.pageGet('name')); // 从本地存储获取'name'的值 +console.log($.zui.store.pageGet('date').year); // 从本地存储获取'date'值的year属性 + +$.zui.store.pageRemove('name'); // 从本地存储移除‘name’的值 +$.zui.store.pageClear(); // 清空所有本地存储的条目 + + +/** + * modal + */ +$('#myModal').modal({ + keyboard: false, + show: true +}) + + +/** + * modal trigger + */ + +$('#triggerButton').modalTrigger({ title: '新的标题' }); + +/* 使用触发器对象直接显示 */ +(new $.zui.ModalTrigger({ title: '新的标题' })).show(); +$.zui.modalTrigger.show({ title: '标题' }); + +/** + * tabs + */ +$().tab('show'); +$('#myTabLink').tab('show'); + +/** + * tooltip + */ +$('[data-toggle="tooltip"]').tooltip(); +$('#element').tooltip('show'); +$('#element').tooltip('show', '这是新的工具提示内容'); + + +/** + * popover + */ +// 或者在初始化时指定弹出方向 +$('[data-toggle="popover"]').popover({ + placement: 'bottom' +}); +$('#myPopover').popover('show'); + +/** + * collapse + */ +$('#myCollapseContent').collapse({ + toggle: false +}); +$().collapse('show') + +$('#myCollapseContent').on('hidden.zui.collapse', function () { + console.log('折叠内容已隐藏。'); +}) + +/** + * carousel + */ +$('.carousel').carousel() + +/** + * datetime picker + */ +// 仅选择日期 +$(".form-date").datetimepicker( +{ + language: "zh-CN", + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 2, + minView: 2, + forceParse: 0, + format: "yyyy-mm-dd" +}); +// 选择时间 +$(".form-time").datetimepicker({ + language: "zh-CN", + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 1, + minView: 0, + maxView: 1, + forceParse: 0, + format: 'hh:ii' +}); +// 选择时间和日期 +$(".form-datetime").datetimepicker( +{ + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 2, + forceParse: 0, + showMeridian: 1, + format: "yyyy-mm-dd hh:ii" +}); + +// 仅选择日期 +$(".form-date").datetimepicker( +{ + language: "zh-CN", + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 2, + minView: 2, + forceParse: 0, + format: "yyyy-mm-dd" +}); +// 选择时间 +$(".form-time").datetimepicker({ + language: "zh-CN", + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 1, + minView: 0, + maxView: 1, + forceParse: 0, + format: 'hh:ii' +}); + +/** + * chosen + */ + +$('select.chosen-select').chosen({ + no_results_text: '没有找到', // 当检索时没有找到匹配项时显示的提示文本 + disable_search_threshold: 10, // 10 个以下的选择项则不显示检索框 + search_contains: true // 从任意位置开始检索 +}); \ No newline at end of file From 001235c7763804d5d41eeb78011a45f1cf6b192c Mon Sep 17 00:00:00 2001 From: Drew Hays Date: Thu, 6 Jul 2017 08:39:19 -0700 Subject: [PATCH 0175/1618] clean up imports --- types/next/index.d.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 436914fd5d..ab6e3df6f5 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -69,11 +69,14 @@ declare module 'next/error' { declare module 'next/head' { import * as React from 'react'; + function defaultHead(): JSX.Element[]; export default class extends React.Component<{}, {}> {} } declare module 'next/document' { + import * as React from 'react'; + interface DocumentProps { __NEXT_DATA__?: any; dev?: boolean; @@ -91,6 +94,8 @@ declare module 'next/document' { declare module 'next/link' { import * as url from 'url'; + import * as React from 'react'; + type UrlLike = url.UrlObject | url.Url; interface LinkState { prefetch?: boolean; @@ -107,6 +112,8 @@ declare module 'next/link' { } declare module 'next/dynamic' { + import * as React from 'react'; + interface DynamicOptions { loading?: React.ComponentType; ssr?: boolean; @@ -124,7 +131,7 @@ declare module 'next/dynamic' { } declare module 'next/router' { - import * as url from 'url'; + import * as React from 'react'; interface EventChangeOptions { shallow?: boolean; From a63c9fda694c6138df1d7844ea46152155a004a5 Mon Sep 17 00:00:00 2001 From: tedbcsgpro Date: Thu, 6 Jul 2017 09:33:40 -0700 Subject: [PATCH 0176/1618] Updates type definitions for Dropzone 5.0.0 --- types/dropzone/dropzone-tests.ts | 49 ++++++++++++++++++++++++++------ types/dropzone/index.d.ts | 30 +++++++++++++++---- 2 files changed, 65 insertions(+), 14 deletions(-) diff --git a/types/dropzone/dropzone-tests.ts b/types/dropzone/dropzone-tests.ts index f52cbc303e..cad22badb7 100644 --- a/types/dropzone/dropzone-tests.ts +++ b/types/dropzone/dropzone-tests.ts @@ -4,6 +4,10 @@ const dropzoneRenameFunction = function (name:string):string { return name + 'new'; }; +Dropzone.createElement('
'); +Dropzone.isBrowserSupported(); +console.log(Dropzone.instances.length); + const dropzoneWithOptions = new Dropzone(".test", { url: "/some/url", method: "post", @@ -14,8 +18,14 @@ const dropzoneWithOptions = new Dropzone(".test", { paramName: "file", createImageThumbnails: true, maxThumbnailFilesize: 1024, - thumbnailWidth: 50, - thumbnailHeight: 50, + thumbnailWidth: 120, + thumbnailHeight: 120, + thumbnailMethod: 'crop', + resizeWidth: 1024, + resizeHeight: 1024, + resizeMimeType: 'image.jpeg', + resizeQuality: .8, + resizeMethod: 'contain', filesizeBase: 1000, maxFiles: 100, params: { @@ -61,7 +71,7 @@ const dropzoneWithOptions = new Dropzone(".test", { init: () => console.log("Initialized"), forceFallback: false, fallback: () => console.log("Fallback"), - resize: (file:Dropzone.DropzoneFile) => ({ + resize: (file:Dropzone.DropzoneFile, width:120, height:120, resizeMethod:'contain') => ({ srcX: 0, srcY: 0, trgX: 10, @@ -70,8 +80,6 @@ const dropzoneWithOptions = new Dropzone(".test", { srcHeight: 100, trgWidth: 50, trgHeight: 50, - optWidth: 50, - optHeight: 50 }), drop: (e:DragEvent) => console.log("Drop"), @@ -146,6 +154,8 @@ const dropzone = new Dropzone(".test"); dropzone.enable(); dropzone.disable(); + + dropzone.files.forEach(f => { if (f.xhr) { console.log(f.xhr.readyState) @@ -167,10 +177,22 @@ dropzone.enqueueFile(firstFile); dropzone.processFile(firstFile); dropzone.uploadFile(firstFile); dropzone.cancelUpload(firstFile); -dropzone.createThumbnail(firstFile, () => { + +dropzone.createThumbnail(firstFile); +dropzone.createThumbnail(firstFile, dropzone.defaultOptions.resizeWidth); +dropzone.createThumbnail(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight); +dropzone.createThumbnail(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight, dropzone.defaultOptions.resizeMethod); +dropzone.createThumbnail(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight, dropzone.defaultOptions.resizeMethod, true); +dropzone.createThumbnail(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight, dropzone.defaultOptions.resizeMethod, true, () => { console.log("createThumbnail") }); -dropzone.createThumbnailFromUrl(firstFile, "/some/url", () => { + +dropzone.createThumbnailFromUrl(firstFile); +dropzone.createThumbnailFromUrl(firstFile, dropzone.defaultOptions.resizeWidth); +dropzone.createThumbnailFromUrl(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight); +dropzone.createThumbnailFromUrl(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight, dropzone.defaultOptions.resizeMethod); +dropzone.createThumbnailFromUrl(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight, dropzone.defaultOptions.resizeMethod, true); +dropzone.createThumbnailFromUrl(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight, dropzone.defaultOptions.resizeMethod, true, () => { console.log("createThumbnailFromUrl") }); dropzone.accept(firstFile, (e:string|Error) => { @@ -180,6 +202,9 @@ dropzone.accept(firstFile, (e:string|Error) => { const acceptedFiles = dropzone.getAcceptedFiles(); dropzone.processFiles(acceptedFiles); +const addedFiles = dropzone.getAddedFiles(); +dropzone.processFiles(addedFiles); + const rejectedFiles = dropzone.getRejectedFiles(); dropzone.enqueueFiles(rejectedFiles); @@ -192,12 +217,18 @@ dropzone.processFiles(uploadingFiles); const activeFiles = dropzone.getActiveFiles(); dropzone.processFiles(activeFiles); -const addedFiles = dropzone.getFilesWithStatus(Dropzone.ADDED); -dropzone.processFiles(addedFiles); +const getFileWithStatusAdded = dropzone.getFilesWithStatus(Dropzone.ADDED); +dropzone.processFiles(getFileWithStatusAdded); dropzone.processQueue(); dropzone.removeAllFiles(true); +dropzone.resizeImage(firstFile); +dropzone.resizeImage(firstFile, 120); +dropzone.resizeImage(firstFile, 120, 120); +dropzone.resizeImage(firstFile, 120, 120, 'contain'); +dropzone.resizeImage(firstFile, 120, 120, 'contain', function(){}); + dropzone .on("drop", () => { console.count('drop'); diff --git a/types/dropzone/index.d.ts b/types/dropzone/index.d.ts index 703172072f..e410833e68 100644 --- a/types/dropzone/index.d.ts +++ b/types/dropzone/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Dropzone 4.3.0 +// Type definitions for Dropzone 5.0.0 // Project: http://www.dropzonejs.com/ -// Definitions by: Natan Vivo , Andy Hawkins , Vasya Aksyonov , Simon Huber , Sebastiaan de Rooij +// Definitions by: Natan Vivo , Andy Hawkins , Vasya Aksyonov , Simon Huber , Sebastiaan de Rooij , Ted Bicknell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -16,8 +16,6 @@ declare namespace Dropzone { srcHeight?:number; trgWidth?:number; trgHeight?:number; - optWidth?:number; - optHeight?:number; } export interface DropzoneFile extends File { @@ -41,6 +39,12 @@ declare namespace Dropzone { maxThumbnailFilesize?: number; thumbnailWidth?: number; thumbnailHeight?: number; + thumbnailMethod?: string; + resizeWidth?: number; + resizeHeight?: number; + resizeMimeType?: string; + resizeQuality?: number; + resizeMethod?: string; filesizeBase?: number; maxFiles?: number; params?: {}; @@ -72,7 +76,7 @@ declare namespace Dropzone { init?():void; forceFallback?: boolean; fallback?():void; - resize?(file:DropzoneFile):DropzoneResizeInfo; + resize?(file:DropzoneFile, width?: number, height?: number, resizeMethod?:string):DropzoneResizeInfo; drop?(e:DragEvent):void; dragstart?(e:DragEvent):void; @@ -124,6 +128,9 @@ declare class Dropzone { static autoDiscover:boolean; static options:any; static confirm:(question:string, accepted:() => void, rejected?:() => void) => void; + static createElement(string: string): HTMLElement; + static isBrowserSupported():boolean; + static instances: Dropzone[]; static ADDED:string; static QUEUED:string; @@ -135,6 +142,7 @@ declare class Dropzone { static SUCCESS:string; files:Dropzone.DropzoneFile[]; + defaultOptions:Dropzone.DropzoneOptions; enable():void; @@ -148,18 +156,30 @@ declare class Dropzone { removeAllFiles(cancelIfNecessary?:boolean):void; + resizeImage(file:Dropzone.DropzoneFile, width?: number, height?: number, resizeMethod?: string, callback?:(...args:any[]) => void):void; + processQueue():void; cancelUpload(file:Dropzone.DropzoneFile):void; + createThumbnail(file:Dropzone.DropzoneFile, width?:number, height?:number, resizeMethod?:string, fixOrientation?: boolean, callback?:(...args:any[]) => void):any; + + createThumbnailFromUrl(file:Dropzone.DropzoneFile, width?: number, height?: number, resizeMethod?:string, fixOrientation?: boolean, callback?:(...args:any[]) => void, crossOrigin?:string):any; + processFiles(files:Dropzone.DropzoneFile[]):void; processFile(file:Dropzone.DropzoneFile):void; uploadFile(file:Dropzone.DropzoneFile):void; + uploadFiles(files:Dropzone.DropzoneFile[]):void; + getAcceptedFiles():Dropzone.DropzoneFile[]; + getActiveFiles(): Dropzone.DropzoneFile[] + + getAddedFiles() : Dropzone.DropzoneFile[]; + getRejectedFiles():Dropzone.DropzoneFile[]; getQueuedFiles():Dropzone.DropzoneFile[]; From 96f681f10c7250588976b66d3abded253c507e9e Mon Sep 17 00:00:00 2001 From: tedbcsgpro Date: Thu, 6 Jul 2017 11:26:53 -0700 Subject: [PATCH 0177/1618] updates style and formatting, missing semicolons --- types/dropzone/dropzone-tests.ts | 88 +++++---- types/dropzone/index.d.ts | 308 +++++++++++++++---------------- 2 files changed, 197 insertions(+), 199 deletions(-) diff --git a/types/dropzone/dropzone-tests.ts b/types/dropzone/dropzone-tests.ts index cad22badb7..53cedba333 100644 --- a/types/dropzone/dropzone-tests.ts +++ b/types/dropzone/dropzone-tests.ts @@ -1,7 +1,7 @@ const dropzoneFromString = new Dropzone(".test"); const dropzoneFromElement = new Dropzone(document.getElementById("test")); -const dropzoneRenameFunction = function (name:string):string { - return name + 'new'; +const dropzoneRenameFunction = function (name: string): string { + return name + 'new'; }; Dropzone.createElement('
'); @@ -22,10 +22,10 @@ const dropzoneWithOptions = new Dropzone(".test", { thumbnailHeight: 120, thumbnailMethod: 'crop', resizeWidth: 1024, - resizeHeight: 1024, - resizeMimeType: 'image.jpeg', - resizeQuality: .8, - resizeMethod: 'contain', + resizeHeight: 1024, + resizeMimeType: 'image.jpeg', + resizeQuality: .8, + resizeMethod: 'contain', filesizeBase: 1000, maxFiles: 100, params: { @@ -57,7 +57,7 @@ const dropzoneWithOptions = new Dropzone(".test", { dictRemoveFileConfirmation: "", dictMaxFilesExceeded: "", - accept: (file:Dropzone.DropzoneFile, done:(error?:string|Error) => void) => { + accept: (file: Dropzone.DropzoneFile, done: (error?: string | Error) => void) => { if (file.accepted) { file.previewElement.classList.add("accepted"); file.previewTemplate.classList.add("accepted"); @@ -71,7 +71,7 @@ const dropzoneWithOptions = new Dropzone(".test", { init: () => console.log("Initialized"), forceFallback: false, fallback: () => console.log("Fallback"), - resize: (file:Dropzone.DropzoneFile, width:120, height:120, resizeMethod:'contain') => ({ + resize: (file: Dropzone.DropzoneFile, width: 120, height: 120, resizeMethod: 'contain') => ({ srcX: 0, srcY: 0, trgX: 10, @@ -82,50 +82,50 @@ const dropzoneWithOptions = new Dropzone(".test", { trgHeight: 50, }), - drop: (e:DragEvent) => console.log("Drop"), - dragstart: (e:DragEvent) => console.log("Dragstart"), - dragend: (e:DragEvent) => console.log("Dragend"), - dragenter: (e:DragEvent) => console.log("Dragenter"), - dragover: (e:DragEvent) => console.log("Dragover"), - dragleave: (e:DragEvent) => console.log("Dragleave"), - paste: (e:DragEvent) => console.log("Paste"), + drop: (e: DragEvent) => console.log("Drop"), + dragstart: (e: DragEvent) => console.log("Dragstart"), + dragend: (e: DragEvent) => console.log("Dragend"), + dragenter: (e: DragEvent) => console.log("Dragenter"), + dragover: (e: DragEvent) => console.log("Dragover"), + dragleave: (e: DragEvent) => console.log("Dragleave"), + paste: (e: DragEvent) => console.log("Paste"), reset: () => console.log("Reset"), - addedfile: (file:Dropzone.DropzoneFile) => console.log("Addedfile"), - addedfiles: (files:Dropzone.DropzoneFile[]) => console.log("Addedfiles"), - removedfile: (file:Dropzone.DropzoneFile) => console.log("Removedfile"), - thumbnail: (file:Dropzone.DropzoneFile, dataUrl:string) => console.log("Thumbnail"), + addedfile: (file: Dropzone.DropzoneFile) => console.log("Addedfile"), + addedfiles: (files: Dropzone.DropzoneFile[]) => console.log("Addedfiles"), + removedfile: (file: Dropzone.DropzoneFile) => console.log("Removedfile"), + thumbnail: (file: Dropzone.DropzoneFile, dataUrl: string) => console.log("Thumbnail"), - error: (file:Dropzone.DropzoneFile, message:string|Error) => console.log("Error"), - errormultiple: (files:Dropzone.DropzoneFile[], message:string|Error) => console.log("Errormultiple"), + error: (file: Dropzone.DropzoneFile, message: string | Error) => console.log("Error"), + errormultiple: (files: Dropzone.DropzoneFile[], message: string | Error) => console.log("Errormultiple"), - processing: (file:Dropzone.DropzoneFile) => console.log("Processing"), - processingmultiple: (files:Dropzone.DropzoneFile[]) => console.log("Processingmultiple"), + processing: (file: Dropzone.DropzoneFile) => console.log("Processing"), + processingmultiple: (files: Dropzone.DropzoneFile[]) => console.log("Processingmultiple"), - uploadprogress: (file:Dropzone.DropzoneFile, progress:number, bytesSent:number) => console.log("Uploadprogress"), - totaluploadprogress: (totalProgress:number, totalBytes:number, totalBytesSent:number) => console.log("Totaluploadprogress"), + uploadprogress: (file: Dropzone.DropzoneFile, progress: number, bytesSent: number) => console.log("Uploadprogress"), + totaluploadprogress: (totalProgress: number, totalBytes: number, totalBytesSent: number) => console.log("Totaluploadprogress"), - sending: (file:Dropzone.DropzoneFile, xhr:XMLHttpRequest, formData:{}) => console.log("Sending"), - sendingmultiple: (files:Dropzone.DropzoneFile[], xhr:XMLHttpRequest, formData:{}) => console.log("Sendingmultiple"), + sending: (file: Dropzone.DropzoneFile, xhr: XMLHttpRequest, formData: {}) => console.log("Sending"), + sendingmultiple: (files: Dropzone.DropzoneFile[], xhr: XMLHttpRequest, formData: {}) => console.log("Sendingmultiple"), - success: (file:Dropzone.DropzoneFile) => console.log("Success"), - successmultiple: (files:Dropzone.DropzoneFile[]) => console.log("Successmultiple"), + success: (file: Dropzone.DropzoneFile) => console.log("Success"), + successmultiple: (files: Dropzone.DropzoneFile[]) => console.log("Successmultiple"), - canceled: (file:Dropzone.DropzoneFile) => console.log("Canceled"), - canceledmultiple: (file:Dropzone.DropzoneFile[]) => console.log("Canceledmultiple"), + canceled: (file: Dropzone.DropzoneFile) => console.log("Canceled"), + canceledmultiple: (file: Dropzone.DropzoneFile[]) => console.log("Canceledmultiple"), - complete: (file:Dropzone.DropzoneFile) => console.log("Complete"), - completemultiple: (file:Dropzone.DropzoneFile[]) => console.log("Completemultiple"), + complete: (file: Dropzone.DropzoneFile) => console.log("Complete"), + completemultiple: (file: Dropzone.DropzoneFile[]) => console.log("Completemultiple"), - maxfilesexceeded: (file:Dropzone.DropzoneFile) => console.log("Maxfilesexceeded"), - maxfilesreached: (files:Dropzone.DropzoneFile[]) => console.log("Maxfilesreached"), + maxfilesexceeded: (file: Dropzone.DropzoneFile) => console.log("Maxfilesexceeded"), + maxfilesreached: (files: Dropzone.DropzoneFile[]) => console.log("Maxfilesreached"), queuecomplete: () => console.log("Queuecomplete"), previewTemplate: "
", }); -var dropzoneWithOptionsVariations:Dropzone; +var dropzoneWithOptionsVariations: Dropzone; dropzoneWithOptionsVariations = new Dropzone(".test", { clickable: ".test" }); @@ -143,10 +143,10 @@ dropzoneWithOptionsVariations = new Dropzone(".test", { }); dropzoneWithOptionsVariations = new Dropzone(".test", { - success: (file:Dropzone.DropzoneFile, response:Object) => console.log(file, response) + success: (file: Dropzone.DropzoneFile, response: Object) => console.log(file, response) }); dropzoneWithOptionsVariations = new Dropzone(".test", { - success: (file:Dropzone.DropzoneFile, response:string) => console.log(file, response) + success: (file: Dropzone.DropzoneFile, response: string) => console.log(file, response) }); const dropzone = new Dropzone(".test"); @@ -154,8 +154,6 @@ const dropzone = new Dropzone(".test"); dropzone.enable(); dropzone.disable(); - - dropzone.files.forEach(f => { if (f.xhr) { console.log(f.xhr.readyState) @@ -195,7 +193,7 @@ dropzone.createThumbnailFromUrl(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.createThumbnailFromUrl(firstFile, dropzone.defaultOptions.resizeWidth, dropzone.defaultOptions.resizeHeight, dropzone.defaultOptions.resizeMethod, true, () => { console.log("createThumbnailFromUrl") }); -dropzone.accept(firstFile, (e:string|Error) => { +dropzone.accept(firstFile, (e: string | Error) => { console.log(e); }); @@ -227,7 +225,7 @@ dropzone.resizeImage(firstFile); dropzone.resizeImage(firstFile, 120); dropzone.resizeImage(firstFile, 120, 120); dropzone.resizeImage(firstFile, 120, 120, 'contain'); -dropzone.resizeImage(firstFile, 120, 120, 'contain', function(){}); +dropzone.resizeImage(firstFile, 120, 120, 'contain', function () { }); dropzone .on("drop", () => { @@ -318,9 +316,9 @@ dropzone console.count('queuecomplete'); }); - dropzone.off("drop", () => { - console.count('drop'); - }) +dropzone.off("drop", () => { + console.count('drop'); +}) .off("dragstart") .off(); diff --git a/types/dropzone/index.d.ts b/types/dropzone/index.d.ts index e410833e68..18a70ca7fb 100644 --- a/types/dropzone/index.d.ts +++ b/types/dropzone/index.d.ts @@ -8,14 +8,14 @@ declare namespace Dropzone { export interface DropzoneResizeInfo { - srcX?:number; - srcY?:number; - trgX?:number; - trgY?:number; - srcWidth?:number; - srcHeight?:number; - trgWidth?:number; - trgHeight?:number; + srcX?: number; + srcY?: number; + trgX?: number; + trgY?: number; + srcWidth?: number; + srcHeight?: number; + trgWidth?: number; + trgHeight?: number; } export interface DropzoneFile extends File { @@ -41,22 +41,22 @@ declare namespace Dropzone { thumbnailHeight?: number; thumbnailMethod?: string; resizeWidth?: number; - resizeHeight?: number; - resizeMimeType?: string; - resizeQuality?: number; - resizeMethod?: string; + resizeHeight?: number; + resizeMimeType?: string; + resizeQuality?: number; + resizeMethod?: string; filesizeBase?: number; maxFiles?: number; params?: {}; headers?: {}; - clickable?: boolean|string|HTMLElement|(string|HTMLElement)[]; + clickable?: boolean | string | HTMLElement | (string | HTMLElement)[]; ignoreHiddenFiles?: boolean; acceptedFiles?: string; - renameFilename?(name:string): string; + renameFilename?(name: string): string; autoProcessQueue?: boolean; autoQueue?: boolean; addRemoveLinks?: boolean; - previewsContainer?: boolean|string|HTMLElement; + previewsContainer?: boolean | string | HTMLElement; hiddenInputContainer?: HTMLElement; capture?: string; @@ -72,225 +72,225 @@ declare namespace Dropzone { dictRemoveFileConfirmation?: string; dictMaxFilesExceeded?: string; - accept?(file:DropzoneFile, done:(error?:string|Error) => void):void; - init?():void; + accept?(file: DropzoneFile, done: (error?: string | Error) => void): void; + init?(): void; forceFallback?: boolean; - fallback?():void; - resize?(file:DropzoneFile, width?: number, height?: number, resizeMethod?:string):DropzoneResizeInfo; + fallback?(): void; + resize?(file: DropzoneFile, width?: number, height?: number, resizeMethod?: string): DropzoneResizeInfo; - drop?(e:DragEvent):void; - dragstart?(e:DragEvent):void; - dragend?(e:DragEvent):void; - dragenter?(e:DragEvent):void; - dragover?(e:DragEvent):void; - dragleave?(e:DragEvent):void; - paste?(e:DragEvent):void; + drop?(e: DragEvent): void; + dragstart?(e: DragEvent): void; + dragend?(e: DragEvent): void; + dragenter?(e: DragEvent): void; + dragover?(e: DragEvent): void; + dragleave?(e: DragEvent): void; + paste?(e: DragEvent): void; - reset?():void; + reset?(): void; - addedfile?(file:DropzoneFile):void; - addedfiles?(files:DropzoneFile[]):void; - removedfile?(file:DropzoneFile):void; - thumbnail?(file:DropzoneFile, dataUrl:string):void; + addedfile?(file: DropzoneFile): void; + addedfiles?(files: DropzoneFile[]): void; + removedfile?(file: DropzoneFile): void; + thumbnail?(file: DropzoneFile, dataUrl: string): void; - error?(file:DropzoneFile, message:string|Error, xhr:XMLHttpRequest):void; - errormultiple?(files:DropzoneFile[], message:string|Error, xhr:XMLHttpRequest):void; + error?(file: DropzoneFile, message: string | Error, xhr: XMLHttpRequest): void; + errormultiple?(files: DropzoneFile[], message: string | Error, xhr: XMLHttpRequest): void; - processing?(file:DropzoneFile):void; - processingmultiple?(files:DropzoneFile[]):void; + processing?(file: DropzoneFile): void; + processingmultiple?(files: DropzoneFile[]): void; - uploadprogress?(file:DropzoneFile, progress:number, bytesSent:number):void; - totaluploadprogress?(totalProgress:number, totalBytes:number, totalBytesSent:number):void; + uploadprogress?(file: DropzoneFile, progress: number, bytesSent: number): void; + totaluploadprogress?(totalProgress: number, totalBytes: number, totalBytesSent: number): void; - sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; - sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; + sending?(file: DropzoneFile, xhr: XMLHttpRequest, formData: FormData): void; + sendingmultiple?(files: DropzoneFile[], xhr: XMLHttpRequest, formData: FormData): void; - success?(file: DropzoneFile, response: Object|string): void; - successmultiple?(files:DropzoneFile[], responseText:string):void; + success?(file: DropzoneFile, response: Object | string): void; + successmultiple?(files: DropzoneFile[], responseText: string): void; - canceled?(file:DropzoneFile):void; - canceledmultiple?(file:DropzoneFile[]):void; + canceled?(file: DropzoneFile): void; + canceledmultiple?(file: DropzoneFile[]): void; - complete?(file:DropzoneFile):void; - completemultiple?(file:DropzoneFile[]):void; + complete?(file: DropzoneFile): void; + completemultiple?(file: DropzoneFile[]): void; - maxfilesexceeded?(file:DropzoneFile):void; - maxfilesreached?(files:DropzoneFile[]):void; - queuecomplete?():void; + maxfilesexceeded?(file: DropzoneFile): void; + maxfilesreached?(files: DropzoneFile[]): void; + queuecomplete?(): void; previewTemplate?: string; } } declare class Dropzone { - constructor(container:string|HTMLElement, options?:Dropzone.DropzoneOptions); + constructor(container: string | HTMLElement, options?: Dropzone.DropzoneOptions); - static autoDiscover:boolean; - static options:any; - static confirm:(question:string, accepted:() => void, rejected?:() => void) => void; + static autoDiscover: boolean; + static options: any; + static confirm: (question: string, accepted: () => void, rejected?: () => void) => void; static createElement(string: string): HTMLElement; - static isBrowserSupported():boolean; + static isBrowserSupported(): boolean; static instances: Dropzone[]; - static ADDED:string; - static QUEUED:string; - static ACCEPTED:string; - static UPLOADING:string; - static PROCESSING:string; - static CANCELED:string; - static ERROR:string; - static SUCCESS:string; + static ADDED: string; + static QUEUED: string; + static ACCEPTED: string; + static UPLOADING: string; + static PROCESSING: string; + static CANCELED: string; + static ERROR: string; + static SUCCESS: string; - files:Dropzone.DropzoneFile[]; - defaultOptions:Dropzone.DropzoneOptions; + files: Dropzone.DropzoneFile[]; + defaultOptions: Dropzone.DropzoneOptions; - enable():void; + enable(): void; - disable():void; + disable(): void; - destroy():Dropzone; + destroy(): Dropzone; - addFile(file:Dropzone.DropzoneFile):void; + addFile(file: Dropzone.DropzoneFile): void; - removeFile(file:Dropzone.DropzoneFile):void; + removeFile(file: Dropzone.DropzoneFile): void; - removeAllFiles(cancelIfNecessary?:boolean):void; + removeAllFiles(cancelIfNecessary?: boolean): void; - resizeImage(file:Dropzone.DropzoneFile, width?: number, height?: number, resizeMethod?: string, callback?:(...args:any[]) => void):void; + resizeImage(file: Dropzone.DropzoneFile, width?: number, height?: number, resizeMethod?: string, callback?: (...args: any[]) => void): void; - processQueue():void; + processQueue(): void; - cancelUpload(file:Dropzone.DropzoneFile):void; + cancelUpload(file: Dropzone.DropzoneFile): void; - createThumbnail(file:Dropzone.DropzoneFile, width?:number, height?:number, resizeMethod?:string, fixOrientation?: boolean, callback?:(...args:any[]) => void):any; + createThumbnail(file: Dropzone.DropzoneFile, width?: number, height?: number, resizeMethod?: string, fixOrientation?: boolean, callback?: (...args: any[]) => void): any; - createThumbnailFromUrl(file:Dropzone.DropzoneFile, width?: number, height?: number, resizeMethod?:string, fixOrientation?: boolean, callback?:(...args:any[]) => void, crossOrigin?:string):any; + createThumbnailFromUrl(file: Dropzone.DropzoneFile, width?: number, height?: number, resizeMethod?: string, fixOrientation?: boolean, callback?: (...args: any[]) => void, crossOrigin?: string): any; - processFiles(files:Dropzone.DropzoneFile[]):void; + processFiles(files: Dropzone.DropzoneFile[]): void; - processFile(file:Dropzone.DropzoneFile):void; + processFile(file: Dropzone.DropzoneFile): void; - uploadFile(file:Dropzone.DropzoneFile):void; + uploadFile(file: Dropzone.DropzoneFile): void; - uploadFiles(files:Dropzone.DropzoneFile[]):void; + uploadFiles(files: Dropzone.DropzoneFile[]): void; - getAcceptedFiles():Dropzone.DropzoneFile[]; + getAcceptedFiles(): Dropzone.DropzoneFile[]; - getActiveFiles(): Dropzone.DropzoneFile[] + getActiveFiles(): Dropzone.DropzoneFile[]; - getAddedFiles() : Dropzone.DropzoneFile[]; - - getRejectedFiles():Dropzone.DropzoneFile[]; + getAddedFiles(): Dropzone.DropzoneFile[]; - getQueuedFiles():Dropzone.DropzoneFile[]; + getRejectedFiles(): Dropzone.DropzoneFile[]; - getUploadingFiles():Dropzone.DropzoneFile[]; + getQueuedFiles(): Dropzone.DropzoneFile[]; - accept(file:Dropzone.DropzoneFile, done:(error?:string|Error) => void):void; + getUploadingFiles(): Dropzone.DropzoneFile[]; - getActiveFiles():Dropzone.DropzoneFile[]; + accept(file: Dropzone.DropzoneFile, done: (error?: string | Error) => void): void; - getFilesWithStatus(status:string):Dropzone.DropzoneFile[]; + getActiveFiles(): Dropzone.DropzoneFile[]; - enqueueFile(file:Dropzone.DropzoneFile):void; + getFilesWithStatus(status: string): Dropzone.DropzoneFile[]; - enqueueFiles(file:Dropzone.DropzoneFile[]):void; + enqueueFile(file: Dropzone.DropzoneFile): void; - createThumbnail(file:Dropzone.DropzoneFile, callback?:(...args:any[]) => void):any; + enqueueFiles(file: Dropzone.DropzoneFile[]): void; - createThumbnailFromUrl(file:Dropzone.DropzoneFile, url:string, callback?:(...args:any[]) => void):any; + createThumbnail(file: Dropzone.DropzoneFile, callback?: (...args: any[]) => void): any; - on(eventName:string, callback:(...args:any[]) => void):Dropzone; + createThumbnailFromUrl(file: Dropzone.DropzoneFile, url: string, callback?: (...args: any[]) => void): any; + + on(eventName: string, callback: (...args: any[]) => void): Dropzone; off(): Dropzone; - off(eventName:string, callback?:(...args:any[]) => void):Dropzone; + off(eventName: string, callback?: (...args: any[]) => void): Dropzone; - emit(eventName:string, ...args:any[]):Dropzone; + emit(eventName: string, ...args: any[]): Dropzone; - on(eventName:"drop", callback:(e:DragEvent) => any):Dropzone; - on(eventName:"dragstart", callback:(e:DragEvent) => any):Dropzone; - on(eventName:"dragend", callback:(e:DragEvent) => any):Dropzone; - on(eventName:"dragenter", callback:(e:DragEvent) => any):Dropzone; - on(eventName:"dragover", callback:(e:DragEvent) => any):Dropzone; - on(eventName:"dragleave", callback:(e:DragEvent) => any):Dropzone; - on(eventName:"paste", callback:(e:DragEvent) => any):Dropzone; + on(eventName: "drop", callback: (e: DragEvent) => any): Dropzone; + on(eventName: "dragstart", callback: (e: DragEvent) => any): Dropzone; + on(eventName: "dragend", callback: (e: DragEvent) => any): Dropzone; + on(eventName: "dragenter", callback: (e: DragEvent) => any): Dropzone; + on(eventName: "dragover", callback: (e: DragEvent) => any): Dropzone; + on(eventName: "dragleave", callback: (e: DragEvent) => any): Dropzone; + on(eventName: "paste", callback: (e: DragEvent) => any): Dropzone; - on(eventName:"reset"):Dropzone; + on(eventName: "reset"): Dropzone; - on(eventName:"addedfile", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; - on(eventName:"addedfiles", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; - on(eventName:"removedfile", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; - on(eventName:"thumbnail", callback:(file:Dropzone.DropzoneFile, dataUrl:string) => any):Dropzone; + on(eventName: "addedfile", callback: (file: Dropzone.DropzoneFile) => any): Dropzone; + on(eventName: "addedfiles", callback: (files: Dropzone.DropzoneFile[]) => any): Dropzone; + on(eventName: "removedfile", callback: (file: Dropzone.DropzoneFile) => any): Dropzone; + on(eventName: "thumbnail", callback: (file: Dropzone.DropzoneFile, dataUrl: string) => any): Dropzone; - on(eventName:"error", callback:(file:Dropzone.DropzoneFile, message:string|Error) => any):Dropzone; - on(eventName:"errormultiple", callback:(files:Dropzone.DropzoneFile[], message:string|Error) => any):Dropzone; + on(eventName: "error", callback: (file: Dropzone.DropzoneFile, message: string | Error) => any): Dropzone; + on(eventName: "errormultiple", callback: (files: Dropzone.DropzoneFile[], message: string | Error) => any): Dropzone; - on(eventName:"processing", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; - on(eventName:"processingmultiple", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; + on(eventName: "processing", callback: (file: Dropzone.DropzoneFile) => any): Dropzone; + on(eventName: "processingmultiple", callback: (files: Dropzone.DropzoneFile[]) => any): Dropzone; - on(eventName:"uploadprogress", callback:(file:Dropzone.DropzoneFile, progress:number, bytesSent:number) => any):Dropzone; - on(eventName:"totaluploadprogress", callback:(totalProgress:number, totalBytes:number, totalBytesSent:number) => any):Dropzone; + on(eventName: "uploadprogress", callback: (file: Dropzone.DropzoneFile, progress: number, bytesSent: number) => any): Dropzone; + on(eventName: "totaluploadprogress", callback: (totalProgress: number, totalBytes: number, totalBytesSent: number) => any): Dropzone; - on(eventName:"sending", callback:(file:Dropzone.DropzoneFile, xhr:XMLHttpRequest, formData:FormData) => any):Dropzone; - on(eventName:"sendingmultiple", callback:(files:Dropzone.DropzoneFile[], xhr:XMLHttpRequest, formData:FormData) => any):Dropzone; + on(eventName: "sending", callback: (file: Dropzone.DropzoneFile, xhr: XMLHttpRequest, formData: FormData) => any): Dropzone; + on(eventName: "sendingmultiple", callback: (files: Dropzone.DropzoneFile[], xhr: XMLHttpRequest, formData: FormData) => any): Dropzone; - on(eventName:"success", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; - on(eventName:"successmultiple", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; + on(eventName: "success", callback: (file: Dropzone.DropzoneFile) => any): Dropzone; + on(eventName: "successmultiple", callback: (files: Dropzone.DropzoneFile[]) => any): Dropzone; - on(eventName:"canceled", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; - on(eventName:"canceledmultiple", callback:(file:Dropzone.DropzoneFile[]) => any):Dropzone; + on(eventName: "canceled", callback: (file: Dropzone.DropzoneFile) => any): Dropzone; + on(eventName: "canceledmultiple", callback: (file: Dropzone.DropzoneFile[]) => any): Dropzone; - on(eventName:"complete", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; - on(eventName:"completemultiple", callback:(file:Dropzone.DropzoneFile[]) => any):Dropzone; + on(eventName: "complete", callback: (file: Dropzone.DropzoneFile) => any): Dropzone; + on(eventName: "completemultiple", callback: (file: Dropzone.DropzoneFile[]) => any): Dropzone; - on(eventName:"maxfilesexceeded", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; - on(eventName:"maxfilesreached", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; - on(eventName:"queuecomplete"):Dropzone; + on(eventName: "maxfilesexceeded", callback: (file: Dropzone.DropzoneFile) => any): Dropzone; + on(eventName: "maxfilesreached", callback: (files: Dropzone.DropzoneFile[]) => any): Dropzone; + on(eventName: "queuecomplete"): Dropzone; - emit(eventName:"drop", e:DragEvent):Dropzone; - emit(eventName:"dragstart", e:DragEvent):Dropzone; - emit(eventName:"dragend", e:DragEvent):Dropzone; - emit(eventName:"dragenter", e:DragEvent):Dropzone; - emit(eventName:"dragover", e:DragEvent):Dropzone; - emit(eventName:"dragleave", e:DragEvent):Dropzone; - emit(eventName:"paste", e:DragEvent):Dropzone; + emit(eventName: "drop", e: DragEvent): Dropzone; + emit(eventName: "dragstart", e: DragEvent): Dropzone; + emit(eventName: "dragend", e: DragEvent): Dropzone; + emit(eventName: "dragenter", e: DragEvent): Dropzone; + emit(eventName: "dragover", e: DragEvent): Dropzone; + emit(eventName: "dragleave", e: DragEvent): Dropzone; + emit(eventName: "paste", e: DragEvent): Dropzone; - emit(eventName:"reset"):Dropzone; + emit(eventName: "reset"): Dropzone; - emit(eventName:"addedfile", file:Dropzone.DropzoneFile):Dropzone; - emit(eventName:"addedfiles", files:Dropzone.DropzoneFile[]):Dropzone; - emit(eventName:"removedfile", file:Dropzone.DropzoneFile):Dropzone; - emit(eventName:"thumbnail", file:Dropzone.DropzoneFile, dataUrl:string):Dropzone; + emit(eventName: "addedfile", file: Dropzone.DropzoneFile): Dropzone; + emit(eventName: "addedfiles", files: Dropzone.DropzoneFile[]): Dropzone; + emit(eventName: "removedfile", file: Dropzone.DropzoneFile): Dropzone; + emit(eventName: "thumbnail", file: Dropzone.DropzoneFile, dataUrl: string): Dropzone; - emit(eventName:"error", file:Dropzone.DropzoneFile, message:string|Error):Dropzone; - emit(eventName:"errormultiple", files:Dropzone.DropzoneFile[], message:string|Error):Dropzone; + emit(eventName: "error", file: Dropzone.DropzoneFile, message: string | Error): Dropzone; + emit(eventName: "errormultiple", files: Dropzone.DropzoneFile[], message: string | Error): Dropzone; - emit(eventName:"processing", file:Dropzone.DropzoneFile):Dropzone; - emit(eventName:"processingmultiple", files:Dropzone.DropzoneFile[]):Dropzone; + emit(eventName: "processing", file: Dropzone.DropzoneFile): Dropzone; + emit(eventName: "processingmultiple", files: Dropzone.DropzoneFile[]): Dropzone; - emit(eventName:"uploadprogress", file:Dropzone.DropzoneFile, progress:number, bytesSent:number):Dropzone; - emit(eventName:"totaluploadprogress", totalProgress:number, totalBytes:number, totalBytesSent:number):Dropzone; + emit(eventName: "uploadprogress", file: Dropzone.DropzoneFile, progress: number, bytesSent: number): Dropzone; + emit(eventName: "totaluploadprogress", totalProgress: number, totalBytes: number, totalBytesSent: number): Dropzone; - emit(eventName:"sending", file:Dropzone.DropzoneFile, xhr:XMLHttpRequest, formData:FormData):Dropzone; - emit(eventName:"sendingmultiple", files:Dropzone.DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):Dropzone; + emit(eventName: "sending", file: Dropzone.DropzoneFile, xhr: XMLHttpRequest, formData: FormData): Dropzone; + emit(eventName: "sendingmultiple", files: Dropzone.DropzoneFile[], xhr: XMLHttpRequest, formData: FormData): Dropzone; - emit(eventName:"success", file:Dropzone.DropzoneFile):Dropzone; - emit(eventName:"successmultiple", files:Dropzone.DropzoneFile[]):Dropzone; + emit(eventName: "success", file: Dropzone.DropzoneFile): Dropzone; + emit(eventName: "successmultiple", files: Dropzone.DropzoneFile[]): Dropzone; - emit(eventName:"canceled", file:Dropzone.DropzoneFile):Dropzone; - emit(eventName:"canceledmultiple", file:Dropzone.DropzoneFile[]):Dropzone; + emit(eventName: "canceled", file: Dropzone.DropzoneFile): Dropzone; + emit(eventName: "canceledmultiple", file: Dropzone.DropzoneFile[]): Dropzone; - emit(eventName:"complete", file:Dropzone.DropzoneFile):Dropzone; - emit(eventName:"completemultiple", file:Dropzone.DropzoneFile[]):Dropzone; + emit(eventName: "complete", file: Dropzone.DropzoneFile): Dropzone; + emit(eventName: "completemultiple", file: Dropzone.DropzoneFile[]): Dropzone; - emit(eventName:"maxfilesexceeded", file:Dropzone.DropzoneFile):Dropzone; - emit(eventName:"maxfilesreached", files:Dropzone.DropzoneFile[]):Dropzone; - emit(eventName:"queuecomplete"):Dropzone; + emit(eventName: "maxfilesexceeded", file: Dropzone.DropzoneFile): Dropzone; + emit(eventName: "maxfilesreached", files: Dropzone.DropzoneFile[]): Dropzone; + emit(eventName: "queuecomplete"): Dropzone; } interface JQuery { - dropzone(options:Dropzone.DropzoneOptions): Dropzone; + dropzone(options: Dropzone.DropzoneOptions): Dropzone; } export = Dropzone; From 03d228ff8e57bf7948e8f3f42579606af7882b14 Mon Sep 17 00:00:00 2001 From: nearbydelta Date: Fri, 7 Jul 2017 06:40:13 +0900 Subject: [PATCH 0178/1618] Fix the definition of class Note in VexFlow. - The Note constructor should accept either zero argument or one argument. --- types/vexflow/index.d.ts | 6 +++--- types/vexflow/vexflow-tests.ts | 10 +++++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/types/vexflow/index.d.ts b/types/vexflow/index.d.ts index 3c3aa2365a..873e6cc044 100644 --- a/types/vexflow/index.d.ts +++ b/types/vexflow/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for VexFlow v1.2.83 +// Type definitions for VexFlow v1.2.84 // Project: http://vexflow.com // Definitions by: Roman Quiring // Sebastian Haas @@ -618,8 +618,8 @@ declare namespace Vex { getTickMultiplier() : Fraction; applyTickMultiplier(numerator : number, denominator : number) : void; setDuration(duration : Fraction) : void; - - constructor(note_struct : {type? : string, dots? : number, duration : string}); + + constructor(note_struct? : {type? : string, dots? : number, duration : string}); getPlayNote() : any; setPlayNote(note : any) : Note; isRest() : boolean; diff --git a/types/vexflow/vexflow-tests.ts b/types/vexflow/vexflow-tests.ts index 52a031ac1b..6a9187c7e5 100644 --- a/types/vexflow/vexflow-tests.ts +++ b/types/vexflow/vexflow-tests.ts @@ -34,16 +34,20 @@ notes1[2].addModifier(0, new Vex.Flow.GraceNoteGroup([gracenote], true).beamNote // Color the chord notes1[3].setStyle({fillStyle: "blue", strokeStyle: "blue"}); +// Add a bar +var tickable1: Vex.Flow.Note[] = notes1; +tickable1.push(new Vex.Flow.BarNote()); + // Create a voice in 4/4 and add notes var voice1 = new Vex.Flow.Voice({ num_beats: 4, beat_value: 4, resolution: Vex.Flow.RESOLUTION -}).addTickables(notes1); +}).addTickables(tickable1); // Create a second voice with just one whole note var voice2 = new Vex.Flow.Voice(Vex.Flow.TIME4_4). - addTickables([new Vex.Flow.StaveNote({keys: ["c/4"], duration: "w"})]); + addTickables([new Vex.Flow.StaveNote({keys: ["c/4"], duration: "w"}), new Vex.Flow.BarNote()]); // Format and justify the notes to 550 pixels var formatter = new Vex.Flow.Formatter(). @@ -85,4 +89,4 @@ var notes = [ ]; // Format ad draw the notes -Vex.Flow.Formatter.FormatAndDraw(ctx, tabstave, notes); \ No newline at end of file +Vex.Flow.Formatter.FormatAndDraw(ctx, tabstave, notes); From 816fa90b77b83a4ba0af94d972b1e8fd5e362196 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 08:26:25 +0800 Subject: [PATCH 0179/1618] add color.d.ts --- types/zui/color.d.ts | 31 +++++++++++++++++++++++++++++++ types/zui/index.d.ts | 2 +- types/zui/tsconfig.json | 2 +- types/zui/zui-tests.ts | 14 +++++++++++++- 4 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 types/zui/color.d.ts diff --git a/types/zui/color.d.ts b/types/zui/color.d.ts new file mode 100644 index 0000000000..e19e13c3c2 --- /dev/null +++ b/types/zui/color.d.ts @@ -0,0 +1,31 @@ +interface Color { + rgb(rgbaColor?: string): object; + hue(hue: string): string, + darken(percent: number): string; + lighten(percent: number): string; + clone(): Color; + fade(percent: number): any; + toHsl(): object; + luma(): string; + saturate(): string; + contrast(dark: string, light: string, threshold: number): string; + hexStr(): string; + toCssStr(): string; +} + +interface ColorStatic { + new (): Color; + new (hexStr: string): Color; + new (r: number, g: number, b: number): Color; + new (r: number, g: number, b: number, a: number): Color; + new (rgbColorOrRgbaColorOrName: string): Color; + isColor(str: string): boolean; + names: Array; +} +interface ColorSet { + get(name: string): Color; +} +interface ZuiStatic { + Color: ColorStatic; + colorset: ColorSet; +} \ No newline at end of file diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index da8e423a85..4db802ff52 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -12,7 +12,7 @@ /// /// - +/// /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. diff --git a/types/zui/tsconfig.json b/types/zui/tsconfig.json index 83e99ace31..06fa3ab094 100644 --- a/types/zui/tsconfig.json +++ b/types/zui/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "zui-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index 51437097a6..9848744732 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -173,4 +173,16 @@ $('select.chosen-select').chosen({ no_results_text: '没有找到', // 当检索时没有找到匹配项时显示的提示文本 disable_search_threshold: 10, // 10 个以下的选择项则不显示检索框 search_contains: true // 从任意位置开始检索 -}); \ No newline at end of file +}); + +/** + * color + */ +// 创建颜色实例 +var myColor = new $.zui.Color('#095823'); + +// 调用实例方法 +var myHsl = myColor.toHsl(); + +var zuiPrimaryColor = $.zui.colorset.get('primary'); +console.log('ZUI primary color is', zuiPrimaryColor.toCssStr()); \ No newline at end of file From 8d32ba9f6b4fee6ebf743fe86a6b9ee61376bcdd Mon Sep 17 00:00:00 2001 From: Mohsen Azimi Date: Thu, 6 Jul 2017 18:30:14 -0700 Subject: [PATCH 0180/1618] make devtoolModuleFilenameTemplate accept a function Reference https://github.com/facebookincubator/create-react-app/blob/567d981ee28188a78731b4c45aedaa60b22a03bd/packages/react-scripts/config/webpack.config.dev.js#L81 --- types/webpack/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 88cf8a6318..43295be8b9 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -106,7 +106,7 @@ declare namespace webpack { /** The filename of the SourceMaps for the JavaScript files. They are inside the output.path directory. */ sourceMapFilename?: string; /** Filename template string of function for the sources array in a generated SourceMap. */ - devtoolModuleFilenameTemplate?: string; + devtoolModuleFilenameTemplate?: string | (info: any) => string; /** Similar to output.devtoolModuleFilenameTemplate, but used in the case of duplicate module identifiers. */ devtoolFallbackModuleFilenameTemplate?: string; /** From 79db06a10ede2c84fcf9c03a6c1fcafe9c3cdedd Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 09:47:13 +0800 Subject: [PATCH 0181/1618] add draggable --- types/zui/draggable.d.ts | 32 ++++++++++++++ types/zui/index.d.ts | 2 +- types/zui/zui-tests.ts | 95 ++++++++++++++++++++++++---------------- 3 files changed, 90 insertions(+), 39 deletions(-) create mode 100644 types/zui/draggable.d.ts diff --git a/types/zui/draggable.d.ts b/types/zui/draggable.d.ts new file mode 100644 index 0000000000..723c304fc7 --- /dev/null +++ b/types/zui/draggable.d.ts @@ -0,0 +1,32 @@ + +interface Postion { + left: number; + top: number; + width: number; + height: number; +} +interface DraggableEvent { + event?: object; + element?: object; + pos?: Postion; + offset?: object; + smallOffset?: object; + startOffset?: object; + +} +interface DraggableOption { + container?: string, + move?: boolean; + selector?: string, + handle?: string, + mouseButton?: string, + stopPropagation?: boolean, + before?(e?: DraggableEvent): boolean; + drag?(e: DraggableEvent): void; + finish?(e: DraggableEvent): void +} + +interface JQuery { + draggable(command: string): JQuery; + draggable(option: DraggableOption): JQuery; +} \ No newline at end of file diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index 4db802ff52..78ce948431 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -13,7 +13,7 @@ /// /// - +/// /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. *~ Otherwise, delete this declaration. diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index 9848744732..426a54ce43 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -83,7 +83,7 @@ $('#myPopover').popover('show'); * collapse */ $('#myCollapseContent').collapse({ - toggle: false + toggle: false }); $().collapse('show') @@ -101,22 +101,22 @@ $('.carousel').carousel() */ // 仅选择日期 $(".form-date").datetimepicker( -{ - language: "zh-CN", - weekStart: 1, - todayBtn: 1, - autoclose: 1, - todayHighlight: 1, - startView: 2, - minView: 2, - forceParse: 0, - format: "yyyy-mm-dd" -}); + { + language: "zh-CN", + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 2, + minView: 2, + forceParse: 0, + format: "yyyy-mm-dd" + }); // 选择时间 $(".form-time").datetimepicker({ - language: "zh-CN", + language: "zh-CN", weekStart: 1, - todayBtn: 1, + todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 1, @@ -127,35 +127,35 @@ $(".form-time").datetimepicker({ }); // 选择时间和日期 $(".form-datetime").datetimepicker( -{ - weekStart: 1, - todayBtn: 1, - autoclose: 1, - todayHighlight: 1, - startView: 2, - forceParse: 0, - showMeridian: 1, - format: "yyyy-mm-dd hh:ii" -}); + { + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 2, + forceParse: 0, + showMeridian: 1, + format: "yyyy-mm-dd hh:ii" + }); // 仅选择日期 $(".form-date").datetimepicker( -{ - language: "zh-CN", - weekStart: 1, - todayBtn: 1, - autoclose: 1, - todayHighlight: 1, - startView: 2, - minView: 2, - forceParse: 0, - format: "yyyy-mm-dd" -}); + { + language: "zh-CN", + weekStart: 1, + todayBtn: 1, + autoclose: 1, + todayHighlight: 1, + startView: 2, + minView: 2, + forceParse: 0, + format: "yyyy-mm-dd" + }); // 选择时间 $(".form-time").datetimepicker({ - language: "zh-CN", + language: "zh-CN", weekStart: 1, - todayBtn: 1, + todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 1, @@ -185,4 +185,23 @@ var myColor = new $.zui.Color('#095823'); var myHsl = myColor.toHsl(); var zuiPrimaryColor = $.zui.colorset.get('primary'); -console.log('ZUI primary color is', zuiPrimaryColor.toCssStr()); \ No newline at end of file +console.log('ZUI primary color is', zuiPrimaryColor.toCssStr()); + +/** + * + */ +let count = 0; +$('#draggableBtn').draggable({ + container: '#draggableBox', + before: function () { + console.log(count++ + ': ' + '[开始] 拖动...\n'); + return true; + }, + drag: function (e: DraggableEvent) { + console.log(count++ + ': ' + '拖动: pos = ' + JSON.stringify(e.pos) + ', offset = ' + JSON.stringify(e.offset) + '\n'); + // console.log('(' + e.pos.left + ', ' + e.pos.top + ')'); + }, + finish: function (e: DraggableEvent) { + console.log(count++ + ': ' + '[完毕]:pos = ' + JSON.stringify(e.pos) + ', offset = ' + JSON.stringify(e.offset) + '\n'); + } +}); \ No newline at end of file From 07170475ac8ad88984f173d2ebc48897ae55783f Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 09:54:47 +0800 Subject: [PATCH 0182/1618] add droppable --- types/zui/droppable.d.ts | 41 ++++++++++++++++++++++++++++++++++++++++ types/zui/index.d.ts | 3 +++ types/zui/zui-tests.ts | 27 +++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 types/zui/droppable.d.ts diff --git a/types/zui/droppable.d.ts b/types/zui/droppable.d.ts new file mode 100644 index 0000000000..24fccfd501 --- /dev/null +++ b/types/zui/droppable.d.ts @@ -0,0 +1,41 @@ + +interface Postion { + left: number; + top: number; + width: number; + height: number; +} +interface DroppableEvent { + event?: object; + element?: JQuery; + target?: JQuery; + pos?: Postion; + offset?: object; + smallOffset?: object; + startOffset?: object; + +} +interface DraggableOption { + container?: string, + selector?: string, + handle?: string, + target: JQuery | string, + + flex?: boolean, + deviation?: number, + sensorOffsetX?: number, + sensorOffsetY?: number, + + stopPropagation?: boolean, + before?(e?: DroppableEvent): boolean; + start?(e?: DroppableEvent): void; + drop?(e: DroppableEvent): void; + beforeDrop?(e: DroppableEvent): boolean; + finish?(e: DroppableEvent): void; + always?(e: DroppableEvent): void; +} + +interface JQuery { + droppable(command: string): JQuery; + droppable(option: DraggableOption): JQuery; +} \ No newline at end of file diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index 78ce948431..5e97854f83 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -14,6 +14,9 @@ /// /// /// +/// + + /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. *~ Otherwise, delete this declaration. diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index 426a54ce43..f407f0f054 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -188,7 +188,7 @@ var zuiPrimaryColor = $.zui.colorset.get('primary'); console.log('ZUI primary color is', zuiPrimaryColor.toCssStr()); /** - * + * draggable */ let count = 0; $('#draggableBtn').draggable({ @@ -204,4 +204,29 @@ $('#draggableBtn').draggable({ finish: function (e: DraggableEvent) { console.log(count++ + ': ' + '[完毕]:pos = ' + JSON.stringify(e.pos) + ', offset = ' + JSON.stringify(e.offset) + '\n'); } +}); + +/** + * droppable + */ +$('#multiDroppableContainer').droppable({ + selector: '.btn-droppable', // 定义允许拖放的元素 + target: '.droppable-target', + start: function () { + $('#multiDroppableContainer .droppable-target').removeClass('panel-warning').removeClass('panel-success').find('.panel-heading').text('拖动到这里吗?'); + }, + drop: function (event: DroppableEvent) { + var msg = '真棒!'; + $('#multiDroppableContainer .droppable-target').removeClass('panel-success').removeClass('panel-warning'); + if (event.target && event.element) { + var elementId = event.element.find('.btn-droppable-id').text(); + event.target.addClass('panel-success').find('.panel-heading').text('成功将【按钮#' + elementId + '】拖到目的地。'); + msg += '成功拖动【按钮#' + elementId + '】到区域 ' + event.target.find('.area-name').text(); + } + $.zui.messager.show(msg); + }, + drag: function (event: DroppableEvent) { + $('#multiDroppableContainer .droppable-target').removeClass('panel-success').removeClass('panel-warning'); + if (event.target) event.target.addClass('panel-warning'); + } }); \ No newline at end of file From 0a93d659eaa9b0048bdc5f3d15743f5f52befb43 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 10:18:12 +0800 Subject: [PATCH 0183/1618] add sortable --- types/zui/draggable.d.ts | 3 ++- types/zui/droppable.d.ts | 8 ++++---- types/zui/index.d.ts | 2 +- types/zui/sortable.d.ts | 21 +++++++++++++++++++++ types/zui/zui-tests.ts | 17 ++++++++++++++++- 5 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 types/zui/sortable.d.ts diff --git a/types/zui/draggable.d.ts b/types/zui/draggable.d.ts index 723c304fc7..163d5cfa5d 100644 --- a/types/zui/draggable.d.ts +++ b/types/zui/draggable.d.ts @@ -7,7 +7,8 @@ interface Postion { } interface DraggableEvent { event?: object; - element?: object; + element?: JQuery | object; + target?: JQuery | object; pos?: Postion; offset?: object; smallOffset?: object; diff --git a/types/zui/droppable.d.ts b/types/zui/droppable.d.ts index 24fccfd501..d06c762a6c 100644 --- a/types/zui/droppable.d.ts +++ b/types/zui/droppable.d.ts @@ -15,7 +15,7 @@ interface DroppableEvent { startOffset?: object; } -interface DraggableOption { +interface DroppableOption { container?: string, selector?: string, handle?: string, @@ -26,16 +26,16 @@ interface DraggableOption { sensorOffsetX?: number, sensorOffsetY?: number, - stopPropagation?: boolean, before?(e?: DroppableEvent): boolean; start?(e?: DroppableEvent): void; - drop?(e: DroppableEvent): void; + drag?(e: DroppableEvent): void; beforeDrop?(e: DroppableEvent): boolean; + drop?(e: DroppableEvent): void; finish?(e: DroppableEvent): void; always?(e: DroppableEvent): void; } interface JQuery { droppable(command: string): JQuery; - droppable(option: DraggableOption): JQuery; + droppable(option: DroppableOption): JQuery; } \ No newline at end of file diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index 5e97854f83..e3699d1223 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -15,7 +15,7 @@ /// /// /// - +/// /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. diff --git a/types/zui/sortable.d.ts b/types/zui/sortable.d.ts new file mode 100644 index 0000000000..4c3fc55bc1 --- /dev/null +++ b/types/zui/sortable.d.ts @@ -0,0 +1,21 @@ +interface SortEvent { + list: Array; + element: JQuery | object; +} + +interface SortableOption { + selector?: string, + trigger?: string, + reverse?: boolean, + dragCssClass?: string, + sortingClass?: string, + mouseButton?: string, + start?(e?: SortEvent): void; + order?(e?: SortEvent): void; + finish?(e?: SortEvent): void; +} + +interface JQuery { + sortable(command?: string): JQuery + sortable(option?: SortableOption): JQuery +} \ No newline at end of file diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index f407f0f054..859b65b4e1 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -229,4 +229,19 @@ $('#multiDroppableContainer').droppable({ $('#multiDroppableContainer .droppable-target').removeClass('panel-success').removeClass('panel-warning'); if (event.target) event.target.addClass('panel-warning'); } -}); \ No newline at end of file +}); + +/** + * sortable + */ +// 定义选项对象 +var options = { + selector: '.sortable-item', + finish: function (e: SortEvent) { + console.log('排序完成:', e); + }, + // 设置更多选项... +}; + +// 初始化时传入选项参数 +$('#sortableList').sortable(options) \ No newline at end of file From ed17ae55a75afee306a3e9730665fe71676dfd6d Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 7 Jul 2017 12:51:17 +0900 Subject: [PATCH 0184/1618] Add definitions for react-transition-group v2 --- .../react-transition-group/CSSTransition.d.ts | 20 +++ types/react-transition-group/Transition.d.ts | 24 ++++ .../TransitionGroup.d.ts | 21 +-- types/react-transition-group/index.d.ts | 30 ++-- .../react-transition-group-tests.tsx | 130 ++++++++++-------- types/react-transition-group/tsconfig.json | 8 +- .../{ => v1}/CSSTransitionGroup.d.ts | 0 .../v1/TransitionGroup.d.ts | 19 +++ types/react-transition-group/v1/index.d.ts | 29 ++++ .../v1/react-transition-group-tests.tsx | 73 ++++++++++ types/react-transition-group/v1/tsconfig.json | 27 ++++ types/react-transition-group/v1/tslint.json | 1 + 12 files changed, 282 insertions(+), 100 deletions(-) create mode 100644 types/react-transition-group/CSSTransition.d.ts create mode 100644 types/react-transition-group/Transition.d.ts rename types/react-transition-group/{ => v1}/CSSTransitionGroup.d.ts (100%) create mode 100644 types/react-transition-group/v1/TransitionGroup.d.ts create mode 100644 types/react-transition-group/v1/index.d.ts create mode 100644 types/react-transition-group/v1/react-transition-group-tests.tsx create mode 100644 types/react-transition-group/v1/tsconfig.json create mode 100644 types/react-transition-group/v1/tslint.json diff --git a/types/react-transition-group/CSSTransition.d.ts b/types/react-transition-group/CSSTransition.d.ts new file mode 100644 index 0000000000..49d9bde183 --- /dev/null +++ b/types/react-transition-group/CSSTransition.d.ts @@ -0,0 +1,20 @@ +import { Component } from "react"; +import { TransitionActions } from "react-transition-group"; +import { TransitionProps } from "react-transition-group/Transition"; + +export interface CSSTransitionClassNames { + appear?: string; + appearActive?: string; + enter?: string; + enterActive?: string; + exit?: string; + exitActive?: string; +} + +export interface CSSTransitionProps extends TransitionProps { + classNames: string | CSSTransitionClassNames; +} + +declare class CSSTransition extends Component {} + +export default CSSTransition; diff --git a/types/react-transition-group/Transition.d.ts b/types/react-transition-group/Transition.d.ts new file mode 100644 index 0000000000..29387be19c --- /dev/null +++ b/types/react-transition-group/Transition.d.ts @@ -0,0 +1,24 @@ +import { Component, HTMLProps } from "react"; +import { TransitionActions } from "react-transition-group"; + +export type EndHandler = (node: HTMLElement, done: () => void) => void; +export type EnterHandler = (node: HTMLElement, isAppearing: boolean) => void; +export type ExitHandler = (node: HTMLElement) => void; + +export interface TransitionProps extends TransitionActions, HTMLProps { + in?: boolean; + mountOnEnter?: boolean; + unmountOnExit?: boolean; + timeout: number | { enter?: number, exit?: number }; + addEndListener?: EndHandler; + onEnter?: EnterHandler; + onEntering?: EnterHandler; + onEntered?: EnterHandler; + onExit?: ExitHandler; + onExiting?: ExitHandler; + onExited?: ExitHandler; +} + +declare class Transition extends Component {} + +export default Transition; diff --git a/types/react-transition-group/TransitionGroup.d.ts b/types/react-transition-group/TransitionGroup.d.ts index 44d9100889..fb169c2d8f 100644 --- a/types/react-transition-group/TransitionGroup.d.ts +++ b/types/react-transition-group/TransitionGroup.d.ts @@ -1,19 +1,10 @@ -import { Component, HTMLAttributes, ReactElement, ReactType } from "react"; -import { HTMLTransitionGroupProps } from "./index"; +import { Component, ReactType, HTMLProps } from "react"; +import { TransitionActions } from "react-transition-group"; -declare namespace TransitionGroup { - interface TransitionGroupChildLifecycle { - componentWillAppear?(callback: () => void): void; - componentDidAppear?(): void; - componentWillEnter?(callback: () => void): void; - componentDidEnter?(): void; - componentWillLeave?(callback: () => void): void; - componentDidLeave?(): void; - } - - type TransitionGroupProps = HTMLTransitionGroupProps; +export interface TransitionGroupProps extends TransitionActions, HTMLProps { + component?: ReactType; } -declare class TransitionGroup extends Component {} +declare class TransitionGroup extends Component {} -export = TransitionGroup; +export default TransitionGroup; diff --git a/types/react-transition-group/index.d.ts b/types/react-transition-group/index.d.ts index 3c82827b46..62136d8ea4 100644 --- a/types/react-transition-group/index.d.ts +++ b/types/react-transition-group/index.d.ts @@ -1,29 +1,15 @@ -// Type definitions for react-transition-group 1.1 +// Type definitions for react-transition-group 2.0 // Project: https://github.com/reactjs/react-transition-group // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { HTMLAttributes, ReactElement, ReactType } from "react"; +export { default as CSSTransition, CSSTransitionProps, CSSTransitionClassNames } from "react-transition-group/CSSTransition"; +export { default as Transition, TransitionProps } from "react-transition-group/Transition"; +export { default as TransitionGroup, TransitionGroupProps } from "react-transition-group/TransitionGroup"; -export interface HTMLTransitionGroupProps extends HTMLAttributes { - component?: ReactType; - childFactory?(child: ReactElement): ReactElement; +export interface TransitionActions { + appear?: boolean; + enter?: boolean; + exit?: boolean; } - -import * as TransitionGroup from "./TransitionGroup"; -export { - TransitionGroupProps, - TransitionGroupChildLifecycle -} from "./TransitionGroup"; - -import * as CSSTransitionGroup from "./CSSTransitionGroup"; -export { - CSSTransitionGroupProps, - CSSTransitionGroupTransitionName -} from "./CSSTransitionGroup"; - -export { - TransitionGroup, - CSSTransitionGroup -}; diff --git a/types/react-transition-group/react-transition-group-tests.tsx b/types/react-transition-group/react-transition-group-tests.tsx index 346fe9989a..53d3e9b22e 100644 --- a/types/react-transition-group/react-transition-group-tests.tsx +++ b/types/react-transition-group/react-transition-group-tests.tsx @@ -1,73 +1,81 @@ import * as React from "react"; -import * as TransitionGroup from "react-transition-group/TransitionGroup"; -import * as CSSTransitionGroup from "react-transition-group/CSSTransitionGroup"; -import { CSSTransitionGroupProps, TransitionGroupProps, TransitionGroupChildLifecycle } from "react-transition-group"; - -class TestChild extends React.Component implements TransitionGroupChildLifecycle { - componentWillAppear(callback: () => void) { - callback(); - } - - componentDidAppear() {} - - componentWillEnter(callback: () => void) { - callback(); - } - - componentDidEnter() {} - - componentWillLeave(callback: () => void) { - callback(); - } - - componentDidLeave() {} - - render() { - return (
  • { "Test" }
  • ); - } -} +import CSSTransition from "react-transition-group/CSSTransition"; +import Transition from "react-transition-group/Transition"; +import TransitionGroup from "react-transition-group/TransitionGroup"; +import { CSSTransitionProps, TransitionProps, TransitionGroupProps } from "react-transition-group"; const Test: React.StatelessComponent = () => { + function handleEnter(node: HTMLElement, isAppearing: boolean) {} + + function handleExit(node: HTMLElement) {} + + function handleEndListener(node: HTMLElement, done: () => void) { + node.addEventListener("transitionend", done, false); + } + return ( -
    - - - - - +
    { "test" }
    -
    + - +
    { "test" }
    + + + +
    { "test" }
    +
    + +
    { "test" }
    -
    - - -
    { "test" }
    -
    -
    + +
    ); }; diff --git a/types/react-transition-group/tsconfig.json b/types/react-transition-group/tsconfig.json index 1fbbc5df49..305822cd04 100644 --- a/types/react-transition-group/tsconfig.json +++ b/types/react-transition-group/tsconfig.json @@ -1,9 +1,12 @@ { "compilerOptions": { + "target": "es5", "module": "commonjs", + "moduleResolution": "node", "lib": [ - "es6" + "es6", "dom" ], + "strict": true, "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -18,7 +21,8 @@ }, "files": [ "index.d.ts", - "CSSTransitionGroup.d.ts", + "CSSTransition.d.ts", + "Transition.d.ts", "TransitionGroup.d.ts", "react-transition-group-tests.tsx" ] diff --git a/types/react-transition-group/CSSTransitionGroup.d.ts b/types/react-transition-group/v1/CSSTransitionGroup.d.ts similarity index 100% rename from types/react-transition-group/CSSTransitionGroup.d.ts rename to types/react-transition-group/v1/CSSTransitionGroup.d.ts diff --git a/types/react-transition-group/v1/TransitionGroup.d.ts b/types/react-transition-group/v1/TransitionGroup.d.ts new file mode 100644 index 0000000000..44d9100889 --- /dev/null +++ b/types/react-transition-group/v1/TransitionGroup.d.ts @@ -0,0 +1,19 @@ +import { Component, HTMLAttributes, ReactElement, ReactType } from "react"; +import { HTMLTransitionGroupProps } from "./index"; + +declare namespace TransitionGroup { + interface TransitionGroupChildLifecycle { + componentWillAppear?(callback: () => void): void; + componentDidAppear?(): void; + componentWillEnter?(callback: () => void): void; + componentDidEnter?(): void; + componentWillLeave?(callback: () => void): void; + componentDidLeave?(): void; + } + + type TransitionGroupProps = HTMLTransitionGroupProps; +} + +declare class TransitionGroup extends Component {} + +export = TransitionGroup; diff --git a/types/react-transition-group/v1/index.d.ts b/types/react-transition-group/v1/index.d.ts new file mode 100644 index 0000000000..3c82827b46 --- /dev/null +++ b/types/react-transition-group/v1/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for react-transition-group 1.1 +// Project: https://github.com/reactjs/react-transition-group +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { HTMLAttributes, ReactElement, ReactType } from "react"; + +export interface HTMLTransitionGroupProps extends HTMLAttributes { + component?: ReactType; + childFactory?(child: ReactElement): ReactElement; +} + +import * as TransitionGroup from "./TransitionGroup"; +export { + TransitionGroupProps, + TransitionGroupChildLifecycle +} from "./TransitionGroup"; + +import * as CSSTransitionGroup from "./CSSTransitionGroup"; +export { + CSSTransitionGroupProps, + CSSTransitionGroupTransitionName +} from "./CSSTransitionGroup"; + +export { + TransitionGroup, + CSSTransitionGroup +}; diff --git a/types/react-transition-group/v1/react-transition-group-tests.tsx b/types/react-transition-group/v1/react-transition-group-tests.tsx new file mode 100644 index 0000000000..346fe9989a --- /dev/null +++ b/types/react-transition-group/v1/react-transition-group-tests.tsx @@ -0,0 +1,73 @@ +import * as React from "react"; +import * as TransitionGroup from "react-transition-group/TransitionGroup"; +import * as CSSTransitionGroup from "react-transition-group/CSSTransitionGroup"; +import { CSSTransitionGroupProps, TransitionGroupProps, TransitionGroupChildLifecycle } from "react-transition-group"; + +class TestChild extends React.Component implements TransitionGroupChildLifecycle { + componentWillAppear(callback: () => void) { + callback(); + } + + componentDidAppear() {} + + componentWillEnter(callback: () => void) { + callback(); + } + + componentDidEnter() {} + + componentWillLeave(callback: () => void) { + callback(); + } + + componentDidLeave() {} + + render() { + return (
  • { "Test" }
  • ); + } +} + +const Test: React.StatelessComponent = () => { + return ( +
    + + + + + +
    { "test" }
    +
    + + +
    { "test" }
    +
    + + +
    { "test" }
    +
    +
    + ); +}; diff --git a/types/react-transition-group/v1/tsconfig.json b/types/react-transition-group/v1/tsconfig.json new file mode 100644 index 0000000000..b7b4bfd758 --- /dev/null +++ b/types/react-transition-group/v1/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "jsx": "react", + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "react-transition-group": ["react-transition-group/v1"], + "react-transition-group/*": ["react-transition-group/v1/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "CSSTransitionGroup.d.ts", + "TransitionGroup.d.ts", + "react-transition-group-tests.tsx" + ] +} diff --git a/types/react-transition-group/v1/tslint.json b/types/react-transition-group/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-transition-group/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f8e165003397be393b8ce962329a21ff4e574af2 Mon Sep 17 00:00:00 2001 From: Nam Vu Date: Fri, 7 Jul 2017 10:57:57 +0700 Subject: [PATCH 0185/1618] Add static createWithoutData for Parse.Object --- types/parse/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index b4cd725529..8dfcb670a7 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -334,6 +334,7 @@ declare namespace Parse { static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; static registerSubclass(className: string, clazz: new (options?: any) => T): void; + static createWithoutData(id: string): T; initialize(): void; add(attr: string, item: any): this; From fc18988b7e3505e60649f2a290d7b6db0a15ba52 Mon Sep 17 00:00:00 2001 From: Kamil Ejsymont Date: Fri, 7 Jul 2017 08:25:04 +0200 Subject: [PATCH 0186/1618] Add some missing definitions --- types/jsforce/connection.d.ts | 28 ++++++++++++++++++++++++---- types/jsforce/index.d.ts | 1 + types/jsforce/query.d.ts | 3 +++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/types/jsforce/connection.d.ts b/types/jsforce/connection.d.ts index f3864eb5d8..c7f59916c2 100644 --- a/types/jsforce/connection.d.ts +++ b/types/jsforce/connection.d.ts @@ -5,17 +5,30 @@ import { RecordResult } from './record-result'; import { SObject } from './salesforce-object'; export interface ConnectionOptions { - instanceUrl?: string; accessToken?: string; - refreshToken?: string; + callOptions?: Object; + instanceUrl?: string; + loginUrl?: string; + logLevel?: string; + maxRequest?: number; oauth2?: { clientId: string, clientSecret: string, redirectUri?: string, }; - sessionId?: string; - serverUrl?: string; + proxyUrl?: string; redirectUri?: string; + refreshToken?: string; + serverUrl?: string; + sessionId?: string; + signedRequest?: string | Object, + version?: string; +} + +export interface UserInfo { + id: string; + organizationId: string; + url: string; } export type ConnectionEvent = "refresh"; @@ -23,6 +36,13 @@ export type ConnectionEvent = "refresh"; export class Connection { constructor(params: ConnectionOptions) + accessToken: string; sobject(resource: string): SObject; + login(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; + loginByOAuth2(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; + loginBySoap(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; + logout(callback?: (err: Error, res: void) => void): Promise; + logoutByOAuth2(callback?: (err: Error, res: void) => void): Promise; + logoutBySoap(callback?: (err: Error, res: void) => void): Promise; on(eventName: ConnectionEvent, callback: Function): void; } diff --git a/types/jsforce/index.d.ts b/types/jsforce/index.d.ts index bf8f98b574..9210b5eae4 100644 --- a/types/jsforce/index.d.ts +++ b/types/jsforce/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for jsforce 1.8 // Project: https://github.com/jsforce/jsforce // Definitions by: Dolan Miu +// Kamil Ejsymont // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as fs from 'fs'; diff --git a/types/jsforce/query.d.ts b/types/jsforce/query.d.ts index 0d716c28da..ac59969b08 100644 --- a/types/jsforce/query.d.ts +++ b/types/jsforce/query.d.ts @@ -8,7 +8,10 @@ export interface ExecuteOptions { } export class Query { + end(): Query; filter(filter: Object): Query; + map(map: Object): Query; + include(include: string): Query; hint(hint: Object): Query; limit(value: number): Query; maxFetch(value: number): Query; From e687ec04560482508d244d8c563c130267160c98 Mon Sep 17 00:00:00 2001 From: Kamil Ejsymont Date: Fri, 7 Jul 2017 08:31:51 +0200 Subject: [PATCH 0187/1618] Fix linter errors --- types/jsforce/connection.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/jsforce/connection.d.ts b/types/jsforce/connection.d.ts index c7f59916c2..612bf6fc84 100644 --- a/types/jsforce/connection.d.ts +++ b/types/jsforce/connection.d.ts @@ -21,7 +21,7 @@ export interface ConnectionOptions { refreshToken?: string; serverUrl?: string; sessionId?: string; - signedRequest?: string | Object, + signedRequest?: string | Object; version?: string; } @@ -41,8 +41,8 @@ export class Connection { login(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; loginByOAuth2(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; loginBySoap(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; - logout(callback?: (err: Error, res: void) => void): Promise; - logoutByOAuth2(callback?: (err: Error, res: void) => void): Promise; - logoutBySoap(callback?: (err: Error, res: void) => void): Promise; + logout(callback?: (err: Error, res: undefined) => void): Promise; + logoutByOAuth2(callback?: (err: Error, res: undefined) => void): Promise; + logoutBySoap(callback?: (err: Error, res: undefined) => void): Promise; on(eventName: ConnectionEvent, callback: Function): void; } From 34095176bf60538f886f392b67f5e9f14f55de3d Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 14:33:55 +0800 Subject: [PATCH 0188/1618] add imagecutter --- types/zui/imagecutter.d.ts | 33 +++++++++++++++++++++++++++++++++ types/zui/index.d.ts | 2 ++ types/zui/selectable.d.ts | 31 +++++++++++++++++++++++++++++++ types/zui/zui-tests.ts | 34 +++++++++++++++++++++++++++++++++- 4 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 types/zui/imagecutter.d.ts create mode 100644 types/zui/selectable.d.ts diff --git a/types/zui/imagecutter.d.ts b/types/zui/imagecutter.d.ts new file mode 100644 index 0000000000..c849a4e61d --- /dev/null +++ b/types/zui/imagecutter.d.ts @@ -0,0 +1,33 @@ +interface ImageCutterOption { + coverColor?: string, + coverOpacity?: number, + defaultWidth?: number, + defaultHeight?: number, + fixedRatio?: boolean, + minWidth?: number, + minHeight?: number, + post?: string, + get?: string +} +interface ImageData { + originWidth: number, + originHeight: number, + scaled: boolean, + scaleHeight: number, + scaleWidth: number, + width: number, + height: number, + left: number, + right: number, + top: number, + bottom: number +} +interface ImageCutter { + resetImage(img: string): any; + getData(): ImageData; +} + +interface JQuery { + imgCutter(option: ImageCutterOption): JQuery; + data(cmd: string): ImageCutter; +} \ No newline at end of file diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index e3699d1223..a9da140191 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -16,6 +16,8 @@ /// /// /// +/// +/// /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. diff --git a/types/zui/selectable.d.ts b/types/zui/selectable.d.ts new file mode 100644 index 0000000000..92ee5e23ba --- /dev/null +++ b/types/zui/selectable.d.ts @@ -0,0 +1,31 @@ +interface SelectableEvent { + selections: Map; + selected: Array; +} +interface SelectableOption { + selector?: string, + trigger?: string, + rangeStyle?: string|object, + clickBehavior?: string, + mouseButton?: string, + ignoreVal?: number, + + start?(e?: SelectableEvent): boolean; + finish?(e?: SelectableEvent): void; + select?(e?: SelectableEvent): void; + unselect?(e?: SelectableEvent): void; +} + +interface Selectable { + toggle(): any; + toggle(elementOrId: string | object | JQuery): any; + select(): any; + select(elementOrId: string | object | JQuery): any; + unselect(): any; + unselect(elementOrId: string | object | JQuery): any; +} + +interface JQuery { + selectable(option?: SelectableOption): JQuery; + +} \ No newline at end of file diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index 859b65b4e1..fefd533c47 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -244,4 +244,36 @@ var options = { }; // 初始化时传入选项参数 -$('#sortableList').sortable(options) \ No newline at end of file +$('#sortableList').sortable(options) + + +/** + * selectable + */ + +$('#selectable').selectable({ + selector: 'div', // #selectable 内的所有 div 都可以进行选中 + rangeStyle: { + border: '1px solid red' // 拖选范围指示矩形边框设置为红色 + }, + finish: function (data: SelectableEvent) { // 选择结束时的回调函数 + // 所有元素的选中或非选中状态 + console.log(data.selections); + + // 所有已选中的元素 ID 值的数组 + console.log(data.selected); + } +}); + +/** + * image cutter + */ + +// 获取 imgCutter 实例 +var myImgCutter = $('#imgCutter').data('zui.imgCutter'); + +// 调用 resetImg 方法 +myImgCutter.resetImage('http://zui.sexy/docs/img/img1.jpg'); + +// 调用 getData 方法 +var myImgCutterData = myImgCutter.getData(); \ No newline at end of file From d026e5340cc960baa7c4b2202cf50631673e094f Mon Sep 17 00:00:00 2001 From: izumin5210 Date: Fri, 7 Jul 2017 15:54:59 +0900 Subject: [PATCH 0189/1618] Add removeEventListener(), removeListener() and off() to ace --- types/ace/index.d.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 58bf1c2bd8..456727756c 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -1041,6 +1041,12 @@ declare namespace AceAjax { addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void; addEventListener(ev: string, callback: Function): void; + off(ev: string, callback: Function): void; + + removeListener(ev: string, callback: Function): void; + + removeEventListener(ev: string, callback: Function): void; + inMultiSelectMode: boolean; selectMoreLines(n: number): void; @@ -2166,8 +2172,16 @@ declare namespace AceAjax { **/ export interface Selection { + on(ev: string, callback: Function): void; + addEventListener(ev: string, callback: Function): void; + off(ev: string, callback: Function): void; + + removeListener(ev: string, callback: Function): void; + + removeEventListener(ev: string, callback: Function): void; + moveCursorWordLeft(): void; moveCursorWordRight(): void; From a2731f6cf0fc765cbbaf09bf5ea8dc2f65e1b35e Mon Sep 17 00:00:00 2001 From: "daniel.thunell" Date: Fri, 7 Jul 2017 09:01:53 +0200 Subject: [PATCH 0190/1618] NodeCache will return undefined on cache miss, see https://github.com/mpneuried/nodecache/blob/master/_src/lib/node_cache.coffee#L101 --- types/node-cache/index.d.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/types/node-cache/index.d.ts b/types/node-cache/index.d.ts index 37b4389d69..6cc565fd19 100644 --- a/types/node-cache/index.d.ts +++ b/types/node-cache/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for node-cache v3.0.0 // Project: https://github.com/tcs-de/nodecache // Definitions by: Ilya Mochalov +// Daniel Thunell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -25,7 +26,7 @@ declare namespace NodeCache { get( key: string, cb?: Callback - ): T; + ): T | undefined; /** * get multiple cached keys at once and change the stats @@ -35,8 +36,8 @@ declare namespace NodeCache { */ mget( keys: string[], - cb?: Callback<{[key: string]: T}> - ): {[key: string]: T}; + cb?: Callback<{ [key: string]: T }> + ): { [key: string]: T }; /** * set a cached key and change the stats @@ -50,7 +51,7 @@ declare namespace NodeCache { set( key: string, value: T, - ttl: number|string, + ttl: number | string, cb?: Callback ): boolean; @@ -67,7 +68,7 @@ declare namespace NodeCache { * @returns Number of deleted keys */ del( - keys: string|string[], + keys: string | string[], cb?: Callback ): number; @@ -183,8 +184,8 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac */ mget( keys: string[], - cb?: Callback<{[key: string]: T}> - ): {[key: string]: T}; + cb?: Callback<{ [key: string]: T }> + ): { [key: string]: T }; /** * set a cached key and change the stats @@ -198,7 +199,7 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac set( key: string, value: T, - ttl: number|string, + ttl: number | string, cb?: Callback ): boolean; @@ -215,7 +216,7 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac * @returns Number of deleted keys */ del( - keys: string|string[], + keys: string | string[], cb?: Callback ): number; From de50423e1684833a01039dfc32722313700afaa3 Mon Sep 17 00:00:00 2001 From: CSoellinger Date: Fri, 7 Jul 2017 09:05:19 +0200 Subject: [PATCH 0191/1618] Add systeminformation type definition --- types/systeminformation/index.d.ts | 507 ++++++++++++++++++ .../systeminformation-tests.ts | 50 ++ types/systeminformation/tsconfig.json | 22 + types/systeminformation/tslint.json | 3 + 4 files changed, 582 insertions(+) create mode 100644 types/systeminformation/index.d.ts create mode 100644 types/systeminformation/systeminformation-tests.ts create mode 100644 types/systeminformation/tsconfig.json create mode 100644 types/systeminformation/tslint.json diff --git a/types/systeminformation/index.d.ts b/types/systeminformation/index.d.ts new file mode 100644 index 0000000000..b8ec674839 --- /dev/null +++ b/types/systeminformation/index.d.ts @@ -0,0 +1,507 @@ +// Type definitions for systeminformation 3.23 +// Project: https://github.com/sebhildebrandt/systeminformation +// Definitions by: PixelCrab +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function version(): string; + +export function time(): Systeminformation.TimeData; + +export function system(cb?: (data: Systeminformation.SystemData) => any): Promise; + +export function cpu(cb?: (data: Systeminformation.CpuData) => any): Promise; + +export function cpuFlags(cb?: (data: string) => any): Promise; + +export function cpuCache(cb?: (data: Systeminformation.CpuCacheData) => any): Promise; + +export function cpuCurrentspeed(cb?: (data: Systeminformation.CpuCurrentSpeedData) => any): Promise; + +export function cpuTemperature(cb?: (data: Systeminformation.CpuTemperatureData) => any): Promise; + +export function mem(cb?: (data: Systeminformation.MemData) => any): Promise; + +export function memLayout(cb?: (data: Systeminformation.MemLayoutData) => any): Promise; + +export function diskLayout(cb?: (data: Systeminformation.DiskLayoutData) => any): Promise; + +export function battery(cb?: (data: Systeminformation.BatteryData) => any): Promise; + +export function graphics(cb?: (data: Systeminformation.GraphicsData) => any): Promise; + +export function osInfo(cb?: (data: Systeminformation.OsData) => any): Promise; + +export function versions(cb?: (data: Systeminformation.VersionData) => any): Promise; + +export function shell(cb?: (data: string) => any): Promise; + +export function users(cb?: (data: Systeminformation.UserData[]) => any): Promise; + +export function fsSize(cb?: (data: Systeminformation.FsSizeData[]) => any): Promise; + +export function blockDevices(cb?: (data: Systeminformation.BlockDevicesData[]) => any): Promise; + +export function fsStats(cb?: (data: Systeminformation.FsStatsData) => any): Promise; + +export function disksIO(cb?: (data: Systeminformation.DisksIoData) => any): Promise; + +export function networkInterfaces(cb ?: (data: Systeminformation.NetInterfacesData[]) => any): Promise; + +export function networkInterfaceDefault(cb ?: (data: string) => any): Promise; + +export function networkStats(iface?: string, cb?: (data: Systeminformation.NetStatsData) => any): Promise; + +export function networkConnections(cb?: (data: Systeminformation.NetConnectionsData[]) => any): Promise; + +export function inetChecksite(url: string, cb?: (data: Systeminformation.NetChecksiteData) => any): Promise; + +export function inetLatency(host?: string, cb?: (data: number) => any): Promise; + +export function currentLoad(cb?: (data: Systeminformation.CurrentLoadData) => any): Promise; + +export function fullLoad(cb?: (data: number) => any): Promise; + +export function processes(cb?: (data: Systeminformation.ProcessesData) => any): Promise; + +export function processLoad(processName: string, cb?: (data: Systeminformation.ProcessesProcessLoadData) => any): Promise; + +export function services(serviceName: string, cb?: (data: Systeminformation.ServicesData[]) => any): Promise; + +export function dockerContainers(all?: boolean, cb?: (data: Systeminformation.DockerContainerData[]) => any): Promise; + +export function dockerContainerStats(id?: string, cb?: (data: any) => any): Promise; + +export function dockerContainerProcesses(id?: string, cb?: (data: any) => any): Promise; + +export function dockerAll(cb?: (data: any) => any): Promise; + +export function getStaticData(cb?: (data: Systeminformation.StaticData) => any): Promise; + +export function getDynamicData(srv?: string, iface?: string, cb?: (data: any) => any): Promise; + +export function getAllData(srv?: string, iface?: string, cb?: (data: any) => any): Promise; + +export namespace Systeminformation { + interface StaticData { + version: string; + system: SystemData; + os: OsData; + versions: VersionData; + cpu: CpuData; + graphics: GraphicsData; + net: NetInterfacesData[]; + memLayout: MemLayoutData[]; + diskLayout: DiskLayoutData[]; + } + + interface TimeData { + current: string; + uptime: string; + timezone: string; + timezoneName: string; + } + + interface SystemData { + manufacturer: string; + model: string; + version: string; + serial: string; + uuid: string; + } + + interface CpuData { + manufacturer: string; + brand: string; + vendor: string; + family: string; + model: string; + stepping: string; + revision: string; + speed: string; + speedmin: string; + speedmax: string; + cores: number; + cache: CpuCacheData; + flags: string; + } + + interface CpuCacheData { + l1d: number; + l1i: number; + l2: number; + l3: number; + } + + interface CpuCurrentSpeedData { + avg: string; + min: string; + max: string; + } + + interface CpuTemperatureData { + main: string; + cores: string; + max: string; + } + + interface MemData { + total: number; + free: number; + used: number; + active: number; + available: number; + buffcache: number; + swaptotal: number; + swapused: number; + swapfree: number; + } + + interface MemLayoutData { + size: number; + bank: string; + type: string; + clockSpeed: number; + formFactor: string; + partNum: string; + serialNum: string; + voltageConfigured: number; + voltageMin: number; + voltageMax: number; + } + + interface DiskLayoutData { + type: string; + name: string; + vendor: string; + size: number; + bytesPerSector: number; + totalCylinders: number; + totalHeads: number; + totalSectors: number; + totalTracks: number; + tracksPerCylinder: number; + sectorsPerTrack: number; + firmwareRevision: string; + serialNum: string; + interfaceType: string; + } + + interface BatteryData { + hasbatter: boolean; + cyclecount: number; + ischarging: boolean; + maxcapacity: number; + currentcapacity: number; + percent: number; + } + + interface GraphicsData { + controllers: GraphicsControllerInfo[]; + displays: GraphicsDisplayInfo[]; + } + + interface GraphicsControllerInfo { + vendor: string; + model: string; + bus: string; + vram: number; + vramDynamic: boolean; + } + + interface GraphicsDisplayInfo { + connection: string; + main: boolean; + builtin: boolean; + model: string; + resolutionx: number; + resolutiony: number; + sizex: number; + sizey: number; + pixeldepth: number; + } + + interface OsData { + platform: string; + distro: string; + release: string; + codename: string; + kernel: string; + arch: string; + hostname: string; + logofile: string; + } + + interface VersionData { + kernel: string; + node: string; + v8: string; + npm: string; + pm2: string; + openssl: string; + } + + interface UserData { + user: string; + tty: string; + date: string; + time: string; + ip: string; + command: string; + } + + interface FsSizeData { + fs: string; + type: string; + size: number; + used: number; + use: number; + mount: string; + } + + interface BlockDevicesData { + name: string; + type: string; + fstype: string; + mount: string; + size: number; + physical: string; + uuid: string; + label: string; + model: string; + serial: string; + removable: boolean; + protocol: string; + } + + interface FsStatsData { + rx: number; + wx: number; + tx: number; + rx_sec: number; + wx_sec: number; + tx_sec: number; + ms: number; + } + + interface DisksIoData { + rIO: number; + wIO: number; + tIO: number; + rIO_sec: number; + wIO_sec: number; + tIO_sec: number; + ms: number; + } + + interface NetInterfacesData { + iface: string; + ip4: string; + ip6: string; + mac: string; + internal: boolean; + } + + interface NetStatsData { + iface: string; + rx: number; + tx: number; + rx_sec: number; + tx_sec: number; + ms: number; + } + + interface NetConnectionsData { + protocol: string; + localaddress: string; + localport: string; + peeraddress: string; + peerport: string; + state: string; + } + + interface NetChecksiteData { + url: string; + ok: boolean; + status: number; + ms: number; + } + + interface CurrentLoadData { + avgload: number; + currentload: number; + currentload_user: number; + currentload_nice: number; + currentload_system: number; + currentload_irq: number; + cpus: CurrentLoadCpuData[]; + } + + interface CurrentLoadCpuData { + load: number; + load_user: number; + load_nice: number; + load_system: number; + load_irq: number; + } + + interface ProcessesData { + all: number; + running: number; + blocked: number; + sleeping: number; + list: ProcessesProcessData[]; + } + + interface ProcessesProcessData { + pid: number; + pcpu: number; + pcpuu: number; + pcpus: number; + pmem: number; + priority: number; + mem_vsz: number; + mem_rss: number; + nice: number; + started: string; + state: string; + tty: string; + user: string; + command: string; + } + + interface ProcessesProcessLoadData { + proc: string; + pid: number; + cpu: number; + mem: number; + } + + interface ServicesData { + name: string; + running: boolean; + pcpu: number; + pmem: number; + } + + interface DockerContainerData { + id: string; + name: string; + image: string; + imageID: string; + command: string; + created: number; + state: string; + ports: number[]; + mounts: DockerContainerMountData[]; + } + + interface DockerContainerMountData { + Type: string; + Source: string; + Destination: string; + Mode: string; + RW: boolean; + Propagation: string; + } + + interface DockerContainerStatsData { + id: string; + mem_usage: number; + mem_limit: number; + mem_percent: number; + cpu_percent: number; + netIO: { + rx: number; + wx: number; + }; + blockIO: { + r: number; + w: number; + }; + cpu_stats: { + cpu_usage: { + total_usage: number; + usage_in_kernelmode: number; + usage_in_usermode: number; + }, + throttling_data: { + periods: number; + throttled_periods: number; + throttled_time: number; + } + }; + precpu_stats: { + cpu_usage: { + total_usage: number; + usage_in_kernelmode: number; + usage_in_usermode: number; + }, + throttling_data: { + periods: number; + throttled_periods: number; + throttled_time: number; + } + }; + memory_stats: { + usage: number; + max_usage: number; + stats: { + active_anon: number; + active_file: number; + cache: number; + dirty: number; + hierarchical_memory_limit: number; + inactive_anon: number; + inactive_file: number; + mapped_file: number; + pgfault: number; + pgmajfault: number; + pgpgin: number; + pgpgout: number; + rss: number; + rss_huge: number; + total_active_anon: number; + total_active_file: number; + total_cache: number; + total_dirty: number; + total_inactive_anon: number; + total_inactive_file: number; + total_mapped_file: number; + total_pgfault: number; + total_pgmajfault: number; + total_pgpgin: number; + total_pgpgout: number; + total_rss: number; + total_rss_huge: number; + total_unevictable: number; + total_writeback: number; + unevictable: number; + writeback: number; + }, + limit: number; + }; + networks: any; + } + + interface DockerContainerAllData extends DockerContainerData, DockerContainerStatsData { + pids: number; + processes: DockerContainerStatsProcessesData[]; + } + + interface DockerContainerStatsProcessesData { + pid_host: string; + ppid: string; + pgid: string; + user: string; + ruser: string; + group: string; + rgroup: string; + stat: string; + time: string; + elapsed: string; + nice: string; + rss: string; + vsz: string; + command: string; + } +} diff --git a/types/systeminformation/systeminformation-tests.ts b/types/systeminformation/systeminformation-tests.ts new file mode 100644 index 0000000000..fe431a1131 --- /dev/null +++ b/types/systeminformation/systeminformation-tests.ts @@ -0,0 +1,50 @@ +import * as systeminformation from "systeminformation"; + +systeminformation.version(); // $ExpectType string +systeminformation.time(); // $ExpectType TimeData +systeminformation.system(); // $ExpectType Promise +systeminformation.cpu(); // $ExpectType Promise +systeminformation.cpuFlags(); // $ExpectType Promise +systeminformation.cpuCache(); // $ExpectType Promise +systeminformation.cpuCurrentspeed(); // $ExpectType Promise +systeminformation.cpuTemperature(); // $ExpectType Promise +systeminformation.mem(); // $ExpectType Promise +systeminformation.memLayout(); // $ExpectType Promise +systeminformation.diskLayout(); // $ExpectType Promise +systeminformation.battery(); // $ExpectType Promise +systeminformation.graphics(); // $ExpectType Promise +systeminformation.osInfo(); // $ExpectType Promise + +systeminformation.versions() + .then((versions) => { + versions.kernel; // $ExpectType string + versions.node; // $ExpectType string + versions.npm; // $ExpectType string + versions.openssl; // $ExpectType string + versions.pm2; // $ExpectType string + versions.v8; // $ExpectType string + }); + +systeminformation.shell(); // $ExpectType Promise +systeminformation.users(); // $ExpectType Promise +systeminformation.fsSize(); // $ExpectType Promise +systeminformation.blockDevices(); // $ExpectType Promise +systeminformation.fsStats(); // $ExpectType Promise +systeminformation.disksIO(); // $ExpectType Promise +systeminformation.networkInterfaces(); // $ExpectType Promise +systeminformation.networkInterfaceDefault(); // $ExpectType Promise +systeminformation.networkStats(); // $ExpectType Promise +systeminformation.networkConnections(); // $ExpectType Promise +systeminformation.inetChecksite('http://www.google.at'); // $ExpectType Promise +systeminformation.currentLoad(); // $ExpectType Promise +systeminformation.fullLoad(); // $ExpectType Promise +systeminformation.processes(); // $ExpectType Promise +// systeminformation.processLoad(); // $ExpectType Promise +// systeminformation.services(); // $ExpectType Promise +systeminformation.dockerContainers(); // $ExpectType Promise +// systeminformation.dockerContainerStats(); // $ExpectType Promise +// systeminformation.dockerContainerProcesses(); // $ExpectType Promise +systeminformation.dockerAll(); // $ExpectType Promise +systeminformation.getStaticData(); // $ExpectType Promise +systeminformation.getDynamicData(); // $ExpectType Promise +systeminformation.getAllData(); // $ExpectType Promise diff --git a/types/systeminformation/tsconfig.json b/types/systeminformation/tsconfig.json new file mode 100644 index 0000000000..3e291804fb --- /dev/null +++ b/types/systeminformation/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "systeminformation-tests.ts" + ] +} diff --git a/types/systeminformation/tslint.json b/types/systeminformation/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/systeminformation/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From f1965f5eba6d370b5167263b8fb7d7df38d06cc8 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 15:45:50 +0800 Subject: [PATCH 0192/1618] add datatable --- types/zui/datatable.d.ts | 80 ++++++++++++++++++++++++++++++++++++++++ types/zui/index.d.ts | 2 + types/zui/treemenu.d.ts | 43 +++++++++++++++++++++ types/zui/zui-tests.ts | 51 ++++++++++++++++++++++++- 4 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 types/zui/datatable.d.ts create mode 100644 types/zui/treemenu.d.ts diff --git a/types/zui/datatable.d.ts b/types/zui/datatable.d.ts new file mode 100644 index 0000000000..15734e1e48 --- /dev/null +++ b/types/zui/datatable.d.ts @@ -0,0 +1,80 @@ +interface Col { + width?: number, + text?: string, + type?: string, + flex?: boolean, + colClass?: string, + sort?: string, + ignore?: boolean +} +interface Row { + id?: string, + checked?: boolean, + cssClass?: string, + css?: string, + data?: Array +} +interface DataTableData { + rows: Array, + cols: Array +} +interface AfterLoadEvent { + data: DataTableData; +} +interface SortEvent { + sorter: { + index: number, + sortUp: boolean, + } +} +interface SizeChangeEvent { + changes: { + change: string, + oldWidth: number, + newWidth: number, + colIndex: number, + } +} +interface ChecksChangeEvent { + checks: { + checkedAll: boolean, + checks: Array + } +} +interface DataTableOption { + checkable?: boolean, + checkByClickRow?: boolean, + checkedClass?: string, + storage?: boolean, + sortable?: boolean, + fixedHeader?: boolean, + fixedHeaderOffset?: number, + fixedLeftWidth?: string, + fixedRightWidth?: string, + flexHeadDrag?: boolean, + scrollPos?: string, + rowHover?: boolean, + colHover?: boolean, + fixCellHeight?: boolean, + minColWidth?: number, + minFixedLeftWidth?: number, + minFixedRightWidth?: number, + minFlexAreaWidth?: number + selectable?: boolean | object, + + afterLoad?(event: AfterLoadEvent): void; + ready?(): void; + sort?(event: SortEvent): void; + sizeChanged?(event: SizeChangeEvent): void; + checksChanged?(event: ChecksChangeEvent): void; +} + +interface DataTable { + checks: { checkedAll: boolean, checks: Array } +} + +interface JQuery { + datatable(option?: DataTableOption): JQuery; + datatable(command: string, option?: DataTableOption): JQuery; + datatable(command: string, data: DataTableData): JQuery; +} \ No newline at end of file diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index a9da140191..2bd66ea5e1 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -18,6 +18,8 @@ /// /// /// +/// +/// /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. diff --git a/types/zui/treemenu.d.ts b/types/zui/treemenu.d.ts new file mode 100644 index 0000000000..3512efe8ae --- /dev/null +++ b/types/zui/treemenu.d.ts @@ -0,0 +1,43 @@ +interface TreeNode { + title?: string, + url?: string, + html?: string, + children?: Array; + open?: boolean, + id?: string +} +interface TreeMenuOption { + animate?: boolean, + initialState?: string, + data?: Array + itemCreator?(li: JQuery | object, item: TreeNode): any, + itemWrapper?: boolean +} + +interface TreeMenu { + expand(): void; + expand(params: JQuery): void; + expand(params: JQuery, disableAnimate: boolean): void; + + collapse(): void; + collapse(params: JQuery): void; + collapse(params: JQuery, disableAnimate: boolean): void; + + toggle(): void; + toggle(params: JQuery): void; + toggle(params: JQuery, disableAnimate: boolean): void; + + show(): void; + show(params: JQuery): void; + show(params: JQuery, disableAnimate: boolean): void; + + add(element: JQuery, items: Array, expand?: boolean, disabledAnimate?: boolean): void; + toData($ul?: JQuery, filter?: string): object; + + reload(data: Array):void; + remove(): void; + empty(): void; +} +interface JQuery { + tree(option?: TreeMenuOption): JQuery +} \ No newline at end of file diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index fefd533c47..12ce598c51 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -276,4 +276,53 @@ var myImgCutter = $('#imgCutter').data('zui.imgCutter'); myImgCutter.resetImage('http://zui.sexy/docs/img/img1.jpg'); // 调用 getData 方法 -var myImgCutterData = myImgCutter.getData(); \ No newline at end of file +var myImgCutterData = myImgCutter.getData(); + +/** + * treemenu + */ +var myTreeData = [{ + title: '水果', + url: 'http://zui.sexy', + open: true, + children: [ + { title: '橘子' }, + { + title: '瓜', + children: [ + { title: '西瓜' }, + { title: '黄瓜' } + ] + } + ] +}, { + title: '坚果', + children: [ + { title: '向日葵' }, + { title: '瓜子' } + ] +}, { + title: '蔬菜' +}]; + +$('#myTree').tree({ data: myTreeData }); + + +/** + * datatable + */ +$('table.datatable').datatable({ sortable: true }); +// 使用data参数更新数据: +$('table.datatable').datatable('load', { + cols: [ + { width: 80, text: '#', type: 'number', flex: false, colClass: 'text-center' }, + { width: 160, text: '时间', type: 'date', flex: false, sort: 'down' }, + { width: 80, text: '名称', type: 'string', flex: true, colClass: '' } + ], + rows: [ + { checked: false, data: [1, '2016-01-18 11:09:36', '新的名称示例1'] }, + { checked: false, data: [2, '2016-01-22 12:06:16', '新的名称示例2'] }, + // 更多数据 + ] +}); + From a2e5ed8b4c5d259e6453036152d59304c07a642c Mon Sep 17 00:00:00 2001 From: Georgy Krivonosov Date: Fri, 7 Jul 2017 10:50:01 +0300 Subject: [PATCH 0193/1618] fix typescript version --- types/reapop/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/reapop/index.d.ts b/types/reapop/index.d.ts index 54d4a46537..626d9bb58c 100644 --- a/types/reapop/index.d.ts +++ b/types/reapop/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/LouisBarranqueiro/reapop#readme // Definitions by: Barrokgl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1.1 +// TypeScript Version: 2.3 import * as React from 'react'; From a8babf29ffbaeccc15ce1c9032c5c15aa5fed160 Mon Sep 17 00:00:00 2001 From: "daniel.thunell" Date: Fri, 7 Jul 2017 10:00:58 +0200 Subject: [PATCH 0194/1618] Add tslint file, fix lint errors, key can be string | number --- types/node-cache/index.d.ts | 43 +++++++++++++++------------- types/node-cache/node-cache-tests.ts | 14 ++++----- types/node-cache/tslint.json | 3 ++ 3 files changed, 33 insertions(+), 27 deletions(-) create mode 100644 types/node-cache/tslint.json diff --git a/types/node-cache/index.d.ts b/types/node-cache/index.d.ts index 6cc565fd19..558882a086 100644 --- a/types/node-cache/index.d.ts +++ b/types/node-cache/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-cache v3.0.0 +// Type definitions for node-cache 4.1 // Project: https://github.com/tcs-de/nodecache // Definitions by: Ilya Mochalov // Daniel Thunell @@ -6,6 +6,12 @@ /// +/** + * Since 4.1.0: Key-validation: The keys can be given as either string or number, + * but are casted to a string internally anyway. + */ +type Key = string | number; + declare namespace NodeCache { interface NodeCache { /** container for cached data */ @@ -24,7 +30,7 @@ declare namespace NodeCache { * @param cb Callback function */ get( - key: string, + key: Key, cb?: Callback ): T | undefined; @@ -35,7 +41,7 @@ declare namespace NodeCache { * @param cb Callback function */ mget( - keys: string[], + keys: Key[], cb?: Callback<{ [key: string]: T }> ): { [key: string]: T }; @@ -49,14 +55,14 @@ declare namespace NodeCache { * @param cb Callback function */ set( - key: string, + key: Key, value: T, ttl: number | string, cb?: Callback ): boolean; set( - key: string, + key: Key, value: T, cb?: Callback ): boolean; @@ -68,7 +74,7 @@ declare namespace NodeCache { * @returns Number of deleted keys */ del( - keys: string | string[], + keys: Key | Key[], cb?: Callback ): number; @@ -76,13 +82,13 @@ declare namespace NodeCache { * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` */ ttl( - key: string, + key: Key, ttl: number, cb?: Callback ): boolean; ttl( - key: string, + key: Key, cb?: Callback, ttl?: number ): boolean; @@ -141,9 +147,7 @@ declare namespace NodeCache { v: T; } - interface Callback { - (err: any, data: T): void; - } + type Callback = (err: any, data: T | undefined) => void; } import events = require("events"); @@ -172,9 +176,9 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac * @param cb Callback function */ get( - key: string, + key: Key, cb?: Callback - ): T; + ): T | undefined; /** * get multiple cached keys at once and change the stats @@ -183,7 +187,7 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac * @param cb Callback function */ mget( - keys: string[], + keys: Key[], cb?: Callback<{ [key: string]: T }> ): { [key: string]: T }; @@ -197,14 +201,14 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac * @param cb Callback function */ set( - key: string, + key: Key, value: T, ttl: number | string, cb?: Callback ): boolean; set( - key: string, + key: Key, value: T, cb?: Callback ): boolean; @@ -216,7 +220,7 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac * @returns Number of deleted keys */ del( - keys: string | string[], + keys: Key | Key[], cb?: Callback ): number; @@ -224,13 +228,13 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac * reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` */ ttl( - key: string, + key: Key, ttl: number, cb?: Callback ): boolean; ttl( - key: string, + key: Key, cb?: Callback, ttl?: number ): boolean; @@ -261,4 +265,3 @@ declare class NodeCache extends events.EventEmitter implements NodeCache.NodeCac } export = NodeCache; - diff --git a/types/node-cache/node-cache-tests.ts b/types/node-cache/node-cache-tests.ts index 7f5f917c07..96c4cdd5e4 100644 --- a/types/node-cache/node-cache-tests.ts +++ b/types/node-cache/node-cache-tests.ts @@ -1,5 +1,3 @@ - - import NodeCache = require('node-cache'); import Options = NodeCache.Options; @@ -23,7 +21,7 @@ interface TypeSample { let cache: NodeCache; let key: string; let cb: Callback; - let result: TypeSample; + let result: TypeSample | undefined; result = cache.get(key); result = cache.get(key, cb); } @@ -31,8 +29,8 @@ interface TypeSample { { let cache: NodeCache; let keys: string[]; - let cb: Callback<{[key: string]: TypeSample}>; - let result: {[key: string]: TypeSample}; + let cb: Callback<{ [key: string]: TypeSample }>; + let result: { [key: string]: TypeSample }; result = cache.mget(keys); result = cache.mget(keys, cb); } @@ -41,7 +39,7 @@ interface TypeSample { let cache: NodeCache; let key: string; let value: TypeSample; - let ttl: number|string; + let ttl: number | string; let cb: Callback; let result: boolean; result = cache.set(key, value); @@ -52,7 +50,7 @@ interface TypeSample { { let cache: NodeCache; - let keys: string|string[]; + let keys: string | string[]; let cb: Callback; let result: number; result = cache.del(keys); @@ -85,6 +83,7 @@ interface TypeSample { result = cache.getStats(); } +/* tslint:disable void-return */ { let cache: NodeCache; let result: void; @@ -96,3 +95,4 @@ interface TypeSample { let result: void; result = cache.close(); } +/* tslint:enable void-return */ diff --git a/types/node-cache/tslint.json b/types/node-cache/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/node-cache/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From 16e0dff475d20254f18028319df2b2faf12b2450 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Fri, 7 Jul 2017 09:04:03 +0100 Subject: [PATCH 0195/1618] Added restify v4 types folder --- types/restify/v4/index.d.ts | 612 ++++++++++++++++++++++++++++++ types/restify/v4/restify-tests.ts | 347 +++++++++++++++++ types/restify/v4/tsconfig.json | 22 ++ types/restify/v4/tslint.json | 1 + 4 files changed, 982 insertions(+) create mode 100644 types/restify/v4/index.d.ts create mode 100644 types/restify/v4/restify-tests.ts create mode 100644 types/restify/v4/tsconfig.json create mode 100644 types/restify/v4/tslint.json diff --git a/types/restify/v4/index.d.ts b/types/restify/v4/index.d.ts new file mode 100644 index 0000000000..37c2b11487 --- /dev/null +++ b/types/restify/v4/index.d.ts @@ -0,0 +1,612 @@ +// Type definitions for restify 4.3 +// Project: https://github.com/restify/node-restify +// Definitions by: Bret Little , Steve Hipwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import http = require('http'); +import Logger = require('bunyan'); +import url = require('url'); + +export interface addressInterface { + port: number; + family: string; + address: string; +} + +export interface requestFileInterface { + path: string; + type: string; +} + +/** + * Comes from authorizationParser plugin + */ +export interface requestAuthorization { + scheme: string; + credentials: string; + basic?: { + username: string; + password: string; + }; +} + +export interface Request extends http.IncomingMessage { + /** + * builds an absolute URI for the request. + * @private + * @function absoluteUri + * @param {String} path a url path + * @returns {String} + */ + absoluteUri(path: string): string; + + /** + * returns any header off the request. also, 'correct' any + * correctly spelled 'referrer' header to the actual spelling used. + * @public + * @function header + * @param {String} name the name of the header + * @param {String} value default value if header isn't found on the req + * @returns {String} + */ + header(name: string, value?: string): string; + + /** + * returns any trailer header off the request. also, 'correct' any + * correctly spelled 'referrer' header to the actual spelling used. + * @public + * @function trailer + * @param {String} name the name of the header + * @param {String} value default value if header isn't found on the req + * @returns {String} + */ + trailer(name: string, value?: string): string; + + /** + * checks if the accept header is present and has the value requested. + * e.g., req.accepts('html'); + * @public + * @function accepts + * @param {String | Array} types an array of accept type headers + * @returns {Boolean} + */ + accepts(types: string | string[]): boolean; + + /** + * checks if the request accepts the encoding types. + * @public + * @function acceptsEncoding + * @param {String | Array} types an array of accept type headers + * @returns {Boolean} + */ + acceptsEncoding(types: string | string[]): boolean; + + /** + * Check if the incoming request contains the Content-Type header field, and + * if it contains the given mime type. + * @public + * @function is + * @param {String} type a content-type header value + * @returns {Boolean} + */ + is(type: string): boolean; + + /** + * Check if the incoming request is chunked. + * @public + * @function isChunked + * @returns {Boolean} + */ + isChunked(): boolean; + + /** + * Check if the incoming request is kept alive. + * @public + * @function isKeepAlive + * @returns {Boolean} + */ + isKeepAlive(): boolean; + + /** + * Check if the incoming request has been upgraded. + * @public + * @function isUpgradeRequest + * @returns {Boolean} + */ + isUpgradeRequest(): boolean; + + /** + * Check if the incoming request is an upload verb. + * @public + * @function isUpload + * @returns {Boolean} + */ + isUpload(): boolean; + + /** + * retrieves the user-agent header. + * @public + * @function userAgent + * @returns {String} + */ + userAgent(): string; + + /** + * Start the timer for a request handler function. You must explicitly invoke + * endHandlerTimer() after invoking this function. Otherwise timing information + * will be inaccurate. + * @public + * @function startHandlerTimer + * @param {String} handlerName The name of the handler. + * @returns {undefined} + */ + startHandlerTimer(handlerName: string): void; + + /** + * Stop the timer for a request handler function. + * @public + * @function endHandlerTimer + * @param {String} handlerName The name of the handler. + * @returns {undefined} + */ + endHandlerTimer(handlerName: string): void; + + getLogger(component: string): any; + + /** + * gets the content-length header off the request. + * @public + * @function getContentLength + * @returns {Number} + */ + getContentLength(): number; + + /** + * @see getContentLength + * @function contentLength + */ + contentLength(): number; + + /** + * gets the content-type header. + * @public + * @function getContentType + * @returns {String} + */ + getContentType(): string; + + /** + * @see getContentType + */ + contentType(): string; + + /** + * retrieves the complete URI requested by the client. + * @public + * @function getHref + * @returns {String} + */ + getHref(): string; + + /** + * @see getHref + */ + href(): string; + + log: Logger; + /** + * retrieves the request uuid. was created when the request was setup. + * @public + * @function getId + * @returns {String} + */ + getId(): string; + + /** + * @see getId + */ + id(): string; + + /** + * retrieves the cleaned up url path. + * e.g., /foo?a=1 => /foo + * @public + * @function getPath + * @returns {String} + */ + getPath(): string; + + /** + * @see getPath + */ + path(): string; + + /** + * returns the raw query string + * @public + * @function getQuery + * @returns {String} + */ + getQuery(): string; + + /** + * @see getQuery + */ + query: any; + + secure: boolean; + + /** + * returns ms since epoch when request was setup. + * @public + * @function time + * @returns {Number} + */ + time(): number; + + /** + * returns a parsed URL object. + * @public + * @function getUrl + * @returns {Object} + */ + getUrl(): url.Url; + + /** + * returns the accept-version header. + * @public + * @function getVersion + * @returns {String} + */ + getVersion(): string; + + /** + * @see getVersion + */ + version(): string; + params: any; + files?: { [name: string]: requestFileInterface }; + + /** + * Check if the incoming request is encrypted. + * @public + * @function isSecure + * @returns {Boolean} + */ + isSecure(): boolean; + /** available when bodyParser plugin is used */ + body?: any; + /** available when authorizationParser plugin is used */ + username?: string; + /** available when authorizationParser plugin is used */ + authorization?: requestAuthorization; + + timers: HandlerTiming[]; +} + +/** + * Timer object used to identify how long a specific handler took to run + * + * @property {String} name The name of the handler. + * @property {Array} time A tuple of [seconds, nanoseconds], how long the handler took. + */ +export interface HandlerTiming { + name: string; + time: [number, number]; +} + +export interface Response extends http.ServerResponse { + header(key: string, value?: any): any; + cache(type?: any, options?: any): any; + noCache(): any; + status(code: number): any; + send(status?: any, body?: any, headers?: { [header: string]: string }): any; + json(status?: any, body?: any, headers?: { [header: string]: string }): any; + code: number; + contentLength: number; + charSet(value: string): void; + contentType: string; + headers: any; + id: string; +} + +export interface RouteSpec { + method: string; + name: string; + path: string | RegExp; + versions: string[]; +} + +export interface Route { + name: string; + method: string; + path: RoutePathRegex; + spec: RouteSpec; + types: string[]; + versions: string[]; +} + +export interface RouteOptions { + name: string; + method: string; + path?: string | RegExp; + url?: string | RegExp; + urlParamPattern?: RegExp; + contentType?: string | string[]; + versions?: string | string[]; +} + +export interface RoutePathRegex extends RegExp { + restifyParams: string[]; +} + +export interface Router { + name: string; + mounts: { [routeName: string]: Route }; + versions: string[]; + contentType: string[]; + routes: { + DELETE: Route[]; + GET: Route[]; + HEAD: Route[]; + OPTIONS: Route[]; + PATCH: Route[]; + POST: Route[]; + PUT: Route[]; + }; + log?: any; + toString(): string; + + /** + * Takes an object of route params and query params, and 'renders' a URL + * @param {String} routeName the route name + * @param {Object} params an object of route params + * @param {Object} query an object of query params + * @returns {String} + */ + render(routeName: string, params: any, query?: any): string; + + /** + * adds a route. + * @param {Object} options an options object + * @returns {String} returns the route name if creation is successful. + */ + mount(options: any): string | boolean; + + /** + * unmounts a route. + * @param {String} name the route name + * @returns {String} the name of the deleted route (or false if it was not matched) + */ + unmount(name: string): string | boolean; + + /** + * finds the route for a given request and response. + * @param {Request} req the request object + * @param {Response} res the response object + * @param {Function} callback operation callback + * @returns {undefined} + */ + find(req: Request, res: Response, callback: (err: Error, route: Route) => void): void; +} + +export interface Server extends http.Server { + use(handler: RequestHandler | RequestHandler[], ...handlers: RequestHandler[]): Server; + // tslint:disable-next-line unified-signatures + use(handler: RequestHandler | RequestHandler[], ...handlers: RequestHandler[][]): Server; + + post(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; + // tslint:disable-next-line unified-signatures + post(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; + + patch(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; + // tslint:disable-next-line unified-signatures + patch(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; + + put(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; + // tslint:disable-next-line unified-signatures + put(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; + + del(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; + // tslint:disable-next-line unified-signatures + del(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; + + get(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; + // tslint:disable-next-line unified-signatures + get(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; + + head(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; + // tslint:disable-next-line unified-signatures + head(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; + + opts(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[]): string; + // tslint:disable-next-line unified-signatures + opts(route: any, routeCallBack: RequestHandler | RequestHandler[], ...routeCallBacks: RequestHandler[][]): string; + + name: string; + version: string; + log: any; + acceptable: string[]; + url: string; + address(): addressInterface; + listen(...args: any[]): any; + close(...args: any[]): any; + pre(routeCallBack: RequestHandler): Server; + server: http.Server; + router: Router; + routes: Route[]; + toString(): string; +} + +export interface ServerOptions { + ca?: string; + certificate?: string | string[] | Buffer | Buffer[]; + key?: string | string[] | Buffer | Buffer[]; + formatters?: any; + log?: any; + name?: string; + spdy?: any; + version?: string; + responseTimeHeader?: string; + responseTimeFormatter?(durationInMilliseconds: number): any; + handleUpgrades?: boolean; + router?: Router; + httpsServerOptions?: any; + socketio?: boolean; +} + +export interface ClientOptions { + accept?: string; + connectTimeout?: number; + requestTimeout?: number; + dtrace?: any; + gzip?: any; + headers?: any; + log?: any; + retry?: any; + signRequest?(): void; + url?: string; + userAgent?: string; + version?: string; +} + +export interface Client { + get(opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; + head(opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any): any; + post(opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; + put(opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; + patch(opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any): any; + del(opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any): any; + basicAuth(username: string, password: string): any; +} + +export interface HttpClient { + get(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; + head(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; + post(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; + put(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; + patch(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; + del(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; + basicAuth(username: string, password: string): any; +} + +export interface ThrottleOptions { + burst?: number; + rate?: number; + ip?: boolean; + xff?: boolean; + username?: boolean; + tokensTable?: any; + maxKeys?: number; + overrides?: any; +} + +export interface Next { + (err?: any): any; + ifError(err?: any): any; +} + +export type RequestHandler = (req: Request, res: Response, next: Next) => any; + +export function createServer(options?: ServerOptions): Server; + +export function createJsonClient(options?: ClientOptions): Client; +export function createStringClient(options?: ClientOptions): Client; +export function createClient(options?: ClientOptions): HttpClient; + +export class HttpError { constructor(cause: any, message?: any); } + +export class DefiniteHttpError { + constructor(message?: any); + + // tslint:disable-next-line unified-signatures + constructor(cause: any, message?: any); +} + +export class BadRequestError extends DefiniteHttpError { } +export class UnauthorizedError extends DefiniteHttpError { } +export class PaymentRequiredError extends DefiniteHttpError { } +export class ForbiddenError extends DefiniteHttpError { } +export class NotFoundError extends DefiniteHttpError { } +export class MethodNotAllowedError extends DefiniteHttpError { } +export class NotAcceptableError extends DefiniteHttpError { } +export class ProxyAuthenticationRequiredError extends DefiniteHttpError { } +export class RequestTimeoutError extends DefiniteHttpError { } +export class ConflictError extends DefiniteHttpError { } +export class GoneError extends DefiniteHttpError { } +export class LengthRequiredError extends DefiniteHttpError { } +export class RequestEntityTooLargeError extends DefiniteHttpError { } +export class RequesturiTooLargeError extends DefiniteHttpError { } +export class UnsupportedMediaTypeError extends DefiniteHttpError { } +export class RequestedRangeNotSatisfiableError extends DefiniteHttpError { } +export class ExpectationFailedError extends DefiniteHttpError { } +export class ImATeapotError extends DefiniteHttpError { } +export class UnprocessableEntityError extends DefiniteHttpError { } +export class LockedError extends DefiniteHttpError { } +export class FailedDependencyError extends DefiniteHttpError { } +export class UnorderedCollectionError extends DefiniteHttpError { } +export class UpgradeRequiredError extends DefiniteHttpError { } +export class PreconditionRequiredError extends DefiniteHttpError { } +export class TooManyRequestsError extends DefiniteHttpError { } +export class RequestHeaderFieldsTooLargeError extends DefiniteHttpError { } +export class InternalServerError extends DefiniteHttpError { } +export class NotImplementedError extends DefiniteHttpError { } +export class BadGatewayError extends DefiniteHttpError { } +export class ServiceUnavailableError extends DefiniteHttpError { } +export class GatewayTimeoutError extends DefiniteHttpError { } +export class HttpVersionNotSupportedError extends DefiniteHttpError { } +export class VariantAlsoNegotiatesError extends DefiniteHttpError { } +export class InsufficientStorageError extends DefiniteHttpError { } +export class BandwidthLimitExceededError extends DefiniteHttpError { } +export class NotExtendedError extends DefiniteHttpError { } +export class NetworkAuthenticationRequiredError extends DefiniteHttpError { } +export class RestError extends DefiniteHttpError { } + +export class PreconditionFailedError extends RestError { } +export class BadDigestError extends RestError { } +export class BadMethodError extends RestError { } +export class InternalError extends RestError { } +export class InvalidArgumentError extends RestError { } +export class InvalidContentError extends RestError { } +export class InvalidCredentialsError extends RestError { } +export class InvalidHeaderError extends RestError { } +export class InvalidVersionError extends RestError { } +export class MissingParameterError extends RestError { } +export class NotAuthorizedError extends RestError { } +export class RequestExpiredError extends RestError { } +export class RequestThrottledError extends RestError { } +export class ResourceNotFoundError extends RestError { } +export class WrongAcceptError extends RestError { } + +export function acceptParser(parser: any): RequestHandler; +export function authorizationParser(): RequestHandler; +export function dateParser(skew?: number): RequestHandler; +export function queryParser(options?: any): RequestHandler; +export function urlEncodedBodyParser(options?: any): RequestHandler[]; +export function jsonp(): RequestHandler; +export function gzipResponse(options?: any): RequestHandler; +export function bodyParser(options?: any): RequestHandler[]; +export function requestLogger(options?: any): RequestHandler; +export function serveStatic(options?: any): RequestHandler; +export function throttle(options?: ThrottleOptions): RequestHandler; +export function conditionalRequest(): RequestHandler[]; +export function auditLogger(options: { log: any }): (req: Request, res: Response, route: Route, err: any) => void; +export function fullResponse(): RequestHandler; +// tslint:disable-next-line no-var +export var defaultResponseHeaders: any; + +export function CORS(options?: CORSOptions): RequestHandler; +export interface CORSOptions { + origins?: string[]; + credentials?: boolean; + headers?: string[]; +} + +export const pre: { + pause(): RequestHandler; + sanitizePath(options?: any): RequestHandler; + userAgentConnection(options?: any): RequestHandler; +}; diff --git a/types/restify/v4/restify-tests.ts b/types/restify/v4/restify-tests.ts new file mode 100644 index 0000000000..15eb8eb868 --- /dev/null +++ b/types/restify/v4/restify-tests.ts @@ -0,0 +1,347 @@ +import * as restify from "restify"; +import * as url from "url"; + +let server = restify.createServer({ + formatters: { + 'application/foo': function formatFoo(req: restify.Request, res: restify.Response, body: any) { + if (body instanceof Error) + return body.stack; + + if (body) + return body.toString('base64'); + + return body; + } + } +}); + +server = restify.createServer({ + ca: "test", + certificate: "test", + key: "test", + formatters: {}, + log: {}, + name: "test", + spdy: {}, + version: "", + responseTimeHeader: "", + responseTimeFormatter: (durationInMilliseconds: number) => { }, + socketio: false +}); + +server.pre(restify.pre.sanitizePath()); + +server.on('someEvent', () => { }); + +server.use((req: restify.Request, res: restify.Response, next: restify.Next) => { }); +server.use([(req: restify.Request, res: restify.Response, next: restify.Next) => { }]); +server.use((req: restify.Request, res: restify.Response, next: restify.Next) => { }, (req: restify.Request, res: restify.Response, next: restify.Next) => { }); + +function send(req: restify.Request, res: restify.Response, next: restify.Next) { + req.header('key', 'val'); + req.header('key') === 'val'; + req.trailer('key', 'val'); + req.trailer('key') === 'val'; + + req.accepts('test') === true; + req.accepts(['test']) === true; + req.acceptsEncoding('test') === true; + req.acceptsEncoding(['test']) === true; + req.is('test') === true; + req.isChunked() === true; + req.isKeepAlive() === true; + req.isSecure() === true; + req.isUpgradeRequest() === true; + req.isUpload() === true; + req.userAgent() === 'test'; + req.startHandlerTimer('test'); + req.endHandlerTimer('test'); + req.absoluteUri('test') === 'test'; + + req.timers.pop() === { name: 'test', time: [0, 1234] }; + req.getLogger('test'); + + const log = req.log; + log.debug({ params: req.params }, 'Hello there %s', 'foo'); + + req.getContentLength() === 50; + req.contentLength() === 50; + req.getContentType() === 'test'; + req.contentType() === 'test'; + req.getHref() === 'test'; + req.href() === 'test'; + req.getId() === 'test'; + req.id() === 'test'; + req.getPath() === 'test'; + req.path() === 'test'; + req.getQuery() === 'test'; + req.query === 'test'; + req.secure === true; + req.time() === 1463518410080; + req.getUrl() === url.parse('http://test.test.test/test'); + req.getVersion() === 'test'; + req.version() === 'test'; + req.params; + + res.header('test'); + res.header('test', {}); + res.header('test', new Date()); + + res.cache(); + res.cache('testst', {}); + + res.status(344); + + res.send({ hello: 'world' }); + res.send(201, { hello: 'world' }); + res.send(new restify.BadRequestError('meh')); + + res.json(201, { hello: 'world' }); + res.json({ hello: 'world' }); + + res.code === 50; + res.contentLength === 50; + res.charSet('test'); + res.contentType === 'test'; + res.headers; + res.id === 'test'; + + res.send('hello ' + req.params.name); + return next(); +} + +server.post('/hello', send); +server.put('/hello', send); +server.del('/hello', send); +server.get('/hello', send); +server.head('/hello', send); +server.opts('/hello', send); + +server.post(/(.*)/, send); +server.put(/(.*)/, send); +server.del(/(.*)/, send); +server.get(/(.*)/, send); +server.head(/(.*)/, send); +server.opts(/(.*)/, send); + +new restify.BadRequestError(); +new restify.UnauthorizedError(); +new restify.PaymentRequiredError(); +new restify.ForbiddenError(); +new restify.NotFoundError(); +new restify.MethodNotAllowedError(); +new restify.NotAcceptableError(); +new restify.ProxyAuthenticationRequiredError(); +new restify.RequestTimeoutError(); +new restify.ConflictError(); +new restify.GoneError(); +new restify.LengthRequiredError(); +new restify.RequestEntityTooLargeError(); +new restify.RequesturiTooLargeError(); +new restify.UnsupportedMediaTypeError(); +new restify.RequestedRangeNotSatisfiableError(); +new restify.ExpectationFailedError(); +new restify.ImATeapotError(); +new restify.UnprocessableEntityError(); +new restify.LockedError(); +new restify.FailedDependencyError(); +new restify.UnorderedCollectionError(); +new restify.UpgradeRequiredError(); +new restify.PreconditionRequiredError(); +new restify.TooManyRequestsError(); +new restify.RequestHeaderFieldsTooLargeError(); +new restify.InternalServerError(); +new restify.NotImplementedError(); +new restify.BadGatewayError(); +new restify.ServiceUnavailableError(); +new restify.GatewayTimeoutError(); +new restify.HttpVersionNotSupportedError(); +new restify.VariantAlsoNegotiatesError(); +new restify.InsufficientStorageError(); +new restify.BandwidthLimitExceededError(); +new restify.NotExtendedError(); +new restify.NetworkAuthenticationRequiredError(); +new restify.RestError(); + +new restify.BadRequestError(new Error(), 'foo'); +new restify.UnauthorizedError(new Error(), 'foo'); +new restify.PaymentRequiredError(new Error(), 'foo'); +new restify.ForbiddenError(new Error(), 'foo'); +new restify.NotFoundError(new Error(), 'foo'); +new restify.MethodNotAllowedError(new Error(), 'foo'); +new restify.NotAcceptableError(new Error(), 'foo'); +new restify.ProxyAuthenticationRequiredError(new Error(), 'foo'); +new restify.RequestTimeoutError(new Error(), 'foo'); +new restify.ConflictError(new Error(), 'foo'); +new restify.GoneError(new Error(), 'foo'); +new restify.LengthRequiredError(new Error(), 'foo'); +new restify.RequestEntityTooLargeError(new Error(), 'foo'); +new restify.RequesturiTooLargeError(new Error(), 'foo'); +new restify.UnsupportedMediaTypeError(new Error(), 'foo'); +new restify.RequestedRangeNotSatisfiableError(new Error(), 'foo'); +new restify.ExpectationFailedError(new Error(), 'foo'); +new restify.ImATeapotError(new Error(), 'foo'); +new restify.UnprocessableEntityError(new Error(), 'foo'); +new restify.LockedError(new Error(), 'foo'); +new restify.FailedDependencyError(new Error(), 'foo'); +new restify.UnorderedCollectionError(new Error(), 'foo'); +new restify.UpgradeRequiredError(new Error(), 'foo'); +new restify.PreconditionRequiredError(new Error(), 'foo'); +new restify.TooManyRequestsError(new Error(), 'foo'); +new restify.RequestHeaderFieldsTooLargeError(new Error(), 'foo'); +new restify.InternalServerError(new Error(), 'foo'); +new restify.NotImplementedError(new Error(), 'foo'); +new restify.BadGatewayError(new Error(), 'foo'); +new restify.ServiceUnavailableError(new Error(), 'foo'); +new restify.GatewayTimeoutError(new Error(), 'foo'); +new restify.HttpVersionNotSupportedError(new Error(), 'foo'); +new restify.VariantAlsoNegotiatesError(new Error(), 'foo'); +new restify.InsufficientStorageError(new Error(), 'foo'); +new restify.BandwidthLimitExceededError(new Error(), 'foo'); +new restify.NotExtendedError(new Error(), 'foo'); +new restify.NetworkAuthenticationRequiredError(new Error(), 'foo'); +new restify.RestError(new Error(), 'foo'); + +new restify.PreconditionFailedError(new Error(), 'foo'); +new restify.BadDigestError(new Error(), 'foo'); +new restify.BadMethodError(new Error(), 'foo'); +new restify.InternalError(new Error(), 'foo'); +new restify.InvalidArgumentError(new Error(), 'foo'); +new restify.InvalidContentError(new Error(), 'foo'); +new restify.InvalidCredentialsError(new Error(), 'foo'); +new restify.InvalidHeaderError(new Error(), 'foo'); +new restify.InvalidVersionError(new Error(), 'foo'); +new restify.MissingParameterError(new Error(), 'foo'); +new restify.NotAuthorizedError(new Error(), 'foo'); +new restify.RequestExpiredError(new Error(), 'foo'); +new restify.RequestThrottledError(new Error(), 'foo'); +new restify.ResourceNotFoundError(new Error(), 'foo'); +new restify.WrongAcceptError(new Error(), 'foo'); + +new restify.PreconditionFailedError(); +new restify.BadDigestError(); +new restify.BadMethodError(); +new restify.InternalError(); +new restify.InvalidArgumentError(); +new restify.InvalidContentError(); +new restify.InvalidCredentialsError(); +new restify.InvalidHeaderError(); +new restify.InvalidVersionError(); +new restify.MissingParameterError(); +new restify.NotAuthorizedError(); +new restify.RequestExpiredError(); +new restify.RequestThrottledError(); +new restify.ResourceNotFoundError(); +new restify.WrongAcceptError(); + +server.name = ""; +server.version = ""; +server.log = {}; +server.acceptable = ["test"]; +server.url = ""; + +server.address().port; +server.address().family; +server.address().address; + +server.listen("somePath", send); +server.close(); + +server.use(restify.acceptParser(server.acceptable)); +server.use(restify.authorizationParser()); +server.use(restify.dateParser()); +server.use(restify.queryParser()); +server.use(restify.jsonp()); +server.use(restify.gzipResponse()); +server.use(restify.bodyParser()); +server.use(restify.CORS({ + origins: ['https://foo.com', 'http://bar.com', 'http://baz.com:8081'], + credentials: true, + headers: ['x-foo'] +})); +server.use(restify.throttle({ + burst: 100, + rate: 50, + ip: true, + overrides: { + '192.168.1.1': { + rate: 0, + burst: 0 + } + } +})); + +server.on('after', restify.auditLogger({ + log: () => { } +})); + +server.on('after', (req: restify.Request, res: restify.Response, route: restify.Route, err: any) => { + route.spec.method === 'GET'; + route.spec.name === 'routeName'; + route.spec.path === '/some/path'; + route.spec.path === /\/some\/path\/.*/; + route.spec.versions === ['v1']; + restify.auditLogger({ log: () => { } })(req, res, route, err); +}); + +( restify).defaultResponseHeaders = function(this: restify.Request, data: any) { + this.header('Server', 'helloworld'); +}; + +( restify).defaultResponseHeaders = false; + +// RESTIFY Client Tests + +let client = restify.createJsonClient({ + url: 'https://api.us-west-1.joyentcloud.com', + version: '*' +}); + +client = restify.createStringClient({ + accept: "test", + connectTimeout: 30, + dtrace: {}, + gzip: {}, + headers: {}, + log: {}, + retry: {}, + signRequest: () => { }, + url: "", + userAgent: "", + version: "" +}); + +client.head('test', (err: any, req: restify.Request, res: restify.Response) => { }); +client.put('path', {}, (err: any, req: restify.Request, res: restify.Response, obj: any) => { }); +client.patch('path', {}, (err: any, req: restify.Request, res: restify.Response, obj: any) => { }); +client.del('path', (err: any, req: restify.Request, res: restify.Response) => { }); + +client.post('/foo', { hello: 'world' }, (err: any, req: restify.Request, res: restify.Response, obj: any) => { + console.log('%d -> %j', res.statusCode, res.headers); + console.log('%j', obj); +}); + +client.get('/foo/bar', (err: any, req: restify.Request, res: restify.Response, data: string) => { + console.log('%s', data); +}); + +let client2 = restify.createClient({ + url: 'http://127.0.0.1' +}); + +client2.get('/str/mcavage', (err: any, req: any) => { + req.on('result', (err: any, res: any) => { + res.body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk: string) => { + res.body += chunk; + }); + + res.on('end', () => { + console.log(res.body); + }); + }); +}); + +client.basicAuth('test', 'password'); +client2.basicAuth('test', 'password'); diff --git a/types/restify/v4/tsconfig.json b/types/restify/v4/tsconfig.json new file mode 100644 index 0000000000..c0de0b8fd9 --- /dev/null +++ b/types/restify/v4/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "restify-tests.ts" + ] +} diff --git a/types/restify/v4/tslint.json b/types/restify/v4/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/restify/v4/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2fde3abd6c21f1f75d3cfc73a4cd4b7161c82d9a Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Fri, 7 Jul 2017 09:58:52 +0100 Subject: [PATCH 0196/1618] Updated resitfy v4 type roots --- types/restify/v4/tsconfig.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/restify/v4/tsconfig.json b/types/restify/v4/tsconfig.json index c0de0b8fd9..1288a1617c 100644 --- a/types/restify/v4/tsconfig.json +++ b/types/restify/v4/tsconfig.json @@ -11,6 +11,9 @@ "typeRoots": [ "../../" ], + "paths": { + "restify": [ "restify/v2" ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true From 969845c8a29775e3c78ff037bb57f3746dd89184 Mon Sep 17 00:00:00 2001 From: Jutta Klebe Date: Fri, 7 Jul 2017 11:00:55 +0200 Subject: [PATCH 0197/1618] Switch to union type. --- types/knockout.validation/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/knockout.validation/index.d.ts b/types/knockout.validation/index.d.ts index 5b8b61d066..8b0300bd7f 100644 --- a/types/knockout.validation/index.d.ts +++ b/types/knockout.validation/index.d.ts @@ -158,7 +158,8 @@ interface KnockoutValidationRuleDefinitions { required: KnockoutValidationRuleDefinition; step: KnockoutValidationRuleDefinition; unique: KnockoutValidationRuleDefinition; - [ruleName: string]: KnockoutValidationRuleBase; + [ruleName: string]: KnockoutValidationRuleDefinition | + KnockoutValidationAsyncRuleDefinition; } interface KnockoutValidationRule { From eb694b90bc3a7729d85860e037d67ce95c2d38ec Mon Sep 17 00:00:00 2001 From: strajuser Date: Fri, 7 Jul 2017 12:01:35 +0300 Subject: [PATCH 0198/1618] - definitions for identify features --- types/esri-leaflet/esri-leaflet-tests.ts | 30 ++++++ types/esri-leaflet/index.d.ts | 111 +++++++++++++++++++++++ 2 files changed, 141 insertions(+) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index e6feca9aba..4c897f7540 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -431,3 +431,33 @@ query.count(function(error, count, response){ }); query.ids(function(error, ids, response){ }); query.where("zone_id='B'").bounds(function(error, latLngBounds, response){ }); + +let identifyFeaturesOptions: L.esri.IdentifyFeaturesOptions; +let identifyFeatures: L.esri.IdentifyFeatures; + +identifyFeaturesOptions = { +}; +identifyFeaturesOptions = { + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}; + +identifyFeatures = L.esri.identifyFeatures(identifyFeaturesOptions); +identifyFeatures = L.esri.identifyFeatures({}); +identifyFeatures = L.esri.identifyFeatures({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +identifyFeatures = new L.esri.IdentifyFeatures(identifyFeaturesOptions); +identifyFeatures = new L.esri.IdentifyFeatures({}); +identifyFeatures = new L.esri.IdentifyFeatures({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index e74511f5c7..66d8ae4d6d 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -972,6 +972,117 @@ declare namespace L { * @returns {Query} */ function query(options: QueryOptions): Query; + + /** + * Options for IdentifyFeatures + * + * @interface IdentifyFeaturesOptions + * @extends {ServiceOptions} + */ + interface IdentifyFeaturesOptions extends ServiceOptions { } + + /** + * L.esri.IdentifyFeatures is an abstraction for the Identify API found in Map Services. It provides a chainable API for building request parameters and executing the request. + * + * @class IdentifyFeatures + * @extends {Task} + */ + class IdentifyFeatures extends Task { + constructor(options: IdentifyFeaturesOptions | ImageService); + /** + * The map to identify features on. + * + * @param {L.Map} map + * @returns {this} + * @memberof IdentifyFeatures + */ + on(map: L.Map): this; + /** + * Identifies feautres at a given + * + * @param {LatLngExpression} latlng + * @returns {this} + * @memberof IdentifyFeatures + */ + at(latlng: LatLngExpression): this; + /** + * Add a layer definition to the query. + * + * @param {number} id + * @param {string} where + * @returns {this} + * @memberof IdentifyFeatures + */ + layerDef(id: number, where: string): this; + /** + * Identifies features within a given time range. + * + * @param {Date} from + * @param {Date} to + * @returns {this} + * @memberof IdentifyFeatures + */ + between(from: Date, to: Date): this; + /** + * By default, only the topmost feature will be identified, but it is possible to specify both an alternative strategy and array of individual layers. See the REST API documentation for more information about valid combinations. + * ex: .layers('all:0'). + * + * @param {string} layers + * @returns {this} + * @memberof IdentifyFeatures + */ + layers(layers: string): this; + /** + * Return only this many decimal points of precision in the output geometries. + * + * @param {number} precision + * @returns {this} + * @memberof IdentifyFeatures + */ + precision(precision: number): this; + /** + * Buffer the identify area by a given number of screen pixels. + * + * @param {number} precision + * @returns {this} + * @memberof IdentifyFeatures + */ + tolerance(precision: number): this; + /** + * Return geometry with results. Default is true. + * + * @param {boolean} returnGeometry + * @returns {this} + * @memberof IdentifyFeatures + */ + returnGeometry(returnGeometry: boolean): this; + /** + * Simplify the geometries of the output features for the current map view. the factor parameter controls the amount of simplification between 0 (no simplification) and 1 (the most basic shape possible). + * + * @param {L.Map} map + * @param {number} factor + * @returns {this} + * @memberof IdentifyFeatures + */ + simplify(map: L.Map, factor: number): this; + /** + * Executes the identify request with the current parameters, identified features will be passed to callback as a GeoJSON FeatureCollection. Accepts an optional function context + * + * @param {FeatureCallbackHandler} callback + * @param {*} context + * @returns {this} + * @memberof IdentifyFeatures + */ + run(callback: FeatureCallbackHandler, context: any): this; + } + + /** + * L.esri.IdentifyFeatures is an abstraction for the Identify API found in Map Services. It provides a chainable API for building request parameters and executing the request. + * + * @param {(IdentifyFeaturesOptions | ImageService)} options + * @returns {IdentifyFeatures} + */ + function identifyFeatures(options: IdentifyFeaturesOptions | ImageService): IdentifyFeatures; } } From 58305be245cb94d1b698054cd0f79a674d3cf1a7 Mon Sep 17 00:00:00 2001 From: strajuser Date: Fri, 7 Jul 2017 12:03:30 +0300 Subject: [PATCH 0199/1618] - IdentifyFeatures definition fixes --- types/esri-leaflet/esri-leaflet-tests.ts | 6 ++++++ types/esri-leaflet/index.d.ts | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index 4c897f7540..06b27c07e3 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -461,3 +461,9 @@ identifyFeatures = new L.esri.IdentifyFeatures({ useCors: true, timeout: 1000 }); + +identifyFeatures + .on(map) + .at([45.543, -122.621]) + .layers('visible:1') + .run(function(error, featureCollection, response) { }); \ No newline at end of file diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index 66d8ae4d6d..7a5861933f 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -1073,7 +1073,7 @@ declare namespace L { * @returns {this} * @memberof IdentifyFeatures */ - run(callback: FeatureCallbackHandler, context: any): this; + run(callback: FeatureCallbackHandler, context?: any): this; } /** From dfc73442c316e9a0b0119a8c9a017a20b10de7b9 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Fri, 7 Jul 2017 10:04:22 +0100 Subject: [PATCH 0200/1618] Fix restify v4 type root --- types/restify/v4/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/restify/v4/tsconfig.json b/types/restify/v4/tsconfig.json index 1288a1617c..dae2203c7e 100644 --- a/types/restify/v4/tsconfig.json +++ b/types/restify/v4/tsconfig.json @@ -12,7 +12,7 @@ "../../" ], "paths": { - "restify": [ "restify/v2" ] + "restify": [ "restify/v4" ] }, "types": [], "noEmit": true, From 24485beed8a58bcd3e236124d83b6f4908d51bb4 Mon Sep 17 00:00:00 2001 From: strajuser Date: Fri, 7 Jul 2017 12:12:40 +0300 Subject: [PATCH 0201/1618] - definitions for Find task --- types/esri-leaflet/esri-leaflet-tests.ts | 41 ++++++- types/esri-leaflet/index.d.ts | 143 ++++++++++++++++++++++- 2 files changed, 182 insertions(+), 2 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index 06b27c07e3..cb68af894e 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -466,4 +466,43 @@ identifyFeatures .on(map) .at([45.543, -122.621]) .layers('visible:1') - .run(function(error, featureCollection, response) { }); \ No newline at end of file + .run(function(error, featureCollection, response) { }); + +let findOptions: L.esri.FindOptions; +let find: L.esri.Find; + +findOptions = { +}; +findOptions = { + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}; + +find = L.esri.find(findOptions); +find = L.esri.find({}); +find = L.esri.find({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +find = new L.esri.Find(findOptions); +find = new L.esri.Find({}); +find = new L.esri.Find({ + url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/0', + proxy: '//localhost/proxy', + useCors: true, + timeout: 1000 +}); + +find.layers('18') + .text('Colorado'); +find.run(function(error, featureCollection, response){ }); + +find.layers('13') + .text('198133') + .fields('GNIS_ID'); +find.run(function(error, featureCollection, response) { }); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index 7a5861933f..28bcfcec9d 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -1031,7 +1031,7 @@ declare namespace L { * @returns {this} * @memberof IdentifyFeatures */ - layers(layers: string): this; + layers(layers: string | Array): this; /** * Return only this many decimal points of precision in the output geometries. * @@ -1083,6 +1083,147 @@ declare namespace L { * @returns {IdentifyFeatures} */ function identifyFeatures(options: IdentifyFeaturesOptions | ImageService): IdentifyFeatures; + + /** + * Options for Find Task + * + * @interface FindOptions + * @extends {ServiceOptions} + */ + interface FindOptions extends ServiceOptions { } + + /** + * L.esri.Find is an abstraction for the find API included in Map Services. It provides a chainable API for building request parameters and executing find tasks. + * + * @class Find + * @extends {Task} + */ + class Find extends Task { + constructor(options: FindOptions | MapService); + /** + * Text that is searched across the layers and fields the user specifies. + * + * @param {string} text + * @returns {this} + * @memberof Find + */ + text(text: string): this; + /** + * When true find task will search for a value that contains the searchText. When false it will do an exact match on the searchText string. Default is true. + * + * @param {boolean} contains + * @returns {this} + * @memberof Find + */ + contains(contains: boolean): this; + /** + * An array or comma-separated list of field names to search. If not specified, all fields are searched. + * + * @param {(string | Array)} fields + * @returns {this} + * @memberof Find + */ + fields(fields: string | Array): this; + /** + * The well known ID (ex. 4326) for the results. + * + * @param {number} sr + * @returns {this} + * @memberof Find + */ + spatialReference(sr: number): this; + /** + * Add a layer definition to the find task. + * + * @param {number} id + * @param {string} where + * @returns {this} + * @memberof Find + */ + layerDef(id: number, where: string): this; + /** + * Layers to perform find task on. Accepts an array of layer IDs or comma-separated list. + * + * @param {(string | Array)} layers + * @returns {this} + * @memberof Find + */ + layers(layers: string | Array): this; + /** + * Return geometry with results. Default is true. + * + * @param {boolean} returnGeometry + * @returns {this} + * @memberof Find + */ + returnGeometry(returnGeometry: boolean): this; + /** + * Specifies the maximum allowable offset to be used for generalizing geometries returned by the find task. + * + * @param {number} maxAllowableOffset + * @returns {this} + * @memberof Find + */ + maxAllowableOffset(maxAllowableOffset: number): this; + /** + * Specifies the number of decimal places in returned geometries. + * + * @param {number} precision + * @returns {this} + * @memberof Find + */ + precision(precision: number): this; + /** + * Include Z values in the results. Default value is true. This parameter only applies if returnGeometry=true. + * + * @param {boolean} returnZ + * @returns {this} + * @memberof Find + */ + returnZ(returnZ: boolean): this; + /** + * Includes M values if the features have them. Default value is false. This parameter only applies if returnGeometry=true. + * + * @param {boolean} returnM + * @returns {this} + * @memberof Find + */ + returnM(returnM: boolean): this; + /** + * Property used for adding new layers or modifying the data source of existing ones in the current map service. + * + * @param {*} dynamicLayers + * @returns {this} + * @memberof Find + */ + dynamicLayers(dynamicLayers: any): this; + /** + * Simplify the geometries of the output features for the current map view. the factor parameter controls the amount of simplification between 0 (no simplification) and 1 (simplify to the most basic shape possible). + * + * @param {L.Map} map + * @param {number} factor + * @returns {this} + * @memberof Find + */ + simplify(map: L.Map, factor: number): this; + /** + * Exectues the find request with the current parameters, features will be passed to callback as a GeoJSON FeatureCollection. Accepts an optional function context. + * + * @param {FeatureCallbackHandler} callback + * @param {*} [context] + * @returns {this} + * @memberof Find + */ + run(callback: FeatureCallbackHandler, context?: any): this; + } + + /** + * L.esri.Find is an abstraction for the find API included in Map Services. It provides a chainable API for building request parameters and executing find tasks. + * + * @param {(FindOptions | MapService)} options + * @returns {Find} + */ + function find(options: FindOptions | MapService): Find; } } From 23cdb472bbfd69f4494a810878c040e58e3d249b Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 17:17:06 +0800 Subject: [PATCH 0202/1618] add uploader --- types/zui/index.d.ts | 1 + types/zui/uploader.d.ts | 148 ++++++++++++++++++++++++++++++++++++++++ types/zui/zui-tests.ts | 11 +++ 3 files changed, 160 insertions(+) create mode 100644 types/zui/uploader.d.ts diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index 2bd66ea5e1..21c4dfe1a8 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -20,6 +20,7 @@ /// /// /// +/// /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. diff --git a/types/zui/uploader.d.ts b/types/zui/uploader.d.ts new file mode 100644 index 0000000000..18ebfb1127 --- /dev/null +++ b/types/zui/uploader.d.ts @@ -0,0 +1,148 @@ +interface UploaderOption { + drop_element?: string, + browse_button?: string, + url: string, + qiniu?: object, + filters?: { + mime_type: Array<{ + title?: string, + extensions?: string + }>, + max_file_size?: string, + prevent_duplicates?: string + }, + fileList?: string, + fileTemplate?: string, + fileFormater?($file: JQuery, file: FileObj, status: STATUS): void; + fileIconCreator?(fileType: string, file: FileObj, uploader: Uploader): void; + staticFiles?: Array<{ + id?: string, + name?: string, + type?: string, + size?: string, + origSize?: string, + lastModifiedDate?: Date + }>; + rename?: boolean, + renameExtension?: boolean, + renameByClick?: boolean, + autoUpload?: boolean, + browseByClickList?: boolean, + dropPlaceholder?: boolean, + previewImageIcon?: boolean, + sendFileName?: boolean, + sendFileId?: boolean, + responseHandler?: boolean | Function, + limitFilesCount?: boolean | number, + deleteConfirm?: boolean | string, + removeUploaded?: boolean, + statusCreator?(total: UploadProgress, state: STATUS, uploader: Uploader): void; + previewImageSize?: { width: number, height: number }, + uploadedMessage?: boolean, + deleteActionOnDone?: boolean, + renameActionOnDone?: boolean, + headers?: object, + multipart?: boolean, + multipart_params?: object | Function, + max_retries?: number, + chunk_size?: string, + resize?: { + width?: number, + height?: number, + crop?: boolean, + quuality?: number, + preserve_headers?: boolean + }, + multi_selection?: boolean, + unique_names?: boolean, + runtimes?: string, + file_data_name?: string, + flash_swf_url?: string, + silverlight_xap_url?: string, + lang?: string, + + onInit?(): void, + onFilesAdded?(fiels: Array): void; + onUploadProgress?(file: FileObj): void; + onFileUploaded?(file: FileObj, responseObject: ResponseObject): void + onUploadComplete?(files: Array): void, + onFilesRemoved?(files: Array): void, + onChunkUploaded?(file: FileObj, responseObject: ResponseObject): void, + onUploadFile?(file: FileObj): void, + onBeforeUpload?(file: FileObj): void, + onStateChanged?(status: STATUS): void, + onQueueChanged?(): void, + onError?(error: { error: ERRORS, message: string, file: FileObj }): void +} +interface ResponseObject { + response?: string, + responseHeaders?: object, + status?: number, + offset?: number, + total?: number +} +declare enum STATUS { + STOPPED = 1, STARTED = 2, QUEUED = 1, UPLOADING = 2, FAILED = 3, DONE = 4 +} +interface FileObj { + id?: string, + name?: string, + type?: string, + ext?: string, + isImage?: boolean, + previewImage?: string, + size?: number, + origSize?: number, + loaded?: number, + percent?: number, + status?: STATUS, + lastModifiedDate?: Date, + getNative(): File, + destroy(): void +} +interface UploadProgress { + size?: number, + loaded?: number, + uploaded?: number, + failed?: number, + queued?: number, + percent?: number, + bytesPerSec?: number +} +declare enum ERRORS { + GENERIC_ERROR = -100, + HTTP_ERROR = -200, + IO_ERROR = -300, + SECURITY_ERROR = -400, + INIT_ERROR = -500, + FILE_SIZE_ERROR = -600, + FILE_EXTENSION_ERROR = -601, + FILE_DUPLICATE_ERROR = -602, + IMAGE_FORMAT_ERROR = -700, + IMAGE_MEMORY_ERROR = -701, + IMAGE_DIMENSIONS_ERROR = -702 +} +interface Uploader { + showMessage(message: string, type: string, time?: number): void; + hideMessage(): void; + start(): void, + stop(): void, + getState(): STATUS, + isStarted(): boolean, + isStopped(): boolean, + getFiles(): Array; + getTotal(): UploadProgress, + disableBrowse(disable: boolean): void, + getFile(id: string): FileObj, + showFile(file: FileObj | Array): void; + removeFile(file: FileObj): void; + destroy(): void, + showStatus(): void +} +interface UplaoderStatic { + +} +interface JQuery { + uploader(option: UploaderOption): JQuery; + +} \ No newline at end of file diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index 12ce598c51..ea90bd89af 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -326,3 +326,14 @@ $('table.datatable').datatable('load', { ] }); + +/** + * uplaoder + */ +$('#myUploader').uploader({ + url: '...', + // ..., + onUploadFile: function(file:FileObj) { + console.log('上传成功', file); + } +}); \ No newline at end of file From 9fdb53083c77b80858fd68cc57b2787a88c2c31f Mon Sep 17 00:00:00 2001 From: strajuser Date: Fri, 7 Jul 2017 12:17:46 +0300 Subject: [PATCH 0203/1618] - Find and IdentifyFeatures return type to service methods. --- types/esri-leaflet/esri-leaflet-tests.ts | 81 +++++++++++------------- types/esri-leaflet/index.d.ts | 30 +++++++-- 2 files changed, 61 insertions(+), 50 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index cb68af894e..c5db206559 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -94,10 +94,17 @@ tiledMapLayer = new L.esri.TiledMapLayer({ tiledMapLayer.authenticate('secret'); tiledMapLayer.metadata((err, metadata) => { }); -// TODO: -tiledMapLayer.identify(); -tiledMapLayer.find(); -tiledMapLayer.query(); +tiledMapLayer.identify() + .at(latlng) + .run(function(error, featureCollection){ }); +tiledMapLayer.find() + .layers('18') + .text('Colorado') + .run(function(error, featureCollection){ }); +tiledMapLayer.query() + .layer(0) + .within(latlngbounds) + .run(function(error, featureCollection, response){ }); let dynamicMapLayer: L.esri.DynamicMapLayer; let dynamicMapLayerOptions: L.esri.DynamicMapLayerOptions; @@ -211,18 +218,13 @@ dynamicMapLayer.bindPopup( dynamicMapLayer.metadata(function (error, metadata) { }); -// TODO: -// dynamicMapLayer.identify() -// .at(latlng) -// .run(function(error, featureCollection){ -// // console.log(featureCollection); -// }); -// dynamicMapLayer.find() -// .layers('18') -// .searchText('Colorado') -// .run(function(error, featureCollection){ -// // console.log(featureCollection); -// }); +dynamicMapLayer.identify() + .at(latlng) + .run(function(error, featureCollection){ }); +dynamicMapLayer.find() + .layers('18') + .text('Colorado') + .run(function(error, featureCollection){ }); dynamicMapLayer.query() .layer(0) .within(latlngbounds) @@ -262,35 +264,26 @@ mapService.query() .layer(0) .within(latlngbounds) .run(function(error, featureCollection, response){ }); -// TODO: -// mapService.identify() -// .on(map) -// .at(latlng) -// .run(function(error, featureCollection, response){ -// // console.log(featureCollection) -// }); -// mapService.find() -// .layers('18') -// .text('Colorado') -// .fields('name') -// .run(function(error, featureCollection, response){ -// // console.log(featureCollection) -// }); +mapService.identify() + .on(map) + .at(latlng) + .run(function(error, featureCollection, response){ }); +mapService.find() + .layers('18') + .text('Colorado') + .fields('name') + .run(function(error, featureCollection, response){ }); -// mapService.identify() -// .on(map) -// .at([45.543, -122.621]) -// .layers('visible:1') -// .run(function(error, featureCollection, response){ -// // console.log("UTC Offset: " + featureCollection.features[0].properties.ZONE); -// }); -// mapService.find() -// .layers('18') -// .searchText('Colorado') -// .searchFields('GNIS_NAME') -// .run(function(error, featureCollection, response){ -// // console.log('Found GNIS ID: ' + featureCollection.features[0].properties.GNIS_ID + ' for the state of ' + featureCollection.features[0].properties.STATE_NAME); -// }); +mapService.identify() + .on(map) + .at([45.543, -122.621]) + .layers('visible:1') + .run(function(error, featureCollection, response){ }); +mapService.find() + .layers('18') + .text('Colorado') + .fields('GNIS_NAME') + .run(function(error, featureCollection, response){ }); let imageServiceOptions : L.esri.ImageServiceOptions; let imageService: L.esri.ImageService; diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index 28bcfcec9d..f1c84b3588 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -140,8 +140,26 @@ declare namespace L { * @memberof TiledMapLayer */ metadata(callback: CallbackHandler, context?: any): this; - identify() : any; - find(): any; + /** + * Returns a new L.esri.services.IdentifyFeatures object that can be used to identify features on this layer. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof TiledMapLayer + */ + identify(): IdentifyFeatures; + /** + * Returns a new L.esri.services.Find object that can be used to find features. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof TiledMapLayer + */ + find(): Find; + /** + * Returns a new L.esri.Query object that can be used to query this service. + * + * @returns {*} + * @memberof TiledMapLayer + */ query(): Query; } @@ -431,14 +449,14 @@ declare namespace L { * @returns {*} * @memberof DynamicMapLayer */ - identify(): any; + identify(): IdentifyFeatures; /** * Returns a new L.esri.services.Find object that can be used to find features. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. * * @returns {*} * @memberof DynamicMapLayer */ - find(): any; + find(): Find; /** * Returns a new L.esri.Query object that can be used to query this service. * @@ -570,14 +588,14 @@ declare namespace L { * @returns {*} * @memberof MapService */ - identify(): any; + identify(): IdentifyFeatures; /** * Returns a new L.esri.services.Find object that can be used to find features. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. * * @returns {*} * @memberof MapService */ - find(): any; + find(): Find; /** * Returns a new L.esri.Query object that can be used to query this service. * From aae9945f3075cf08d37183e68803e27b5f8b23b2 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 17:30:27 +0800 Subject: [PATCH 0204/1618] change packagename --- types/zui/boostrap.datetimepicker/index.d.ts | 7 +++---- types/zui/bootstrap.d.ts | 8 ++++---- types/zui/color.d.ts | 5 +++++ types/zui/datatable.d.ts | 5 +++++ types/zui/draggable.d.ts | 4 ++++ types/zui/droppable.d.ts | 4 ++++ types/zui/imagecutter.d.ts | 5 +++++ types/zui/messager.d.ts | 5 +++++ types/zui/modal.d.ts | 4 ++++ types/zui/modal.trigger.d.ts | 5 +++++ types/zui/selectable.d.ts | 5 +++++ types/zui/sortable.d.ts | 5 +++++ types/zui/store.d.ts | 4 ++++ types/zui/treemenu.d.ts | 5 +++++ types/zui/uploader.d.ts | 5 +++++ 15 files changed, 68 insertions(+), 8 deletions(-) diff --git a/types/zui/boostrap.datetimepicker/index.d.ts b/types/zui/boostrap.datetimepicker/index.d.ts index 129d77491a..9f53c1eee9 100644 --- a/types/zui/boostrap.datetimepicker/index.d.ts +++ b/types/zui/boostrap.datetimepicker/index.d.ts @@ -1,8 +1,7 @@ -// Type definitions for Bootstrap datetimepicker v3 3.x -// Project: http://eonasdan.github.io/bootstrap-datetimepicker -// Definitions by: Jesica N. Fera +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 /** * bootstrap-datetimepicker.js 3.0.0 Copyright (c) 2014 Jonathan Peterson diff --git a/types/zui/bootstrap.d.ts b/types/zui/bootstrap.d.ts index 3976b53886..62f680e5b3 100644 --- a/types/zui/bootstrap.d.ts +++ b/types/zui/bootstrap.d.ts @@ -1,8 +1,8 @@ -// Type definitions for Bootstrap 3.3.5 -// Project: http://twitter.github.com/bootstrap/ -// Definitions by: Boris Yankov +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 + interface ModalOptions { backdrop?: boolean | string; diff --git a/types/zui/color.d.ts b/types/zui/color.d.ts index e19e13c3c2..712577f86f 100644 --- a/types/zui/color.d.ts +++ b/types/zui/color.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface Color { rgb(rgbaColor?: string): object; hue(hue: string): string, diff --git a/types/zui/datatable.d.ts b/types/zui/datatable.d.ts index 15734e1e48..76d271f458 100644 --- a/types/zui/datatable.d.ts +++ b/types/zui/datatable.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface Col { width?: number, text?: string, diff --git a/types/zui/draggable.d.ts b/types/zui/draggable.d.ts index 163d5cfa5d..24c6eeae9d 100644 --- a/types/zui/draggable.d.ts +++ b/types/zui/draggable.d.ts @@ -1,3 +1,7 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Postion { left: number; diff --git a/types/zui/droppable.d.ts b/types/zui/droppable.d.ts index d06c762a6c..792e15eed6 100644 --- a/types/zui/droppable.d.ts +++ b/types/zui/droppable.d.ts @@ -1,3 +1,7 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Postion { left: number; diff --git a/types/zui/imagecutter.d.ts b/types/zui/imagecutter.d.ts index c849a4e61d..64dfc3700a 100644 --- a/types/zui/imagecutter.d.ts +++ b/types/zui/imagecutter.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface ImageCutterOption { coverColor?: string, coverOpacity?: number, diff --git a/types/zui/messager.d.ts b/types/zui/messager.d.ts index 91878a3232..a7397eff19 100644 --- a/types/zui/messager.d.ts +++ b/types/zui/messager.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + declare enum MessagerTypeEnum { 'default', 'primary', 'success', 'info', 'warning', 'danger', 'important', 'special' } diff --git a/types/zui/modal.d.ts b/types/zui/modal.d.ts index 5f7a903f4f..7bc8b22da9 100644 --- a/types/zui/modal.d.ts +++ b/types/zui/modal.d.ts @@ -1,3 +1,7 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface ModalOptions { backdrop?: boolean | string; diff --git a/types/zui/modal.trigger.d.ts b/types/zui/modal.trigger.d.ts index fee8161ce0..8cb71d6b29 100644 --- a/types/zui/modal.trigger.d.ts +++ b/types/zui/modal.trigger.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface ModalTriggerOption { name?: string, className?: string, diff --git a/types/zui/selectable.d.ts b/types/zui/selectable.d.ts index 92ee5e23ba..1cb91ffe8c 100644 --- a/types/zui/selectable.d.ts +++ b/types/zui/selectable.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface SelectableEvent { selections: Map; selected: Array; diff --git a/types/zui/sortable.d.ts b/types/zui/sortable.d.ts index 4c3fc55bc1..226b445837 100644 --- a/types/zui/sortable.d.ts +++ b/types/zui/sortable.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface SortEvent { list: Array; element: JQuery | object; diff --git a/types/zui/store.d.ts b/types/zui/store.d.ts index 3544cbdd60..0da80c6420 100644 --- a/types/zui/store.d.ts +++ b/types/zui/store.d.ts @@ -1,3 +1,7 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface StoreStatic { enable: boolean; diff --git a/types/zui/treemenu.d.ts b/types/zui/treemenu.d.ts index 3512efe8ae..048752aa56 100644 --- a/types/zui/treemenu.d.ts +++ b/types/zui/treemenu.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface TreeNode { title?: string, url?: string, diff --git a/types/zui/uploader.d.ts b/types/zui/uploader.d.ts index 18ebfb1127..60a53e4c67 100644 --- a/types/zui/uploader.d.ts +++ b/types/zui/uploader.d.ts @@ -1,3 +1,8 @@ +// Type definitions for zui 1.7 +// Project: http://zui.sexy +// Definitions by: YuanXu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + interface UploaderOption { drop_element?: string, browse_button?: string, From 3966c184e740276e3fe356b2dc1a6a1b28e44343 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 17:34:58 +0800 Subject: [PATCH 0205/1618] refactor: datetimepicker --- .../zui/boostrap.datetimepicker/package.json | 5 ---- .../zui/boostrap.datetimepicker/tsconfig.json | 27 ------------------- ...dex.d.ts => bootstrap.datetimepicker.d.ts} | 0 types/zui/index.d.ts | 2 +- 4 files changed, 1 insertion(+), 33 deletions(-) delete mode 100644 types/zui/boostrap.datetimepicker/package.json delete mode 100644 types/zui/boostrap.datetimepicker/tsconfig.json rename types/zui/{boostrap.datetimepicker/index.d.ts => bootstrap.datetimepicker.d.ts} (100%) diff --git a/types/zui/boostrap.datetimepicker/package.json b/types/zui/boostrap.datetimepicker/package.json deleted file mode 100644 index 4c6d24a445..0000000000 --- a/types/zui/boostrap.datetimepicker/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "dependencies": { - "moment": ">=2.14.0" - } -} \ No newline at end of file diff --git a/types/zui/boostrap.datetimepicker/tsconfig.json b/types/zui/boostrap.datetimepicker/tsconfig.json deleted file mode 100644 index c81098be9e..0000000000 --- a/types/zui/boostrap.datetimepicker/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../../", - "typeRoots": [ - "../../" - ], - "types": [], - "paths": { - "bootstrap.v3.datetimepicker": [ - "bootstrap.v3.datetimepicker/v3" - ] - }, - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts" - ] -} \ No newline at end of file diff --git a/types/zui/boostrap.datetimepicker/index.d.ts b/types/zui/bootstrap.datetimepicker.d.ts similarity index 100% rename from types/zui/boostrap.datetimepicker/index.d.ts rename to types/zui/bootstrap.datetimepicker.d.ts diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index 21c4dfe1a8..13c2475bab 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -8,7 +8,7 @@ /// /// -/// +/// /// /// From b555ee070da48c3cfc0c152f7e21f55d7b392177 Mon Sep 17 00:00:00 2001 From: Kamil Ejsymont Date: Fri, 7 Jul 2017 11:38:39 +0200 Subject: [PATCH 0206/1618] Fix map property --- types/jsforce/query.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jsforce/query.d.ts b/types/jsforce/query.d.ts index ac59969b08..a2b10d110a 100644 --- a/types/jsforce/query.d.ts +++ b/types/jsforce/query.d.ts @@ -10,7 +10,6 @@ export interface ExecuteOptions { export class Query { end(): Query; filter(filter: Object): Query; - map(map: Object): Query; include(include: string): Query; hint(hint: Object): Query; limit(value: number): Query; @@ -25,6 +24,7 @@ export class Query { delete(callback?: (err: Error, ret: RecordResult) => void): any; destroy(callback?: (err: Error, ret: RecordResult) => void): Promise; explain(callback?: (err: Error, info: ExplainInfo) => void): Promise; + map(map: Object): Promise; scanAll(value: boolean): Query; select(fields: Object | string[] | string): Query; then(onSuccess?: Function, onRejected?: Function): Promise; From 5cd99dd63c555416f3720dad70775668e8f9ab52 Mon Sep 17 00:00:00 2001 From: Anton Korniychuk Date: Fri, 7 Jul 2017 12:47:33 +0300 Subject: [PATCH 0207/1618] Chart.js: fix ChartDataSets properties Added two missing properties into ChartDataSets --- types/chart.js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index d567492602..be55d35ee4 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -361,6 +361,7 @@ declare namespace Chart { type ChartColor = string | CanvasGradient | CanvasPattern | string[]; interface ChartDataSets { + cubicInterpolationMode?: string; backgroundColor?: ChartColor | ChartColor[]; borderWidth?: number; borderColor?: ChartColor; @@ -388,6 +389,7 @@ declare namespace Chart { hidden?: boolean; hideInLegendAndTooltip?: boolean; stack?: string; + spanGaps?: string; } interface ChartScales { From 411f20e3f5e34af494bd194c10ce3df044bbf59a Mon Sep 17 00:00:00 2001 From: Kamil Ejsymont Date: Fri, 7 Jul 2017 11:56:12 +0200 Subject: [PATCH 0208/1618] Final fix --- types/jsforce/query.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jsforce/query.d.ts b/types/jsforce/query.d.ts index a2b10d110a..90e5734253 100644 --- a/types/jsforce/query.d.ts +++ b/types/jsforce/query.d.ts @@ -24,7 +24,7 @@ export class Query { delete(callback?: (err: Error, ret: RecordResult) => void): any; destroy(callback?: (err: Error, ret: RecordResult) => void): Promise; explain(callback?: (err: Error, info: ExplainInfo) => void): Promise; - map(map: Object): Promise; + map(callback: (currentValue: Object) => void): Promise; scanAll(value: boolean): Query; select(fields: Object | string[] | string): Query; then(onSuccess?: Function, onRejected?: Function): Promise; From a7a1f127ed5cf022cfa32d81182a5ea1a43bd0ae Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 18:20:38 +0800 Subject: [PATCH 0209/1618] fix: test error --- types/zui/index.d.ts | 43 ++++++++++-------------- types/zui/modal.d.ts | 23 ------------- types/zui/zui-tests.ts | 74 ++++++++++++++++++++---------------------- 3 files changed, 53 insertions(+), 87 deletions(-) delete mode 100644 types/zui/modal.d.ts diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index 13c2475bab..b8eda21164 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -3,33 +3,27 @@ // Definitions by: YuanXu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// +/// +/// +/// -/// -/// -/// - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// - -/*~ If this module is a UMD module that exposes a global variable 'myLib' when - *~ loaded outside a module loader environment, declare that global here. - *~ Otherwise, delete this declaration. - */ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// interface ZuiStatic { - //$.zui.messager + // $.zui.messager messager: Messager; Messager: MessagerStatic; @@ -37,5 +31,4 @@ interface ZuiStatic { } interface JQueryStatic { zui: ZuiStatic; - -} \ No newline at end of file +} diff --git a/types/zui/modal.d.ts b/types/zui/modal.d.ts deleted file mode 100644 index 7bc8b22da9..0000000000 --- a/types/zui/modal.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Type definitions for zui 1.7 -// Project: http://zui.sexy -// Definitions by: YuanXu -// Definitions: https://github.com/DefinitelyTyped/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 JQuery { - modal(options?: ModalOptions): JQuery; - modal(options?: ModalOptionsBackdropString): JQuery; - modal(command: string): JQuery; -} \ No newline at end of file diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index ea90bd89af..bb6bad33b4 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -1,12 +1,12 @@ -/// +/// new $.zui.Messager(); -new $.zui.Messager('提示消息:成功', { +new $.zui.Messager('提示消息:成功', { type: 'success' // 定义颜色主题 }).show(); -new $.zui.Messager("message") -let messagarOption: MessagerOption = {}; -new $.zui.Messager(messagarOption) +new $.zui.Messager("message"); +let messagarOption: MessagerOption = {}; +new $.zui.Messager(messagarOption); new $.zui.Messager("message", messagarOption); $.zui.messager.show("ok"); @@ -17,7 +17,7 @@ $.zui.store.set('date', { year: 2014, month: 8, day: 6 }); // 将一个对象存 console.log($.zui.store.get('name')); // 从本地存储获取'name'的值 console.log($.zui.store.get('date').year); // 从本地存储获取'date'值的year属性 -$.zui.store.forEach(function (key, value) { // 遍历所有本地存储的条目 +$.zui.store.forEach((key: string, value: any) => { // 遍历所有本地存储的条目 console.log(value); }); @@ -36,15 +36,13 @@ console.log($.zui.store.pageGet('date').year); // 从本地存储 $.zui.store.pageRemove('name'); // 从本地存储移除‘name’的值 $.zui.store.pageClear(); // 清空所有本地存储的条目 - /** * modal */ $('#myModal').modal({ keyboard: false, show: true -}) - +}); /** * modal trigger @@ -69,7 +67,6 @@ $('[data-toggle="tooltip"]').tooltip(); $('#element').tooltip('show'); $('#element').tooltip('show', '这是新的工具提示内容'); - /** * popover */ @@ -85,16 +82,16 @@ $('#myPopover').popover('show'); $('#myCollapseContent').collapse({ toggle: false }); -$().collapse('show') +$().collapse('show'); -$('#myCollapseContent').on('hidden.zui.collapse', function () { +$('#myCollapseContent').on('hidden.zui.collapse', () => { console.log('折叠内容已隐藏。'); -}) +}); /** * carousel */ -$('.carousel').carousel() +$('.carousel').carousel(); /** * datetime picker @@ -179,12 +176,12 @@ $('select.chosen-select').chosen({ * color */ // 创建颜色实例 -var myColor = new $.zui.Color('#095823'); +const myColor = new $.zui.Color('#095823'); // 调用实例方法 -var myHsl = myColor.toHsl(); +const myHsl = myColor.toHsl(); -var zuiPrimaryColor = $.zui.colorset.get('primary'); +const zuiPrimaryColor = $.zui.colorset.get('primary'); console.log('ZUI primary color is', zuiPrimaryColor.toCssStr()); /** @@ -193,15 +190,15 @@ console.log('ZUI primary color is', zuiPrimaryColor.toCssStr()); let count = 0; $('#draggableBtn').draggable({ container: '#draggableBox', - before: function () { + before: () => { console.log(count++ + ': ' + '[开始] 拖动...\n'); return true; }, - drag: function (e: DraggableEvent) { + drag: (e: DraggableEvent) => { console.log(count++ + ': ' + '拖动: pos = ' + JSON.stringify(e.pos) + ', offset = ' + JSON.stringify(e.offset) + '\n'); // console.log('(' + e.pos.left + ', ' + e.pos.top + ')'); }, - finish: function (e: DraggableEvent) { + finish: (e: DraggableEvent) => { console.log(count++ + ': ' + '[完毕]:pos = ' + JSON.stringify(e.pos) + ', offset = ' + JSON.stringify(e.offset) + '\n'); } }); @@ -212,20 +209,22 @@ $('#draggableBtn').draggable({ $('#multiDroppableContainer').droppable({ selector: '.btn-droppable', // 定义允许拖放的元素 target: '.droppable-target', - start: function () { + start: () => { $('#multiDroppableContainer .droppable-target').removeClass('panel-warning').removeClass('panel-success').find('.panel-heading').text('拖动到这里吗?'); }, - drop: function (event: DroppableEvent) { - var msg = '真棒!'; + drop: (event: DroppableEvent) => { + $('#multiDroppableContainer .droppable-target').removeClass('panel-success').removeClass('panel-warning'); if (event.target && event.element) { - var elementId = event.element.find('.btn-droppable-id').text(); + const elementId = event.element.find('.btn-droppable-id').text(); + let msg = '真棒!'; event.target.addClass('panel-success').find('.panel-heading').text('成功将【按钮#' + elementId + '】拖到目的地。'); msg += '成功拖动【按钮#' + elementId + '】到区域 ' + event.target.find('.area-name').text(); + + $.zui.messager.show(msg); } - $.zui.messager.show(msg); }, - drag: function (event: DroppableEvent) { + drag: (event: DroppableEvent) => { $('#multiDroppableContainer .droppable-target').removeClass('panel-success').removeClass('panel-warning'); if (event.target) event.target.addClass('panel-warning'); } @@ -235,17 +234,16 @@ $('#multiDroppableContainer').droppable({ * sortable */ // 定义选项对象 -var options = { +const options = { selector: '.sortable-item', - finish: function (e: SortEvent) { + finish: (e: SortEvent) => { console.log('排序完成:', e); }, // 设置更多选项... }; // 初始化时传入选项参数 -$('#sortableList').sortable(options) - +$('#sortableList').sortable(options); /** * selectable @@ -256,7 +254,7 @@ $('#selectable').selectable({ rangeStyle: { border: '1px solid red' // 拖选范围指示矩形边框设置为红色 }, - finish: function (data: SelectableEvent) { // 选择结束时的回调函数 + finish: (data: SelectableEvent) => { // 选择结束时的回调函数 // 所有元素的选中或非选中状态 console.log(data.selections); @@ -270,18 +268,18 @@ $('#selectable').selectable({ */ // 获取 imgCutter 实例 -var myImgCutter = $('#imgCutter').data('zui.imgCutter'); +const myImgCutter = $('#imgCutter').data('zui.imgCutter'); // 调用 resetImg 方法 myImgCutter.resetImage('http://zui.sexy/docs/img/img1.jpg'); // 调用 getData 方法 -var myImgCutterData = myImgCutter.getData(); +const myImgCutterData = myImgCutter.getData(); /** * treemenu */ -var myTreeData = [{ +const myTreeData = [{ title: '水果', url: 'http://zui.sexy', open: true, @@ -307,7 +305,6 @@ var myTreeData = [{ $('#myTree').tree({ data: myTreeData }); - /** * datatable */ @@ -326,14 +323,13 @@ $('table.datatable').datatable('load', { ] }); - /** * uplaoder */ $('#myUploader').uploader({ url: '...', // ..., - onUploadFile: function(file:FileObj) { - console.log('上传成功', file); + onUploadFile: (file: FileObj) => { + console.log('上传成功', file); } -}); \ No newline at end of file +}); From f73e0acaa6f4f6c5e735363040893d0dd93b0ef2 Mon Sep 17 00:00:00 2001 From: stonio Date: Fri, 7 Jul 2017 12:39:22 +0200 Subject: [PATCH 0210/1618] Update index.d.ts to set fn non-readonly --- types/jquery/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index b71bfbbed3..254a2676ed 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -2422,7 +2422,7 @@ interface JQueryStatic { * @since 1.4.3 */ cssNumber: JQuery.PlainObject; - readonly fn: JQuery; + fn: JQuery; fx: { /** * The rate (in milliseconds) at which animations fire. From 14602bb57b916d247ee21ae1b94b8d1d89eb270c Mon Sep 17 00:00:00 2001 From: Kamil Ejsymont Date: Fri, 7 Jul 2017 12:50:27 +0200 Subject: [PATCH 0211/1618] Return promise with 'any' type --- types/jsforce/query.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jsforce/query.d.ts b/types/jsforce/query.d.ts index 90e5734253..42d258a48d 100644 --- a/types/jsforce/query.d.ts +++ b/types/jsforce/query.d.ts @@ -24,7 +24,7 @@ export class Query { delete(callback?: (err: Error, ret: RecordResult) => void): any; destroy(callback?: (err: Error, ret: RecordResult) => void): Promise; explain(callback?: (err: Error, info: ExplainInfo) => void): Promise; - map(callback: (currentValue: Object) => void): Promise; + map(callback: (currentValue: Object) => void): Promise; scanAll(value: boolean): Query; select(fields: Object | string[] | string): Query; then(onSuccess?: Function, onRejected?: Function): Promise; From fdf409b0aed43d5850e01fbbfa0c8914958ce164 Mon Sep 17 00:00:00 2001 From: sqwk Date: Fri, 7 Jul 2017 12:53:00 +0200 Subject: [PATCH 0212/1618] fix: Make Match Optional --- types/paper/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index f7c93d4797..5718c0af16 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1382,7 +1382,7 @@ declare module 'paper' { * @param options.guides - hit-test items that have Item#guide set to true. * @param options.selected - only hit selected items. */ - hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; match: (hit: HitResult) => boolean; }): HitResult; + hitTest(point: Point, options?: { tolerance?: number; class?: string; fill?: boolean; stroke?: boolean; segments?: boolean; curves?: boolean; handles?: boolean; ends?: boolean; bounds?: boolean; center?: boolean; guides?: boolean; selected?: boolean; match?: (hit: HitResult) => boolean; }): HitResult; /** * Checks whether the item matches the criteria described by the given object, by iterating over all of its properties and matching against their values through matches(name, compare). From e9ecb63b333c8154d839b956378db8a4d37d916f Mon Sep 17 00:00:00 2001 From: Miloslav Nenadal Date: Fri, 7 Jul 2017 14:42:36 +0200 Subject: [PATCH 0213/1618] [ramda]: Improve map definition --- types/ramda/index.d.ts | 2 ++ types/ramda/ramda-tests.ts | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index e30c95f8be..1697ff4341 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -919,6 +919,8 @@ declare namespace R { map(fn: (x: T) => U, list: T[]): U[]; map(fn: (x: T) => U, obj: Functor): Functor; // used in functors map(fn: (x: T) => U): (list: T[]) => U[]; + map(fn: (x: T[keyof T]) => U[keyof T], obj: T): U; + map(fn: (x: T[keyof T]) => U[keyof T]): (obj: T) => U; /** * The mapAccum function behaves like a combination of map and reduce. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 18a5ed4e7d..908c88828a 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -753,6 +753,24 @@ interface Obj { R.map((x: number) => x - 1, numberFunctor); // => "Hello World" }; +() => { + interface A { + a: number; + b: number; + } + + interface B { + a: string; + b: string; + } + + R.map(R.inc, {a: 1, b: 2}); + R.map(R.toString, {a: 1, b: 2}); + + R.map(R.inc)({a: 1, b: 2}); + R.map(R.toString)({a: 1, b: 2}); +}; + () => { let digits = ["1", "2", "3", "4"]; From a8d217f43080bb643903aa8227150b366b383b85 Mon Sep 17 00:00:00 2001 From: Kevin Somers-Higgins Date: Fri, 7 Jul 2017 08:43:35 -0500 Subject: [PATCH 0214/1618] Add tus-js-client type definition --- types/tus-js-client/index.d.ts | 32 +++++++++++++++++++ types/tus-js-client/tsconfig.json | 23 ++++++++++++++ types/tus-js-client/tslint.json | 1 + types/tus-js-client/tus-js-client-tests.ts | 37 ++++++++++++++++++++++ 4 files changed, 93 insertions(+) create mode 100644 types/tus-js-client/index.d.ts create mode 100644 types/tus-js-client/tsconfig.json create mode 100644 types/tus-js-client/tslint.json create mode 100644 types/tus-js-client/tus-js-client-tests.ts diff --git a/types/tus-js-client/index.d.ts b/types/tus-js-client/index.d.ts new file mode 100644 index 0000000000..d5cc75b682 --- /dev/null +++ b/types/tus-js-client/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for tus-js-client 1.4 +// Project: https://github.com/tus/tus-js-client/ +// Definitions by: Kevin Somers-Higgins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface UploadOptions { + endpoint: string; + fingerprint?: string; + resume?: boolean; + onProgress?: ((bytesSent: number, bytesTotal: number) => void) | null; + onChunkComplete?: ((chunkSize: number, bytesAccepted: number, bytesTotal: number) => void) | null; + onSuccess?: (() => void) | null; + onError?: ((error: Error) => void) | null; + headers?: { [key: string]: string }; + chunkSize?: number; + withCredentials?: boolean; + uploadUrl?: string | null; + uploadSize?: number | null; + overridePatchMethod?: boolean; + retryDelays?: number[]; +} + +export class Upload { + constructor(file: File | Blob, options: UploadOptions); + + file: File | Blob; + options: UploadOptions; + url: string | null; + + start(): void; + abort(): void; +} diff --git a/types/tus-js-client/tsconfig.json b/types/tus-js-client/tsconfig.json new file mode 100644 index 0000000000..fdb3cf2814 --- /dev/null +++ b/types/tus-js-client/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "tus-js-client-tests.ts" + ] +} diff --git a/types/tus-js-client/tslint.json b/types/tus-js-client/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tus-js-client/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/tus-js-client/tus-js-client-tests.ts b/types/tus-js-client/tus-js-client-tests.ts new file mode 100644 index 0000000000..adf846b577 --- /dev/null +++ b/types/tus-js-client/tus-js-client-tests.ts @@ -0,0 +1,37 @@ +import * as Tus from 'tus-js-client'; + +let file = new File(["foo"], "foo.txt", { + type: "text/plain", +}); + +let upload = new Tus.Upload(file, { + endpoint: "", + fingerprint: "fingerprint", + resume: true, + onProgress: (bytesSent: number, bytesTotal: number) => { + let percentage = (bytesSent / bytesTotal * 100).toFixed(2); + console.log(bytesSent, bytesTotal, percentage + "%"); + }, + onChunkComplete: (chunkSize: number, bytesAccepted: number) => {}, + onSuccess: () => { + console.log("Download from %s complete", upload.url); + }, + onError: (error: Error) => { + console.log("Failed because: " + error); + }, + headers: {TestHeader: 'TestValue'}, + chunkSize: 100, + withCredentials: true, + uploadUrl: "", + uploadSize: 50, + overridePatchMethod: true, + retryDelays: [10, 20, 50] +}); + +upload.start(); + +upload.abort(); + +let upload2 = new Tus.Upload(file, { + endpoint: "" +}); From ad6ceb5ab30fba5297c9b449beea174ebf27e1a7 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 21:48:59 +0800 Subject: [PATCH 0215/1618] fix test error --- types/zui/tsconfig.json | 3 ++- types/zui/zui-tests.ts | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/zui/tsconfig.json b/types/zui/tsconfig.json index 06fa3ab094..88b3a06bc4 100644 --- a/types/zui/tsconfig.json +++ b/types/zui/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/zui/zui-tests.ts b/types/zui/zui-tests.ts index bb6bad33b4..3d5bc14038 100644 --- a/types/zui/zui-tests.ts +++ b/types/zui/zui-tests.ts @@ -213,7 +213,6 @@ $('#multiDroppableContainer').droppable({ $('#multiDroppableContainer .droppable-target').removeClass('panel-warning').removeClass('panel-success').find('.panel-heading').text('拖动到这里吗?'); }, drop: (event: DroppableEvent) => { - $('#multiDroppableContainer .droppable-target').removeClass('panel-success').removeClass('panel-warning'); if (event.target && event.element) { const elementId = event.element.find('.btn-droppable-id').text(); From 4282bb4c964ea4b4caea850b64f90eb522c954e3 Mon Sep 17 00:00:00 2001 From: Nick Graham Date: Fri, 7 Jul 2017 08:56:18 -0500 Subject: [PATCH 0216/1618] Adds any as MediaQuery state interface Fixes TypeScript issues --- types/react-responsive/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-responsive/index.d.ts b/types/react-responsive/index.d.ts index 3b6e456c73..2b9a37839f 100644 --- a/types/react-responsive/index.d.ts +++ b/types/react-responsive/index.d.ts @@ -59,7 +59,7 @@ declare module "react-responsive" { } } - class MediaQuery extends React.Component { } + class MediaQuery extends React.Component { } export = MediaQuery; } From 5472ca9e0e78de7b40fb4f647bf69e1936b9de40 Mon Sep 17 00:00:00 2001 From: YuanXu Date: Fri, 7 Jul 2017 22:30:06 +0800 Subject: [PATCH 0217/1618] fix compile error --- types/zui/index.d.ts | 3 ++- types/zui/tsconfig.json | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/types/zui/index.d.ts b/types/zui/index.d.ts index b8eda21164..c1090625b6 100644 --- a/types/zui/index.d.ts +++ b/types/zui/index.d.ts @@ -2,8 +2,9 @@ // Project: http://zui.sexy // Definitions by: YuanXu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -/// +/// /// /// diff --git a/types/zui/tsconfig.json b/types/zui/tsconfig.json index 88b3a06bc4..36f8848110 100644 --- a/types/zui/tsconfig.json +++ b/types/zui/tsconfig.json @@ -5,6 +5,7 @@ "es6", "dom" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, From 43f5f4a024d4ee94b8692f60d34643697f515a87 Mon Sep 17 00:00:00 2001 From: Christian Rackerseder Date: Fri, 7 Jul 2017 16:38:07 +0200 Subject: [PATCH 0218/1618] Added property to react-dates --- types/react-dates/index.d.ts | 3 ++- types/react-dates/react-dates-tests.tsx | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index d290c84995..c3559f5278 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-dates v12.1.0 +// Type definitions for react-dates v12.1.1 // Project: https://github.com/airbnb/react-dates // Definitions by: Artur Ampilogov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -226,6 +226,7 @@ declare namespace ReactDates { // navigation related props navPrev?: string | JSX.Element, navNext?: string | JSX.Element, + hideKeyboardShortcutsPanel?: boolean; onPrevMonthClick?: (e: React.EventHandler>) => void, onNextMonthClick?: (e: React.EventHandler>) => void, diff --git a/types/react-dates/react-dates-tests.tsx b/types/react-dates/react-dates-tests.tsx index d8d6691b45..c775480a2f 100644 --- a/types/react-dates/react-dates-tests.tsx +++ b/types/react-dates/react-dates-tests.tsx @@ -47,6 +47,7 @@ class SingleDatePickerFullTest extends React.Component { keepOpenOnDateSelect={true} navNext="next" navPrev="prev" + hideKeyboardShortcutsPanel={true} withPortal={false} onDateChange={d => {}} focused={false} From 2f2608a9adda429e8f413484d5d8bf498303ce5a Mon Sep 17 00:00:00 2001 From: CarbonAtom Date: Fri, 7 Jul 2017 11:04:47 -0400 Subject: [PATCH 0219/1618] [perfect-scrollbar] Updated to v0.7.1. Added global var and vanilla events. Improved jsdoc. --- types/perfect-scrollbar/index.d.ts | 137 +++++++++++++----- .../perfect-scrollbar-tests.ts | 2 + 2 files changed, 105 insertions(+), 34 deletions(-) diff --git a/types/perfect-scrollbar/index.d.ts b/types/perfect-scrollbar/index.d.ts index 74852a513c..bceaf35faa 100644 --- a/types/perfect-scrollbar/index.d.ts +++ b/types/perfect-scrollbar/index.d.ts @@ -1,21 +1,66 @@ -// Type definitions for perfect-scrollbar v0.6.12 +// Type definitions for perfect-scrollbar v0.7.1 // Project: https://github.com/noraesae/perfect-scrollbar // Definitions by: Kombu +// Cyrus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// +interface HTMLElementEventMap { + /** + * This event fires when the y-axis is scrolled in either direction. + */ + 'ps-scroll-y': CustomEvent, + /** + * This event fires when the x-axis is scrolled in either direction. + */ + 'ps-scroll-x': CustomEvent, + /** + * This event fires when scrolling upwards. + */ + 'ps-scroll-up': CustomEvent, + /** + * This event fires when scrolling downwards. + */ + 'ps-scroll-down': CustomEvent, + /** + * This event fires when scrolling to the left. + */ + 'ps-scroll-left': CustomEvent, + /** + * This event fires when scrolling to the right. + */ + 'ps-scroll-right': CustomEvent, + /** + * This event fires when scrolling reaches the start of the y-axis. + */ + 'ps-y-reach-start': CustomEvent, + /** + * This event fires when scrolling reaches the end of the y-axis (useful for infinite scroll). + */ + 'ps-y-reach-end': CustomEvent, + /** + * This event fires when scrolling reaches the start of the x-axis. + */ + 'ps-x-reach-start': CustomEvent, + /** + * This event fires when scrolling reaches the end of the x-axis. + */ + 'ps-x-reach-end': CustomEvent +} + /** - * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/default-setting.js#L3 - * https://github.com/noraesae/perfect-scrollbar#optional-parameters + * @see https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/default-setting.js#L3 + * @see https://github.com/noraesae/perfect-scrollbar#optional-parameters */ interface PerfectScrollbarSettings { /** * It is a list of handlers to use to scroll the element. - * https://github.com/noraesae/perfect-scrollbar#handlers - * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/initialize.js#L9 + * @see https://github.com/noraesae/perfect-scrollbar#handlers + * @see https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/initialize.js#L9 + * @default ['click-rail', 'drag-scrollbar', keyboard', 'wheel', 'touch'] */ handlers?: ('click-rail' | 'drag-scrollbar' | @@ -26,69 +71,87 @@ interface PerfectScrollbarSettings { /** * When set to an integer value, the thumb part of the scrollbar will not expand over that number of pixels. - * https://github.com/noraesae/perfect-scrollbar#maxscrollbarlength + * @see https://github.com/noraesae/perfect-scrollbar#maxscrollbarlength + * @default null */ maxScrollbarLength?: number; /** * When set to an integer value, the thumb part of the scrollbar will not shrink below that number of pixels. - * https://github.com/noraesae/perfect-scrollbar#minscrollbarlength + * @see https://github.com/noraesae/perfect-scrollbar#minscrollbarlength + * @default null */ minScrollbarLength?: number; /** * The number of pixels the content width can surpass the container width without enabling the X axis scroll bar. * Allows some "wiggle room" or "offset break", so that X axis scroll bar is not enabled just because of a few pixels. - * https://github.com/noraesae/perfect-scrollbar#scrollxmarginoffset + * @see https://github.com/noraesae/perfect-scrollbar#scrollxmarginoffset + * @default 0 */ scrollXMarginOffset?: number; /** * The number of pixels the content height can surpass the container height without enabling the Y axis scroll bar. * Allows some "wiggle room" or "offset break", so that Y axis scroll bar is not enabled just because of a few pixels. - * https://github.com/noraesae/perfect-scrollbar#scrollymarginoffset + * @see https://github.com/noraesae/perfect-scrollbar#scrollymarginoffset + * @default 0 */ scrollYMarginOffset?: number; /** - * When set to false, when clicking on a rail, the click event will be allowed to propagate. - * https://github.com/noraesae/perfect-scrollbar#stoppropagationonclick + * @deprecated + * @description When set to false, when clicking on a rail, the click event will be allowed to propagate. + * @see https://github.com/noraesae/perfect-scrollbar#stoppropagationonclick */ stopPropagationOnClick?: boolean; /** * When set to true, the scroll bar in X axis will not be available, regardless of the content width. - * https://github.com/noraesae/perfect-scrollbar#suppressscrollx + * @see https://github.com/noraesae/perfect-scrollbar#suppressscrollx + * @default false */ suppressScrollX?: boolean; /** * When set to true, the scroll bar in Y axis will not be available, regardless of the content height. - * https://github.com/noraesae/perfect-scrollbar#suppressscrolly + * @see https://github.com/noraesae/perfect-scrollbar#suppressscrolly + * @default false */ suppressScrollY?: boolean; /** * If this option is true, when the scroll reaches the end of the side, touch scrolling will be propagated to parent element. - * https://github.com/noraesae/perfect-scrollbar#swipepropagation + * @see https://github.com/noraesae/perfect-scrollbar#swipepropagation + * @default true */ swipePropagation?: boolean; + /** + * If this option is true, swipe scrolling will be eased. + * @see https://github.com/noraesae/perfect-scrollbar#swipeeasing + * @default true + */ + swipeEasing?:boolean; + /** * When set to true, and only one (vertical or horizontal) scrollbar is visible then both vertical and horizontal scrolling will affect the scrollbar. - * https://github.com/noraesae/perfect-scrollbar#usebothwheelaxes + * @see https://github.com/noraesae/perfect-scrollbar#usebothwheelaxes + * @default false */ useBothWheelAxes?: boolean; /** * If this option is true, when the scroll reaches the end of the side, mousewheel event will be propagated to parent element. - * https://github.com/noraesae/perfect-scrollbar#wheelpropagation + * @see https://github.com/noraesae/perfect-scrollbar#wheelpropagation + * @default false */ wheelPropagation?: boolean; /** * The scroll speed applied to mousewheel event. - * https://github.com/noraesae/perfect-scrollbar#wheelspeed + * @see https://github.com/noraesae/perfect-scrollbar#wheelspeed + * @default 1 */ wheelSpeed?: number; @@ -98,33 +161,39 @@ interface PerfectScrollbarSettings { * The class name is prepended with `ps-theme-`. * So default theme class name is `ps-theme-default`. * In order to create custom themes with scss use `ps-container($theme)` mixin, where `$theme` is a scss map. - * https://github.com/noraesae/perfect-scrollbar#theme + * @see https://github.com/noraesae/perfect-scrollbar#theme + * @default 'default' */ theme?: string; } +interface PerfectScrollbar { + /** + * @see https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/initialize.js#L19 + */ + initialize(element: HTMLElement, settings?: PerfectScrollbarSettings): void; + + /** + * @see https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/update.js#L9 + */ + update(element: HTMLElement): void; + + /** + * @see https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/destroy.js#L7 + */ + destroy(element: HTMLElement): void; +} + +declare const Ps: PerfectScrollbar; + declare module 'perfect-scrollbar' { - - /** - * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/initialize.js#L19 - */ - export function initialize(element: HTMLElement, settings?: PerfectScrollbarSettings): void; - - /** - * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/update.js#L9 - */ - export function update(element: HTMLElement): void; - - /** - * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/destroy.js#L7 - */ - export function destroy(element: HTMLElement): void; + export = Ps; } interface JQuery { /** - * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/adaptor/jquery.js#L6 + * @see https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/adaptor/jquery.js#L6 */ perfectScrollbar(settingOrCommand?: PerfectScrollbarSettings | 'update' | 'destroy'): JQuery; } diff --git a/types/perfect-scrollbar/perfect-scrollbar-tests.ts b/types/perfect-scrollbar/perfect-scrollbar-tests.ts index 6bd9854658..4ba80d1294 100644 --- a/types/perfect-scrollbar/perfect-scrollbar-tests.ts +++ b/types/perfect-scrollbar/perfect-scrollbar-tests.ts @@ -36,3 +36,5 @@ $('#container').perfectScrollbar() // Initialize $('#container').perfectScrollbar({ /*...*/ }) // with options $('#container').perfectScrollbar('update') // Update $('#container').perfectScrollbar('destroy') // Destroy + +container.addEventListener('ps-x-reach-start', () => { }); From 35156d5f5d0c69e64bde05d6aba4fece827de0a7 Mon Sep 17 00:00:00 2001 From: Peter Keuter Date: Fri, 7 Jul 2017 17:07:08 +0200 Subject: [PATCH 0220/1618] update pool configuration options --- types/mssql/index.d.ts | 17 +++++++++++++---- types/mssql/mssql-tests.ts | 3 +++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 63cbd69dc6..06da51a99f 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -148,11 +148,20 @@ export interface IOptions { trustedConnection?: boolean; } - export interface IPool { - min: number; - max: number; - idleTimeoutMillis: number; + min?: number; + max?: number; + idleTimeoutMillis?: number; + maxWaitingClients?: number; + testOnBorrow?: boolean; + acquireTimeoutMillis?: number; + fifo?: boolean; + priorityRange?: number; + autostart?: boolean; + evictionRunIntervalMillis?: number; + numTestsPerRun?: number; + softIdleTimeoutMillis?: number; + Promise?: any; } export declare var pool: IPool; diff --git a/types/mssql/mssql-tests.ts b/types/mssql/mssql-tests.ts index 9922364dc1..9d9e72bd4f 100644 --- a/types/mssql/mssql-tests.ts +++ b/types/mssql/mssql-tests.ts @@ -12,6 +12,9 @@ var config: sql.config = { connectionTimeout: 10000, options: { encrypt: true + }, + pool: { + autostart: true } } From ce68df0750961540a30f25ba1eca2b532b6dee66 Mon Sep 17 00:00:00 2001 From: Peter Keuter Date: Fri, 7 Jul 2017 17:09:56 +0200 Subject: [PATCH 0221/1618] update version number --- types/mssql/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 06da51a99f..1200bacfd0 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for mssql 4.0.2 +// Type definitions for mssql 4.0.4 // Project: https://www.npmjs.com/package/mssql // Definitions by: COLSA Corporation , Ben Farr , Vitor Buzinaro , Matt Richardson , Jørgen Elgaard Larsen , Peter Keuter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 51a4747a28d6518ca5f6d92d3547e1d77a5354e6 Mon Sep 17 00:00:00 2001 From: Jan Karres Date: Fri, 7 Jul 2017 17:17:52 +0200 Subject: [PATCH 0222/1618] Update react-tag-input for v4.7.2 --- types/react-tag-input/index.d.ts | 29 +++++++++++++++---- .../react-tag-input/react-tag-input-tests.tsx | 26 +++++++++++++++-- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/types/react-tag-input/index.d.ts b/types/react-tag-input/index.d.ts index 626b44acac..415a2ef2aa 100644 --- a/types/react-tag-input/index.d.ts +++ b/types/react-tag-input/index.d.ts @@ -1,18 +1,35 @@ -// Type definitions for React-Tags (react-tag-input) 4.7 +// Type definitions for React-Tags (react-tag-input) 4.7.2 // Project: https://github.com/prakhar1989/react-tags -// Definitions by: Ogglas +// Definitions by: Ogglas , Jan Karres // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as React from "react"; export interface ReactTagsProps { - tags?: Array<{id: number, text: string }>; + tags?: Array<{ id: number, text: string }>; suggestions?: string[]; - handleDelete: ((i: number) => void); - handleAddition: ((tag: string) => void); - handleDrag?: ((tag: { id: number; text: string; }, currPos: number, newPos: number) => void); + delimiters?: number[]; placeholder?: string; + labelField?: string; + + handleAddition: (tag: string) => void; + handleDelete: (i: number) => void; + handleDrag?: (tag: { id: number; text: string; }, currPos: number, newPos: number) => void; + handleInputChange?: (value: string) => void; + handleFilterSuggestions?: (textInputValue: string, possibleSuggestionsArray: string[]) => boolean; + handleInputBlur?: () => void; + + autofocus?: boolean; + allowDeleteFromEmptyInput?: boolean; + minQueryLength?: number; + removeComponent?: React.Component; + autocomplete?: boolean | 1; + readOnly?: boolean; + maxLength?: number; + + name?: string; + id?: string; } export class WithContext extends React.Component { } diff --git a/types/react-tag-input/react-tag-input-tests.tsx b/types/react-tag-input/react-tag-input-tests.tsx index a78bced3b9..42a9f6df97 100644 --- a/types/react-tag-input/react-tag-input-tests.tsx +++ b/types/react-tag-input/react-tag-input-tests.tsx @@ -7,10 +7,30 @@ let tags = Array({ id: 0, text: "test" }, { id: 1, text: "testing" }); let suggestions = Array("test1", "test2"); ReactDOM.render( - console.log("Delete: " + i)} + delimiters={[13, 8, 188]} // Enter, Tab and Comma + placeholder="Some placeholder text" + labelField="Some label" + handleAddition={(tag: string) => console.log("Add: " + tag)} - handleDrag={(tag: { id: number; text: string; }, currPos: number, newPos: number) => console.log("Drag: " + tag.text)} />, + handleDelete={(i: number) => console.log("Delete: " + i)} + handleDrag={(tag: { id: number; text: string; }, currPos: number, newPos: number) => console.log("Drag: " + tag.text)} + handleInputChange={(value) => console.log("Changed to: ", value)} + handleFilterSuggestions={(textInputValue, possibleSuggestionsArray) => true} + handleInputBlur={() => console.log("Blured")} + + autofocus={false} + allowDeleteFromEmptyInput={false} + minQueryLength={0} + removeComponent={null} + autocomplete={true} + readOnly={false} + maxLength={64} + + name="react-tags-field" + id="react-tags-field" + />, document.getElementById("app") ); From 7da62dff71f72f5a2171b6722c3bdc2daca1a49b Mon Sep 17 00:00:00 2001 From: Andrey Volynkin Date: Fri, 7 Jul 2017 18:21:40 +0300 Subject: [PATCH 0223/1618] Fix mailparser to 2 API MailParser was completely rewrote and last fix was incomplete. --- types/mailparser/index.d.ts | 343 ++++++++++++++++++++++----- types/mailparser/mailparser-tests.ts | 88 +++---- 2 files changed, 313 insertions(+), 118 deletions(-) diff --git a/types/mailparser/index.d.ts b/types/mailparser/index.d.ts index 0bb84e9940..cf493139b4 100644 --- a/types/mailparser/index.d.ts +++ b/types/mailparser/index.d.ts @@ -1,88 +1,305 @@ // Type definitions for mailparser v2.0.0 // Project: https://www.npmjs.com/package/mailparser // Definitions by: Peter Snider +// Andrey Volynkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import StreamModule = require("stream"); +import StreamModule = require('stream'); import Stream = StreamModule.Stream; -import WritableStream = NodeJS.WritableStream; -import EventEmitter = NodeJS.EventEmitter; -interface Options { - debug?: boolean; // if set to true print all incoming lines to console - streamAttachments?: boolean; // if set to true, stream attachments instead of including them - unescapeSMTP?: boolean; // if set to true replace double dots in the beginning of the file - defaultCharset?: string; // the default charset for text/plain and text/html content, if not set reverts to Latin-1 - showAttachmentLinks?: boolean; // if set to true, show inlined attachment links filename +/** + * Structured object for headers with arguments. + * + * `content-type: text/plain; CHARSET="UTF-8"` => + * ``` + * { + * "value": "text/plain", + * "params": { + * "charset": "UTF-8" + * } + * } + * ``` + */ +interface StructuredHeader { + /** + * The main value. + */ + value: string; + /** + * Additional arguments. + */ + params: {[key: string]: string}; } +/** + * Possible types of a header value. + */ +export type HeaderValue = string | string[] | AddressObject | Date | StructuredHeader; +/** + * A Map object with lowercase header keys. + */ +export type Headers = Map; + +/** + * Address details. + */ interface EmailAddress { - address: string; - name: string; + /** + * The email address. + */ + address: string; + /** + * The name part of the email/group. + */ + name: string; + /** + * An array of grouped addresses. + */ + group?: EmailAddress[]; } - -interface Attachment { - contentType: string; - fileName: string; - contentDisposition: string; // e.g. 'attachment' - contentId: string; // e.g. '5.1321281380971@localhost' - transferEncoding: string; // e.g. 'base64' - length: number; // length of the attachment in bytes - generatedFileName: string; // e.g. 'image.png' - checksum: string; // the md5 hash of the file, e.g. 'e4cef4c6e26037bcf8166905207ea09b' - content: Buffer; // possibly a SlowBuffer - stream: Stream; // a stream to read the attachment if streamAttachments is set to true +/** + * Address object. + */ +interface AddressObject { + /** + * An array with address details. + */ + value: EmailAddress[]; + /** + * A formatted address string for HTML context. + */ + html: string; + /** + * A formatted address string for plaintext context. + */ + text: string; } -// emitted with the 'end' event +/** + * COmmon part of the Attachment object. + */ +interface AttachmentCommon { + /** + * Message type. + */ + type: 'attachment'; + /** + * Attachment contents. + */ + content: any; + /** + * MIME type of the message. + */ + contentType: string; + /** + * Content disposition type for the attachment, + * most probably `'attachment'`. + */ + contentDisposition: string; + /** + * File name of the attachment. + */ + filename?: string; + /** + * A Map value that holds MIME headers for the attachment node. + */ + headers: Headers; + /** + * A MD5 hash of the message content. + */ + checksum: string; + /** + * Message size in bytes. + */ + size: number; + /** + * The header value from `Content-ID`. + */ + contentId?: string; + /** + * `contentId` without `<` and `>`. + */ + cid?: string; // e.g. '5.1321281380971@localhost' + /** + * If true then this attachment should not be offered for download + * (at least not in the main attachments list). + */ + related?: boolean; +} + +/** + * Attachment object. + */ +interface Attachment extends AttachmentCommon { + /** + * A Buffer that contains the attachment contents. + */ + content: Buffer; + /** + * If true then this attachment should not be offered for download + * (at least not in the main attachments list). + */ + related: boolean; +} + +/** + * MailParser Attachment object. + */ +interface AttachmentStream extends AttachmentCommon { + /** + * A Buffer that contains the attachment contents. + */ + content: Stream; + /** + * Method must be called once you have processed the attachment. + */ + release(): void; +} + +/** + * Parsed mail object. + */ interface ParsedMail { - headers: any; // unprocessed headers in the form of - {key: value} - if there were multiple fields with the same key then the value is an array - from: EmailAddress[]; // should be only one though) - to: EmailAddress[]; - cc?: EmailAddress[]; - bcc?: EmailAddress[]; - subject: string; // the subject line - references?: string[]; // an array of reference message id values (not set if no reference values present) - inReplyTo?: string[]; // an array of In-Reply-To message id values (not set if no in-reply-to values present) - priority?: string; // priority of the e-mail, always one of the following: normal (default), high, low - text: string; // text body - html: string; // html body - date?: Date; // If date could not be resolved or is not found this field is not set. Check the original date string from headers.date - attachments?: Attachment[]; + /** + * An array of attachments. + */ + attachments?: Attachment[]; + /** + * A Map object with lowercase header keys. + * + * - All address headers are converted into address objects. + * - `references` is a string if only a single reference-id exists or an + * array if multiple ids exist. + * - `date` value is a Date object. + */ + headers: Headers; + /** + * The HTML body of the message. + * + * Sets to `false` when there is no HTML body. + * + * If the message included embedded images as cid: urls then these are all + * replaced with base64 formatted data: URIs. + */ + html: string | boolean; + /** + * The plaintext body of the message. + */ + text: string; + /** + * The plaintext body of the message formatted as HTML. + */ + textAsHtml: string; + /** + * The subject line. + */ + subject: string; + /** + * An array of referenced Message-ID values. + * + * Not set if no reference values present. + */ + references?: string[]; + /** + * A Date object for the `Date:` header. + */ + date?: Date; + /** + * An address object for the `To:` header. + */ + to: AddressObject; + /** + * An address object for the `From:` header. + */ + from: AddressObject; + /** + * An address object for the `Cc:` header. + */ + cc?: AddressObject; + /** + * An address object for the `Bcc:` header (usually not present). + */ + bcc?: AddressObject; + /** + * An address object for the `Reply-To:` header. + */ + replyTo?: AddressObject; + /** + * The Message-ID value string. + */ + messageId?: string; + /** + * The In-Reply-To value string. + */ + inReplyTo?: string; + /** + * Priority of the e-mail. + */ + priority?: 'normal' | 'low' | 'high'; } -export class MailParser extends StreamModule.Writable { - constructor(options?: Options); - on(event: string, callback: (any: any) => void): this; - - // from WritableStream - writable: boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - - // from EventEmitter - static listenerCount(emitter: EventEmitter, event: string): number; - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; +/** + * Text message content. + */ +interface MessageText { + /** + * Message type. + */ + type: 'text'; + /** + * Includes the HTML version of the message. + * + * Is set if the message has at least one `text/html` node. + */ + html?: string | boolean; + /** + * Includes the plaintext version of the message. + * + * Is set if the message has at least one `text/plain` node. + */ + text?: string; + /** + * Includes the plaintext version of the message in HTML format. + * + * Is set if the message has at least one `text/plain` node. + */ + textAsHtml?: string; } +/** + * A lower-level email parsing class. + * + * It is a transform stream that takes email source as bytestream for the input + * and emits data objects for attachments and text contents. + */ +export class MailParser extends StreamModule.Transform { + constructor(options?: StreamModule.TransformOptions); + on(event: string, callback: (any: any) => void): this; + on(event: 'headers', callback: (headers: Headers) => void): this; + on(event: 'data', callback: (data: AttachmentStream | MessageText) => void): this; + on(event: 'readable', callback: (data: AttachmentStream | MessageText) => void): this; +} + +/** + * A message source. + */ export type Source = Buffer | Stream | string; + +/** + * Parse email message to structure object. + * + * @param source A message source. + * @param callback Function to get a structured email object. + */ export function simpleParser(source: Source, callback: (err: any, mail: ParsedMail) => void): void; + +/** + * Parse email message to structure object. + * + * @param source A message source. + */ export function simpleParser(source: Source): Promise; diff --git a/types/mailparser/mailparser-tests.ts b/types/mailparser/mailparser-tests.ts index 30a6e7bf5c..142a2c8b0f 100644 --- a/types/mailparser/mailparser-tests.ts +++ b/types/mailparser/mailparser-tests.ts @@ -1,73 +1,38 @@ -import mailparser_mod = require("mailparser"); +// tslint:disable +import mailparser_mod = require('mailparser'); import MailParser = mailparser_mod.MailParser; -import ParsedMail = mailparser_mod.ParsedMail; -import Attachment = mailparser_mod.Attachment; import simpleParser = mailparser_mod.simpleParser; var mailparser = new MailParser(); - -mailparser.on("headers", function(headers){ - console.log(headers.received); +mailparser.on('headers', function(headers){ + console.log('Subject:', headers.get('subject')); }); -mailparser.on("end", function(mail){ - mail; // object structure for parsed e-mail +// Attachments +mailparser.on('data', data => { + if (data.type === 'attachment'){ + console.log(data.filename); + data.content.pipe(process.stdout); + data.content.on('end', () => data.release()); + } }); - -// Decode a simple e-mail -// This example decodes an e-mail from a string - -var email = "From: 'Sender Name' \r\n"+ - "To: 'Receiver Name' \r\n"+ - "Subject: Hello world!\r\n"+ - "\r\n"+ - "How are you today?"; - // setup an event listener when the parsing finishes -mailparser.on("end", function(mail_object){ - console.log("From:", mail_object.from); //[{address:'sender@example.com',name:'Sender Name'}] - console.log("Subject:", mail_object.subject); // Hello world! - console.log("Text body:", mail_object.text); // How are you today? +mailparser.on('data', data => { + if (data.type === 'text'){ + console.log(data.html); + } }); - // send the email source to the parser -mailparser.write(email); -mailparser.end(); - // Pipe file to MailParser // This example pipes a readableStream file to MailParser -mailparser = new MailParser(); -import fs = require("fs"); -mailparser.on("end", function(mail_object){ - console.log("Subject:", mail_object.subject); -}); - -fs.createReadStream("email.eml").pipe(mailparser); - - -// Attachments -mailparser.on("end", function(mail_object : ParsedMail){ - mail_object.attachments.forEach(function(attachment){ - console.log(attachment.fileName); - }); -}); - - -// Attachment streaming -var mp = new MailParser({ - streamAttachments: true -}) - -mp.on("attachment", function(attachment : Attachment, mail : ParsedMail){ - var output = fs.createWriteStream(attachment.generatedFileName); - attachment.stream.pipe(output); -}); +import fs = require('fs'); +fs.createReadStream('email.eml').pipe(mailparser); // check different sources and promise/callback api for simpleParser -var sourceString = ""; -var sourceBuffer = new Buffer(""); -var sourceStream = fs.createReadStream("foo.eml"); +var sourceString = ''; +var sourceBuffer = new Buffer(''); +var sourceStream = fs.createReadStream('foo.eml'); simpleParser(sourceString, (err, mail) => err ? err : mail.html); simpleParser(sourceBuffer, (err, mail) => err ? err : mail.html); @@ -76,3 +41,16 @@ simpleParser(sourceStream, (err, mail) => err ? err : mail.html); simpleParser(sourceString).then(mail => mail.html).catch(err => err); simpleParser(sourceBuffer).then(mail => mail.html).catch(err => err); simpleParser(sourceStream).then(mail => mail.html).catch(err => err); + +simpleParser(sourceString, (err, mail) => { + console.log(mail.headers.get('subject')); + console.log(mail.subject); + + // Attachments + mail.attachments.forEach(attachment => console.log(attachment.filename)); + + // Text + console.log(mail.text); + console.log(mail.html); + console.log(mail.textAsHtml); +}); From f0e31c622a5b407ae4ac7322b4d354eaca8cf872 Mon Sep 17 00:00:00 2001 From: Jan Karres Date: Fri, 7 Jul 2017 17:27:00 +0200 Subject: [PATCH 0224/1618] Update react-tag-input for v4.7.2 bugfix --- types/react-tag-input/index.d.ts | 14 +++++++------- types/react-tag-input/react-tag-input-tests.tsx | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/types/react-tag-input/index.d.ts b/types/react-tag-input/index.d.ts index 415a2ef2aa..64e24188a5 100644 --- a/types/react-tag-input/index.d.ts +++ b/types/react-tag-input/index.d.ts @@ -13,17 +13,17 @@ export interface ReactTagsProps { placeholder?: string; labelField?: string; - handleAddition: (tag: string) => void; - handleDelete: (i: number) => void; - handleDrag?: (tag: { id: number; text: string; }, currPos: number, newPos: number) => void; - handleInputChange?: (value: string) => void; - handleFilterSuggestions?: (textInputValue: string, possibleSuggestionsArray: string[]) => boolean; - handleInputBlur?: () => void; + handleAddition: ((tag: string) => void); + handleDelete: ((i: number) => void); + handleDrag?: ((tag: { id: number; text: string; }, currPos: number, newPos: number) => void); + handleInputChange?: ((value: string) => void); + handleFilterSuggestions?: ((textInputValue: string, possibleSuggestionsArray: string[]) => boolean); + handleInputBlur?: (() => void); autofocus?: boolean; allowDeleteFromEmptyInput?: boolean; minQueryLength?: number; - removeComponent?: React.Component; + removeComponent?: React.Component; autocomplete?: boolean | 1; readOnly?: boolean; maxLength?: number; diff --git a/types/react-tag-input/react-tag-input-tests.tsx b/types/react-tag-input/react-tag-input-tests.tsx index 42a9f6df97..d7029288d8 100644 --- a/types/react-tag-input/react-tag-input-tests.tsx +++ b/types/react-tag-input/react-tag-input-tests.tsx @@ -17,8 +17,8 @@ ReactDOM.render( handleAddition={(tag: string) => console.log("Add: " + tag)} handleDelete={(i: number) => console.log("Delete: " + i)} handleDrag={(tag: { id: number; text: string; }, currPos: number, newPos: number) => console.log("Drag: " + tag.text)} - handleInputChange={(value) => console.log("Changed to: ", value)} - handleFilterSuggestions={(textInputValue, possibleSuggestionsArray) => true} + handleInputChange={(value: string) => console.log("Changed to: ", value)} + handleFilterSuggestions={(textInputValue: string, possibleSuggestionsArray: string[]) => true} handleInputBlur={() => console.log("Blured")} autofocus={false} From dc9839670f968b3b5df60911d2393fd2d7d51ada Mon Sep 17 00:00:00 2001 From: Felix Caraballo Date: Fri, 7 Jul 2017 11:27:15 -0400 Subject: [PATCH 0225/1618] Add files via upload --- types/google-map-react/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index 5e54c4e5aa..037ebb5f13 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for google-map-react 0.22 +// Type definitions for google-map-react 0.23 // Project: https://github.com/istarkov/google-map-react // Definitions by: Honza Brecka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,6 +15,7 @@ export interface Options { mapTypeControl?: boolean; minZoomOverride?: boolean; minZoom?: number; + maxZoom?: number; gestureHandling?: string; } From ae024825f1ede860eff9514201b9fe07a831244d Mon Sep 17 00:00:00 2001 From: Jan Karres Date: Fri, 7 Jul 2017 17:40:03 +0200 Subject: [PATCH 0226/1618] Bugfix --- types/react-tag-input/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-tag-input/index.d.ts b/types/react-tag-input/index.d.ts index 64e24188a5..2720520766 100644 --- a/types/react-tag-input/index.d.ts +++ b/types/react-tag-input/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for React-Tags (react-tag-input) 4.7.2 // Project: https://github.com/prakhar1989/react-tags -// Definitions by: Ogglas , Jan Karres +// Definitions by: Ogglas +// Jan Karres // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From a18fdfd2f408170ed0b8b200e7cb24f937fa9b58 Mon Sep 17 00:00:00 2001 From: stonio Date: Fri, 7 Jul 2017 18:14:42 +0200 Subject: [PATCH 0227/1618] Create learn-tests.ts --- types/jquery/test/learn-tests.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 types/jquery/test/learn-tests.ts diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts new file mode 100644 index 0000000000..2ad633eddc --- /dev/null +++ b/types/jquery/test/learn-tests.ts @@ -0,0 +1,20 @@ +import jQueryFactory = require('jquery'); +const jQuery = jQueryFactory(window, true); + +# From https://learn.jquery.com/plugins/basic-plugin-creation/ + +## Basic Plugin Authoring + +interface JQuery { + greenify: GreenifyPlugin; +} + +interface GreenifyPlugin { + (this: JQuery): void; +} + +jQuery.fn.greenify = function() { + this.css( "color", "green" ); +}; + +jQuery( "a" ).greenify(); // Makes all the links green. From 5e2a11a1e4f6edb02afe6fd8f63bb51a1bf05d02 Mon Sep 17 00:00:00 2001 From: Mohsen Azimi Date: Fri, 7 Jul 2017 09:21:33 -0700 Subject: [PATCH 0228/1618] Update index.d.ts --- types/webpack/index.d.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 43295be8b9..5890c8679c 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -95,6 +95,18 @@ declare namespace webpack { interface Entry { [name: string]: string | string[]; } + + interface DevtoolModuleTemplateInfo { + identifier: string; + shortIdentifier: string; + resource: any; + resourcePath: string; + absoluteResourcePath: string; + allLoaders: any[]; + query: string; + moduleId: string; + hash: string; + } interface Output { /** The output directory as absolute path (required). */ @@ -106,9 +118,9 @@ declare namespace webpack { /** The filename of the SourceMaps for the JavaScript files. They are inside the output.path directory. */ sourceMapFilename?: string; /** Filename template string of function for the sources array in a generated SourceMap. */ - devtoolModuleFilenameTemplate?: string | (info: any) => string; + devtoolModuleFilenameTemplate?: string | ((info: DevtoolModuleTemplateInfo) => string); /** Similar to output.devtoolModuleFilenameTemplate, but used in the case of duplicate module identifiers. */ - devtoolFallbackModuleFilenameTemplate?: string; + devtoolFallbackModuleFilenameTemplate?: string | ((info: DevtoolModuleTemplateInfo) => string); /** * Enable line to line mapped mode for all/specified modules. * Line to line mapped mode uses a simple SourceMap where each line of the generated source is mapped to the same line of the original source. From 0d0eb743b7e9b5a150c252231e6029522dabf362 Mon Sep 17 00:00:00 2001 From: Mohsen Azimi Date: Fri, 7 Jul 2017 10:15:16 -0700 Subject: [PATCH 0229/1618] Update index.d.ts --- types/webpack/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 5890c8679c..251a7d2a74 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -95,7 +95,7 @@ declare namespace webpack { interface Entry { [name: string]: string | string[]; } - + interface DevtoolModuleTemplateInfo { identifier: string; shortIdentifier: string; From 1f359f76e72ed24e271d22fbbb60ec6fd55cead7 Mon Sep 17 00:00:00 2001 From: Mohsen Azimi Date: Fri, 7 Jul 2017 10:16:34 -0700 Subject: [PATCH 0230/1618] Update index.d.ts --- types/webpack/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 251a7d2a74..6fa0b2fc97 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -96,7 +96,7 @@ declare namespace webpack { [name: string]: string | string[]; } - interface DevtoolModuleTemplateInfo { + interface DevtoolModuleFilenameTemplateInfo { identifier: string; shortIdentifier: string; resource: any; @@ -118,9 +118,9 @@ declare namespace webpack { /** The filename of the SourceMaps for the JavaScript files. They are inside the output.path directory. */ sourceMapFilename?: string; /** Filename template string of function for the sources array in a generated SourceMap. */ - devtoolModuleFilenameTemplate?: string | ((info: DevtoolModuleTemplateInfo) => string); + devtoolModuleFilenameTemplate?: string | ((info: DevtoolModuleFilenameTemplateInfo) => string); /** Similar to output.devtoolModuleFilenameTemplate, but used in the case of duplicate module identifiers. */ - devtoolFallbackModuleFilenameTemplate?: string | ((info: DevtoolModuleTemplateInfo) => string); + devtoolFallbackModuleFilenameTemplate?: string | ((info: DevtoolModuleFilenameTemplateInfo) => string); /** * Enable line to line mapped mode for all/specified modules. * Line to line mapped mode uses a simple SourceMap where each line of the generated source is mapped to the same line of the original source. From 57973a461886d16330fa7756d87e09f1e2f8b662 Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Fri, 7 Jul 2017 20:56:30 +0200 Subject: [PATCH 0231/1618] fixed types following @rbuckton instructions. deleted tests --- types/bitcoinjs-lib/bitcoinjs-lib-tests.ts | 64 -- types/bitcoinjs-lib/index.d.ts | 1073 ++------------------ 2 files changed, 94 insertions(+), 1043 deletions(-) diff --git a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts index 7267fe5d26..e69de29bb2 100644 --- a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -1,64 +0,0 @@ -/// - -import bigi = require('bigi'); -import bitcoin = require('bitcoinjs-lib'); - -declare const it: any; -declare const describe: any; -declare const assert: any; - -describe('bitcoinjs-lib (basic)', () => { - it('can generate a random bitcoin address', () => { - // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } - - // generate random keyPair - const keyPair = bitcoin.ECPair.makeRandom({ rng }); - const address = keyPair.getAddress(); - - assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64'); - }); - - it('can generate an address from a SHA256 hash', () => { - const hash = bitcoin.crypto.sha256('correct horse battery staple'); - const d = bigi.fromBuffer(hash); - - const keyPair = new bitcoin.ECPair(d); - const address = keyPair.getAddress(); - - assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8'); - }); - - it('can generate a random keypair for alternative networks', () => { - // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } - - const litecoin = bitcoin.networks.litecoin; - - const keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); - const wif = keyPair.toWIF(); - const address = keyPair.getAddress(); - - assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn'); - assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS'); - }); - - it('can import an address via WIF', () => { - const keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct'); - const address = keyPair.getAddress(); - - assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31'); - }); - - it('can create a Transaction', () => { - const keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'); - const tx = new bitcoin.TransactionBuilder(); - - tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0); - tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000); - tx.sign(0, keyPair); - - // tslint:disable-next-line:max-line-length - assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000'); - }); -}); diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index cc6dca8747..eb4ec504af 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -1,10 +1,16 @@ -/** Declaration file initially generated by dts-gen for bitcoinjs-lib 3.0.3*/ +// Type definitions for bitcoinjs-lib 3.0.3 +// Project https://github.com/bitcoinjs/bitcoinjs-lib +// Declaration file initially generated by dts-gen for bitcoinjs-lib 3.0.3 +// Definitions by: Mohamed Hegazy +// Daniel +// Ron Buckton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// based on the flow version found at https://github.com/flowtype/flow-typed/blob/master/definitions/npm/bitcoinjs-lib_v2.x.x/flow_v0.17.x-/bitcoinjs-lib_v2.x.x.js -// Definitions by: Daniel . -/* modified by dlebrecht based on the flow version found at https://github.com/flowtype/flow-typed/blob/master/definitions/npm/bitcoinjs-lib_v2.x.x/flow_v0.17.x-/bitcoinjs-lib_v2.x.x.js */ +/// +import BigInteger = require("bigi"); - -export type Utxo = { +export interface Utxo { address: string; amount: number; scriptPubKey: Buffer; @@ -12,19 +18,19 @@ export type Utxo = { vout: number; } -export type Output = { +export interface Output { script: Buffer; value: number; -}; +} -export type Input = { +export interface Input { script: Buffer; hash: Buffer; index: number; sequence: number; -}; +} -export type Network = { +export interface Network { bip32: { public: number; private: number; @@ -35,11 +41,10 @@ export type Network = { wif: number; } - export class Block { constructor(); - byteLength(headersOnly: any): any; + byteLength(headersOnly?: boolean): number; checkMerkleRoot(): any; @@ -55,18 +60,20 @@ export class Block { toHex(headersOnly?: boolean): string; - static calculateMerkleRoot(transactions: any): any; + static calculateMerkleRoot(transactions: Transaction[] | { getHash(): Buffer; }[]): Buffer; - static calculateTarget(bits: any): any; + static calculateTarget(bits: number): Buffer; - static fromBuffer(buffer: Buffer): any; - - static fromHex(hex: string): any; + static fromBuffer(buffer: Buffer): Block; + static fromHex(hex: string): Block; } export class ECPair { - constructor(d: any, Q: any, options: any); + + constructor(d: BigInteger, Q?: null | undefined, options?: { compressed?: boolean, network?: Network }); + + constructor(d: null | undefined, Q: any, options?: { compressed?: boolean, network?: Network }); // Q should be ECPoint, but not sure how to define such type getAddress(): string; @@ -84,31 +91,31 @@ export class ECPair { static fromWIF(string: string, network: Network): ECPair; - static makeRandom(options: any): ECPair; - + static makeRandom(options?: { compressed?: boolean, network?: Network, rng?: (size: number) => Buffer }): ECPair; } export class ECSignature { - constructor(r: any, s: any, ...args: any[]); - toCompact(i: any, compressed: any): any; + constructor(r: BigInteger, s: BigInteger); - toDER(): any; + toCompact(i: number, compressed: boolean): Buffer; - toScriptSignature(hashType: any): any; + toDER(): Buffer; - static fromDER(buffer: Buffer): any; + toScriptSignature(hashType: number): Buffer; - static parseCompact(buffer: Buffer): any; + static fromDER(buffer: Buffer): ECSignature; - static parseScriptSignature(buffer: Buffer): any; + static parseCompact(buffer: Buffer): { compressed: boolean, i: number, signature: ECSignature }; + + static parseScriptSignature(buffer: Buffer): { signature: ECSignature, hashType: number }; } export class HDNode { - constructor(keyPair: ECPair, chainCode: any, ...args: any[]); + constructor(keyPair: ECPair, chainCode: Buffer); - keyPair: ECPair // dl added manually TODO check if correct + keyPair: ECPair; derive(index: number): HDNode; @@ -122,7 +129,7 @@ export class HDNode { getIdentifier(): Buffer; - getNetwork(): any; + getNetwork(): Network; getPublicKeyBuffer(): Buffer; @@ -132,56 +139,58 @@ export class HDNode { sign(hash: Buffer): ECSignature; - toBase58(__isPrivate?: any): string; + toBase58(): string; - verify(hash: Buffer, signature: any): Buffer; + verify(hash: Buffer, signature: ECSignature): Buffer; static HIGHEST_BIT: number; static LENGTH: number; - static fromBase58(string: string, networks?: any): HDNode; + static fromBase58(string: string, networks?: Network[] | Network): HDNode; - static fromSeedBuffer(seed: Buffer, network: Network, ...args: any[]): HDNode; + static fromSeedBuffer(seed: Buffer, network?: Network): HDNode; - static fromSeedHex(hex: string, network: Network): HDNode; + static fromSeedHex(hex: string, network?: Network): HDNode; + + static MASTER_SECRET: Buffer; } export class Transaction { version: number; locktime: number; - ins: Array; - outs: Array; + ins: Input[]; + outs: Output[]; constructor(); - addInput(hash: Buffer, index: number, sequence: any, scriptSig: Buffer, ...args: any[]): any; + addInput(hash: Buffer, index: number, sequence?: number, scriptSig?: Buffer): number; - addOutput(scriptPubKey: any, value: any, ...args: any[]): any; + addOutput(scriptPubKey: Buffer, value: number): number; - byteLength(): any; + byteLength(): number; clone(): Transaction; getHash(): Buffer; - getId(): any; + getId(): string; - hasWitnesses(): any; + hasWitnesses(): boolean; - hashForSignature(inindex: number, prevOutScript: any, hashType: any, ...args: any[]): any; + hashForSignature(inIndex: number, prevOutScript: Buffer, hashType: number): Buffer; - hashForWitnessV0(inindex: number, prevOutScript: any, value: any, hashType: any, ...args: any[]): any; + hashForWitnessV0(inIndex: number, prevOutScript: Buffer, value: number, hashType: number): Buffer; isCoinbase(): boolean; - setInputScript(index: number, scriptSig: Buffer, ...args: any[]): void; + setInputScript(index: number, scriptSig: Buffer): void; setWitness(index: number, witness: any, ...args: any[]): void; - toBuffer(buffer: Buffer, initialOffset: any): Buffer; + toBuffer(buffer: Buffer, initialOffset?: number): Buffer; - toHex(): any; + toHex(): string; static ADVANCED_TRANSACTION_FLAG: number; @@ -197,20 +206,19 @@ export class Transaction { static SIGHASH_SINGLE: number; - static fromBuffer(buffer: Buffer, __noStrict: any): Transaction; + static fromBuffer(buffer: Buffer, __noStrict?: boolean): Transaction; static fromHex(hex: string): Transaction; - static isCoinbaseHash(buffer: Buffer): any; - + static isCoinbaseHash(buffer: Buffer): boolean; } export class TransactionBuilder { - constructor(network: Network, maximumFeeRate?: any); + constructor(network?: Network, maximumFeeRate?: number); - addInput(txhash: Buffer|string|Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): void; + addInput(txhash: Buffer | string | Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): number; - addOutput(scriptPubKey: Buffer|string, value: any): any; + addOutput(scriptPubKey: Buffer | string, value: number): number; build(): Transaction; @@ -220,15 +228,13 @@ export class TransactionBuilder { setVersion(version: number): void; - sign(vin: number, keyPair: ECPair, redeemScript?: Buffer, hashType?: number, witnessValue?: any, witnessScript?: any): void; + sign(vin: number, keyPair: ECPair, redeemScript?: Buffer, hashType?: number, witnessValue?: number, witnessScript?: Buffer): void; static fromTransaction(transaction: Transaction, network: Network): TransactionBuilder; - } - export const networks: { - bitcoin: Network ; + bitcoin: Network; litecoin: Network; testnet: Network; }; @@ -353,968 +359,77 @@ export const opcodes: { OP_XOR: number; }; -export namespace HDNode { - namespace MASTER_SECRET { - const BYTES_PER_ELEMENT: number; - - const byteLength: number; - - const byteOffset: number; - - const length: number; - - const offset: number; - - function asciiSlice(): any; - - function asciiWrite(): any; - - function base64Slice(): any; - - function base64Write(): any; - - function compare(target: any, start: any, end: any, thisStart: any, thisEnd: any, ...args: any[]): any; - - function copy(): any; - - function copyWithin(p0: any, p1: any): any; - - function entries(): any; - - function equals(b: any): any; - - function every(p0: any): any; - - function fill(val: any, start: any, end: any, encoding: any): any; - - function filter(p0: any): any; - - function find(p0: any): any; - - function findIndex(p0: any): any; - - function forEach(p0: any): any; - - function hexSlice(): any; - - function hexWrite(): any; - - function includes(val: any, byteOffset: any, encoding: any): any; - - function indexOf(val: any, byteOffset: any, encoding: any): any; - - function inspect(): any; - - function join(p0: any): any; - - function keys(): any; - - function lastIndexOf(val: any, byteOffset: any, encoding: any): any; - - function latin1Slice(): any; - - function latin1Write(): any; - - function map(p0: any): any; - - function readDoubleBE(offset: any, noAssert: any): any; - - function readDoubleLE(offset: any, noAssert: any): any; - - function readFloatBE(offset: any, noAssert: any): any; - - function readFloatLE(offset: any, noAssert: any): any; - - function readInt16BE(offset: any, noAssert: any): any; - - function readInt16LE(offset: any, noAssert: any): any; - - function readInt32BE(offset: any, noAssert: any): any; - - function readInt32LE(offset: any, noAssert: any): any; - - function readInt8(offset: any, noAssert: any): any; - - function readIntBE(offset: any, byteLength: any, noAssert: any): any; - - function readIntLE(offset: any, byteLength: any, noAssert: any): any; - - function readUInt16BE(offset: any, noAssert: any): any; - - function readUInt16LE(offset: any, noAssert: any): any; - - function readUInt32BE(offset: any, noAssert: any): any; - - function readUInt32LE(offset: any, noAssert: any): any; - - function readUInt8(offset: any, noAssert: any): any; - - function readUIntBE(offset: any, byteLength: any, noAssert: any): any; - - function readUIntLE(offset: any, byteLength: any, noAssert: any): any; - - function reduce(p0: any): any; - - function reduceRight(p0: any): any; - - function reverse(): any; - - function set(p0: any): any; - - function slice(start: any, end: any): any; - - function some(p0: any): any; - - function sort(p0: any): any; - - function subarray(p0: any, p1: any): any; - - function swap16(): any; - - function swap32(): any; - - function swap64(): any; - - function toJSON(): any; - - function toLocaleString(encoding: any, start: any, end: any, ...args: any[]): any; - - function toString(encoding: any, start: any, end: any, ...args: any[]): any; - - function ucs2Slice(): any; - - function ucs2Write(): any; - - function utf8Slice(): any; - - function utf8Write(): any; - - function values(): any; - - function write(string: any, offset: any, length: any, encoding: any): any; - - function writeDoubleBE(val: any, offset: any, noAssert: any): any; - - function writeDoubleLE(val: any, offset: any, noAssert: any): any; - - function writeFloatBE(val: any, offset: any, noAssert: any): any; - - function writeFloatLE(val: any, offset: any, noAssert: any): any; - - function writeInt16BE(value: any, offset: any, noAssert: any): any; - - function writeInt16LE(value: any, offset: any, noAssert: any): any; - - function writeInt32BE(value: any, offset: any, noAssert: any): any; - - function writeInt32LE(value: any, offset: any, noAssert: any): any; - - function writeInt8(value: any, offset: any, noAssert: any): any; - - function writeIntBE(value: any, offset: any, byteLength: any, noAssert: any): any; - - function writeIntLE(value: any, offset: any, byteLength: any, noAssert: any): any; - - function writeUInt16BE(value: any, offset: any, noAssert: any): any; - - function writeUInt16LE(value: any, offset: any, noAssert: any): any; - - function writeUInt32BE(value: any, offset: any, noAssert: any): any; - - function writeUInt32LE(value: any, offset: any, noAssert: any): any; - - function writeUInt8(value: any, offset: any, noAssert: any): any; - - function writeUIntBE(value: any, offset: any, byteLength: any, noAssert: any): any; - - function writeUIntLE(value: any, offset: any, byteLength: any, noAssert: any): any; - - namespace asciiSlice { - const prototype: { - }; - - } - - namespace asciiWrite { - const prototype: { - }; - - } - - namespace base64Slice { - const prototype: { - }; - - } - - namespace base64Write { - const prototype: { - }; - - } - - namespace buffer { - const byteLength: number; - - function slice(p0: any, p1: any): any; - - } - - namespace compare { - const prototype: { - }; - - } - - namespace copy { - const prototype: { - }; - - } - - namespace equals { - const prototype: { - }; - - } - - namespace fill { - const prototype: { - }; - - } - - namespace hexSlice { - const prototype: { - }; - - } - - namespace hexWrite { - const prototype: { - }; - - } - - namespace includes { - const prototype: { - }; - - } - - namespace indexOf { - const prototype: { - }; - - } - - namespace inspect { - const prototype: { - }; - - } - - namespace lastIndexOf { - const prototype: { - }; - - } - - namespace latin1Slice { - const prototype: { - }; - - } - - namespace latin1Write { - const prototype: { - }; - - } - - namespace parent { - const byteLength: number; - - function slice(p0: any, p1: any): any; - - } - - namespace readDoubleBE { - const prototype: { - }; - - } - - namespace readDoubleLE { - const prototype: { - }; - - } - - namespace readFloatBE { - const prototype: { - }; - - } - - namespace readFloatLE { - const prototype: { - }; - - } - - namespace readInt16BE { - const prototype: { - }; - - } - - namespace readInt16LE { - const prototype: { - }; - - } - - namespace readInt32BE { - const prototype: { - }; - - } - - namespace readInt32LE { - const prototype: { - }; - - } - - namespace readInt8 { - const prototype: { - }; - - } - - namespace readIntBE { - const prototype: { - }; - - } - - namespace readIntLE { - const prototype: { - }; - - } - - namespace readUInt16BE { - const prototype: { - }; - - } - - namespace readUInt16LE { - const prototype: { - }; - - } - - namespace readUInt32BE { - const prototype: { - }; - - } - - namespace readUInt32LE { - const prototype: { - }; - - } - - namespace readUInt8 { - const prototype: { - }; - - } - - namespace readUIntBE { - const prototype: { - }; - - } - - namespace readUIntLE { - const prototype: { - }; - - } - - namespace slice { - const prototype: { - }; - - } - - namespace swap16 { - const prototype: { - }; - - } - - namespace swap32 { - const prototype: { - }; - - } - - namespace swap64 { - const prototype: { - }; - - } - - namespace toJSON { - const prototype: { - }; - - } - - namespace toLocaleString { - const prototype: { - }; - - } - - namespace toString { - const prototype: { - }; - - } - - namespace ucs2Slice { - const prototype: { - }; - - } - - namespace ucs2Write { - const prototype: { - }; - - } - - namespace utf8Slice { - const prototype: { - }; - - } - - namespace utf8Write { - const prototype: { - }; - - } - - namespace write { - const prototype: { - }; - - } - - namespace writeDoubleBE { - const prototype: { - }; - - } - - namespace writeDoubleLE { - const prototype: { - }; - - } - - namespace writeFloatBE { - const prototype: { - }; - - } - - namespace writeFloatLE { - const prototype: { - }; - - } - - namespace writeInt16BE { - const prototype: { - }; - - } - - namespace writeInt16LE { - const prototype: { - }; - - } - - namespace writeInt32BE { - const prototype: { - }; - - } - - namespace writeInt32LE { - const prototype: { - }; - - } - - namespace writeInt8 { - const prototype: { - }; - - } - - namespace writeIntBE { - const prototype: { - }; - - } - - namespace writeIntLE { - const prototype: { - }; - - } - - namespace writeUInt16BE { - const prototype: { - }; - - } - - namespace writeUInt16LE { - const prototype: { - }; - - } - - namespace writeUInt32BE { - const prototype: { - }; - - } - - namespace writeUInt32LE { - const prototype: { - }; - - } - - namespace writeUInt8 { - const prototype: { - }; - - } - - namespace writeUIntBE { - const prototype: { - }; - - } - - namespace writeUIntLE { - const prototype: { - }; - - } - - } - - -} - - - export namespace address { - function fromBase58Check(address: string): string; + function fromBase58Check(address: string): { hash: Buffer, version: number }; - function fromOutputScript(outputScript: Buffer, network: Network): string; + function fromOutputScript(outputScript: Buffer, network?: Network): { hash: Buffer, version: number }; - function toBase58Check(hash: Buffer, version: number, ...args: any[]): any; - - function toOutputScript(address: string, network: Network): any; - - namespace fromBase58Check { - const prototype: { - }; - - } - - namespace fromOutputScript { - const prototype: { - }; - - } - - namespace toBase58Check { - const prototype: { - }; - - } - - namespace toOutputScript { - const prototype: { - }; - - } + function toBase58Check(hash: Buffer, version: number): string; + function toOutputScript(address: string, network?: Network): string; } export namespace bufferutils { - function pushDataSize(i: any): any; + function pushDataSize(i: number): number; - function readPushDataInt(buffer: Buffer, offset: any): any; + function readPushDataInt(buffer: Buffer, offset: number): { opcode: number, number: number, size: number }; - function readUInt64LE(buffer: Buffer, offset: any): any; + function readUInt64LE(buffer: Buffer, offset: number): number; - function readVarInt(buffer: Buffer, offset: any): any; + function readVarInt(buffer: Buffer, offset: number): { number: number, size: number }; - function varIntBuffer(number: number, buffer: Buffer, offset: any): any; + function varIntBuffer(number: number, buffer: Buffer, offset: number): Buffer; - function varIntSize(number: number): any; + function varIntSize(number: number): number; - function writePushDataInt(buffer: Buffer, number: number, offset: any): any; + function writePushDataInt(buffer: Buffer, number: number, offset: number): number; - function writeUInt64LE(buffer: Buffer, value: any, offset: any): any; - - function writeVarInt(buffer: Buffer, number: number, offset: any): any; - - namespace pushDataSize { - const prototype: { - }; - - } - - namespace readPushDataInt { - const prototype: { - }; - - } - - namespace readUInt64LE { - const prototype: { - }; - - } - - namespace readVarInt { - const prototype: { - }; - - } - - namespace varIntBuffer { - const prototype: { - }; - - } - - namespace varIntSize { - const prototype: { - }; - - } - - namespace writePushDataInt { - const prototype: { - }; - - } - - namespace writeUInt64LE { - const prototype: { - }; - - } - - namespace writeVarInt { - const prototype: { - }; - - } + function writeUInt64LE(buffer: Buffer, value: number, offset: number): number; + function writeVarInt(buffer: Buffer, number: number, offset: number): number; } export namespace crypto { function hash160(buffer: Buffer): Buffer; - function hash256(buffer: Buffer): any; + function hash256(buffer: Buffer): Buffer; - function ripemd160(buffer: Buffer): any; + function ripemd160(buffer: Buffer): Buffer; - function sha1(buffer: Buffer): any; - - function sha256(buffer: Buffer): any; - - namespace hash160 { - const prototype: { - }; - - } - - namespace hash256 { - const prototype: { - }; - - } - - namespace ripemd160 { - const prototype: { - }; - - } - - namespace sha1 { - const prototype: { - }; - - } - - namespace sha256 { - const prototype: { - }; - - } + function sha1(buffer: Buffer): Buffer; + function sha256(buffer: Buffer): Buffer; } export namespace script { - const multisig: { - input: { - check: any; - decode: any; - decodeStack: any; - encode: any; - encodeStack: any; - }; - output: { - check: any; - decode: any; - encode: any; - }; - }; - const nullData: { - output: { - check: any; - decode: any; - encode: any; - }; - }; + function classifyInput(script: Buffer | (Buffer | number)[], allowIncomplete: boolean): "pubkeyhash" | "scripthash" | "multisig" | "pubkey" | "nonstandard"; - const pubKey: { - input: { - check: any; - decode: any; - decodeStack: any; - encode: any; - encodeStack: any; - }; - output: { - check: any; - decode: any; - encode: any; - }; - }; + function classifyOutput(script: Buffer | (Buffer | number)[]): "witnesspubkeyhash" | "witnessscripthash" | "pubkeyhash" | "scripthash" | "multisig" | "pubkey" | "witnesscommitment" | "nulldata" | "nonstandard"; - const pubKeyHash: { - input: { - check: any; - decode: any; - decodeStack: any; - encode: any; - encodeStack: any; - }; - output: { - check: any; - decode: any; - encode: any; - }; - }; + function classifyWitness(script: Buffer | (Buffer | number)[], allowIncomplete: boolean): "witnesspubkeyhash" | "witnessscripthash" | "nonstandard"; - const scriptHash: { - input: { - check: any; - decode: any; - decodeStack: any; - encode: any; - encodeStack: any; - }; - output: { - check: any; - decode: any; - encode: any; - }; - }; + function compile(chunks: (Buffer | number)[]): Buffer; - const types: { - MULTISIG: string; - NONSTANDARD: string; - NULLDATA: string; - P2PK: string; - P2PKH: string; - P2SH: string; - P2WPKH: string; - P2WSH: string; - WITNESS_COMMITMENT: string; - }; + function decompile(buffer: Buffer): (Buffer | number)[]; - const witnessCommitment: { - output: { - check: any; - decode: any; - encode: any; - }; - }; + function fromASM(asm: string): Buffer; - const witnessPubKeyHash: { - input: { - check: any; - decodeStack: any; - encodeStack: any; - }; - output: { - check: any; - decode: any; - encode: any; - }; - }; + function isCanonicalPubKey(buffer: Buffer): boolean; - const witnessScriptHash: { - input: { - check: any; - decodeStack: any; - encodeStack: any; - }; - output: { - check: any; - decode: any; - encode: any; - }; - }; + function isCanonicalSignature(buffer: Buffer): boolean; - function classifyInput(script: any, allowIncomplete: any): any; + function isDefinedHashType(hashType: any): boolean; - function classifyOutput(script: any): any; + function isPushOnly(value: any): boolean; - function classifyWitness(script: any, allowIncomplete: any): any; + function toASM(chunks: Buffer | (Buffer | number)[]): string; - function compile(chunks: any): any; - - function decompile(buffer: Buffer): any; - - function fromASM(asm: any): any; - - function isCanonicalPubKey(buffer: Buffer): any; - - function isCanonicalSignature(buffer: Buffer): any; - - function isDefinedHashType(hashType: any): any; - - function isPushOnly(value: any): any; - - function toASM(chunks: any): any; - - function toStack(chunks: any): any; - - namespace classifyInput { - const prototype: { - }; - - } - - namespace classifyOutput { - const prototype: { - }; - - } - - namespace classifyWitness { - const prototype: { - }; - - } - - namespace compile { - const prototype: { - }; - - } - - namespace decompile { - const prototype: { - }; - - } - - namespace fromASM { - const prototype: { - }; - - } - - namespace isCanonicalPubKey { - const prototype: { - }; - - } - - namespace isCanonicalSignature { - const prototype: { - }; - - } - - namespace isDefinedHashType { - const prototype: { - }; - - } - - namespace isPushOnly { - const prototype: { - }; - - } + function toStack(chunks: Buffer | (Buffer | number)[]): Buffer[]; namespace number { - function decode(buffer: Buffer, maxLength: any, minimal: any): any; - - function encode(number: number): any; - - namespace decode { - const prototype: { - }; - - } - - namespace encode { - const prototype: { - }; - - } + function decode(buffer: Buffer, maxLength: number, minimal: boolean): number; + function encode(number: number): Buffer; } - - namespace toASM { - const prototype: { - }; - - } - - namespace toStack { - const prototype: { - }; - - } - } From b47a73595c29bde94f0e909ae9d7f3c23ed36b0a Mon Sep 17 00:00:00 2001 From: Paul Douglas Brimicombe Date: Fri, 7 Jul 2017 20:09:06 +0100 Subject: [PATCH 0232/1618] Update type definitions for random-js --- types/random-js/index.d.ts | 121 +++++++++++++++-------------- types/random-js/random-js-tests.ts | 119 ++++++++++++++++++++++++++-- types/random-js/tslint.json | 4 + 3 files changed, 176 insertions(+), 68 deletions(-) create mode 100644 types/random-js/tslint.json diff --git a/types/random-js/index.d.ts b/types/random-js/index.d.ts index fd3909e508..6f03ffbd40 100644 --- a/types/random-js/index.d.ts +++ b/types/random-js/index.d.ts @@ -1,69 +1,70 @@ -// Type definitions for random-js 1.0.8 +// Type definitions for random-js 1.0 // Project: https://github.com/ckknight/random-js // Definitions by: Gustavo Di Pietro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare namespace Random { + interface Engine { + (): number; // tslint:disable-line callable-types + } -declare module TemporaryName { - - export interface Engine { - - } - - export interface MT19937 extends Engine{ - seed (value: number): Engine; - seedWithArray(array: Array): Engine - autoSeed(): Engine; - discard(count: number): Engine; - getUseCount(): Engine; - } - + interface MT19937 extends Engine { + seed(value: number): MT19937; + seedWithArray(array: number[]): MT19937; + autoSeed(): MT19937; + discard(count: number): MT19937; + getUseCount(): number; + } } -declare class TemporaryName { - constructor (engine?: TemporaryName.Engine); - - static engines: { - nativeMath: TemporaryName.Engine, - browserCrypto: TemporaryName.Engine, - mt19937: () => TemporaryName.MT19937 - } - - static Engine(): number; - static MT19937 (): number; - - static integer(min: number, max: number): (engine: TemporaryName.Engine) => number; - static real(min: number, max: number, inclusive: boolean): (engine: TemporaryName.Engine) => number; - static bool(percentage?: number): (engine: TemporaryName.Engine) => boolean; - static bool(numerator: number, denominator: number): (engine: TemporaryName.Engine) => boolean; - static pick(engine: TemporaryName.Engine, array: Array, begin?: number, end?: number): T; - static picker(array: Array, begin?: number, end?: number): (engine: TemporaryName.Engine) => T; - static shuffle(engine: TemporaryName.Engine, array: Array): Array; - static sample(engine: TemporaryName.Engine, population: Array, sampleSize: number): Array; - static die(sideCount: number): (engine: TemporaryName.Engine) => number; - static dice(sideCount: number, dieCount: number): (engine: TemporaryName.Engine) => number; - static uuid4(engine: TemporaryName.Engine): string; - static string(engine: TemporaryName.Engine, length: number): string; - static string(pool: string, length: number): (engine: TemporaryName.Engine, length: number) => string; - static hex(upperCase?: boolean): (engine: TemporaryName.Engine, length: number) => string; - static date(start: Date, end: Date): (engine: TemporaryName.Engine) => Date; - - integer(min: number, max: number): number; - real(min: number, max: number, inclusive: boolean): number; - bool(percentage?: number): (engine: TemporaryName.Engine) => boolean; - bool(numerator: number, denominator: number): boolean; - pick(engine: TemporaryName.Engine, array: Array, begin?: number, end?: number): T; - picker(array: Array, begin?: number, end?: number): (engine: TemporaryName.Engine) => T; - shuffle(engine: TemporaryName.Engine, array: Array): Array; - sample(engine: TemporaryName.Engine, population: Array, sampleSize: number): Array; - die(sideCount: number): (engine: TemporaryName.Engine) => number; - dice(sideCount: number, dieCount: number): number; - uuid4(engine: TemporaryName.Engine): string; - string(engine: TemporaryName.Engine, length: number): string; - string(pool: string, length: number): string; - hex(upperCase?: boolean): string; - date(start: Date, end: Date): Date; +interface Random { + integer(min: number, max: number): number; + real(min: number, max: number, inclusive?: boolean): number; + bool(percentage?: number): boolean; // tslint:disable-line unified-signatures + bool(numerator: number, denominator: number): boolean; // tslint:disable-line unified-signatures + pick(array: T[], begin?: number, end?: number): T; + shuffle(array: T[]): T[]; + sample(population: T[], sampleSize: number): T[]; + die(sideCount: number): number; + dice(sideCount: number, dieCount: number): number[]; + uuid4(engine: Random.Engine): string; + string(engine: Random.Engine, length: number): string; + string(length?: number, pool?: string): string; + hex(length?: number, upperCase?: boolean): string; + date(start: Date, end: Date): Date; } -export = TemporaryName; -export as namespace Random; \ No newline at end of file +interface RandomConstructor { + (engine?: Engine): Random; + new (engine?: Engine): Random; + + engines: { + nativeMath: Random.Engine, + browserCrypto: Random.Engine, + mt19937(): Random.MT19937 + }; + + Engine(): number; + MT19937(): number; + + integer(min: number, max: number): (engine: Random.Engine) => number; + real(min: number, max: number, inclusive?: boolean): (engine: Random.Engine) => number; + bool(percentage?: number): (engine: Random.Engine) => boolean; // tslint:disable-line unified-signatures + bool(numerator: number, denominator: number): (engine: Random.Engine) => boolean; // tslint:disable-line unified-signatures + pick(engine: Random.Engine, array: T[], begin?: number, end?: number): T; + picker(array: T[], begin?: number, end?: number): (engine: Random.Engine) => T; + shuffle(engine: Random.Engine, array: T[]): T[]; + sample(engine: Random.Engine, population: T[], sampleSize: number): T[]; + die(sideCount: number): (engine: Random.Engine) => number; + dice(sideCount: number, dieCount: number): (engine: Random.Engine) => number[]; + uuid4(engine: Random.Engine): string; + string(engine: Random.Engine, length: number): string; + string(pool?: string): (engine: Random.Engine, length?: number) => string; + hex(upperCase?: boolean): (engine: Random.Engine, length?: number) => string; + date(start: Date, end: Date): (engine: Random.Engine) => Date; +} + +declare const Random: RandomConstructor; + +export = Random; +export as namespace Random; diff --git a/types/random-js/random-js-tests.ts b/types/random-js/random-js-tests.ts index 1b9e27c177..ef438e18c5 100644 --- a/types/random-js/random-js-tests.ts +++ b/types/random-js/random-js-tests.ts @@ -1,25 +1,128 @@ +import Engine = Random.Engine; +import MersenneTwisterEngine = Random.MT19937; + +class CustomType {} +const customTypeArray = [new CustomType(), new CustomType(), new CustomType()]; + +// APIs taken from the documentation at https://github.com/ckknight/random-js + +// Basic engine types (https://github.com/ckknight/random-js#engines) +let engine: Engine = Random.engines.nativeMath; +engine = Random.engines.browserCrypto; + +// All engines can be used to generate numbers +let generated: number = engine(); + +// Mersenne Twister API (https://github.com/ckknight/random-js#mersenne-twister-api) +let mersenneTwister: MersenneTwisterEngine = Random.engines.mt19937(); +generated = mersenneTwister(); + +mersenneTwister = mersenneTwister.seed(0x9a0b1d43); +mersenneTwister = mersenneTwister.seedWithArray([0x12345678, 0x90abcdef]); +mersenneTwister = mersenneTwister.autoSeed(); +mersenneTwister = mersenneTwister.discard(10); +const useCount: number = mersenneTwister.getUseCount(); + +// Static "Distributions" API (https://github.com/ckknight/random-js#distributions) +let numeric: number = Random.integer(0, 99)(engine); +numeric = Random.real(0, 10)(engine); +numeric = Random.real(0, 10, true)(engine); + +let bool: boolean = Random.bool()(engine); +bool = Random.bool(20)(engine); +bool = Random.bool(1, 2)(engine); + +let chosen: CustomType = Random.pick(engine, customTypeArray); +chosen = Random.pick(engine, customTypeArray, 0); +chosen = Random.pick(engine, customTypeArray, 0, 2); +chosen = Random.picker(customTypeArray); +chosen = Random.picker(customTypeArray, 0); +chosen = Random.picker(customTypeArray, 0, 2); + +let shuffled: CustomType[] = Random.shuffle(engine, customTypeArray); +let sampled: CustomType[] = Random.sample(engine, customTypeArray, 2); + +numeric = Random.die(5)(engine); +let dieValues: number[] = Random.dice(5, 2)(engine); + +let uuid: string = Random.uuid4(engine); + +let str: string = Random.string()(engine); +str = Random.string()(engine); +str = Random.string()(engine, 10); +str = Random.string('abc')(engine); +str = Random.string('abc')(engine, 2); + +let hex: string = Random.hex()(engine); +hex = Random.hex()(engine, 5); +hex = Random.hex(false)(engine); +hex = Random.hex(false)(engine, 5); +hex = Random.hex(true)(engine); +hex = Random.hex(true)(engine, 5); + +let date: Date = Random.date(new Date(), new Date())(engine); + +// "Alternate" API (https://github.com/ckknight/random-js#alternate-api) + +let random: Random = new Random(engine); +random = new Random(); +random = Random(); + +numeric = random.integer(0, 99); +numeric = random.real(0, 10); +numeric = random.real(0, 10, true); + +bool = random.bool(); +bool = random.bool(50); +bool = random.bool(1, 2); + +chosen = random.pick(customTypeArray); +chosen = random.pick(customTypeArray, 0); +chosen = random.pick(customTypeArray, 0, 2); + +shuffled = random.shuffle(customTypeArray); +sampled = random.sample(customTypeArray, 2); + +numeric = random.die(5); +dieValues = random.dice(5, 2); + +uuid = Random.uuid4(engine); + +str = random.string(); +str = random.string(10); +str = random.string(10, 'abc'); + +hex = random.hex(); +hex = random.hex(5); +hex = random.hex(5, false); +hex = random.hex(undefined, false); +hex = random.hex(5, true); +hex = random.hex(undefined, true); + +date = random.date(new Date(), new Date()); + // Examples taken from the documentation at https://github.com/ckknight/random-js // create a Mersenne Twister-19937 that is auto-seeded based on time and other random values -import Engine = Random.Engine; -var engine: Engine = Random.engines.mt19937().autoSeed(); +engine = Random.engines.mt19937().autoSeed(); // create a distribution that will consistently produce integers within inclusive range [0, 99]. -var distribution: Function = Random.integer(0, 99); +const distribution: ((engine: Engine) => number) = Random.integer(0, 99); // generate a number that is guaranteed to be within [0, 99] without any particular bias. function generateNaturalLessThan100(): number { return distribution(engine); } +// NOTE: The documentation for this example is incorrect in the library documentation // using essentially Math.random() -var engine2: Engine = Random.engines.nativeMath; +const engine2: Engine = Random.engines.nativeMath; // lower-case Hex string distribution -var distribution2: Function = Random.hex(false); +const distribution2: ((engine: Engine, length: number) => string) = Random.hex(false); // generate a 40-character hex string function generateSHA1(): string { - return distribution(40); + return distribution2(engine2, 40); } -var r: Random = new Random(Random.engines.mt19937().seedWithArray([0x12345678, 0x90abcdef])); -var value = r.integer(0, 99); +let r: Random = new Random(Random.engines.mt19937().seedWithArray([0x12345678, 0x90abcdef])); +const value = r.integer(0, 99); r = new Random(); // same as new Random(Random.engines.nativeMath) diff --git a/types/random-js/tslint.json b/types/random-js/tslint.json new file mode 100644 index 0000000000..e26ec8f7eb --- /dev/null +++ b/types/random-js/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} From 8a93b22efe3bc47d44973cf0f8d06005ffe677c4 Mon Sep 17 00:00:00 2001 From: Philippe Legault Date: Fri, 7 Jul 2017 12:36:02 -0700 Subject: [PATCH 0233/1618] React-Burger-Menu: Compatibility with older versions of React Removing the state of ReactBurgerMenu isn't compatible with older versions of React. I know that this request is a bit regressive, but explicitly defining the state would be more practical for those of us who can't easily upgrade React. --- types/react-burger-menu/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-burger-menu/index.d.ts b/types/react-burger-menu/index.d.ts index 7368c335e2..8e43992940 100644 --- a/types/react-burger-menu/index.d.ts +++ b/types/react-burger-menu/index.d.ts @@ -41,7 +41,7 @@ export interface Props { width?: number | string; } -export class ReactBurgerMenu extends React.Component { } +export class ReactBurgerMenu extends React.Component { } export class slide extends ReactBurgerMenu { } export class stack extends ReactBurgerMenu { } From 1bc2e97c9ff03f7be47db31db155ee93c1d22b59 Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Fri, 7 Jul 2017 22:30:31 +0200 Subject: [PATCH 0234/1618] fixed header mistakes --- types/bitcoinjs-lib/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index eb4ec504af..a5e5c6179b 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for bitcoinjs-lib 3.0.3 -// Project https://github.com/bitcoinjs/bitcoinjs-lib -// Declaration file initially generated by dts-gen for bitcoinjs-lib 3.0.3 +// Type definitions for bitcoinjs-lib 3.0 +// Project: https://github.com/bitcoinjs/bitcoinjs-lib // Definitions by: Mohamed Hegazy // Daniel // Ron Buckton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Declaration file initially generated by dts-gen for bitcoinjs-lib 3.0.3 // based on the flow version found at https://github.com/flowtype/flow-typed/blob/master/definitions/npm/bitcoinjs-lib_v2.x.x/flow_v0.17.x-/bitcoinjs-lib_v2.x.x.js /// From ca61e7a06903d2fe2e23ee1aac3edfa9914eaa77 Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Fri, 7 Jul 2017 22:44:31 +0200 Subject: [PATCH 0235/1618] changed [] for Array on complex types --- types/bitcoinjs-lib/bitcoinjs-lib-tests.ts | 0 types/bitcoinjs-lib/index.d.ts | 22 +++++++++------------- 2 files changed, 9 insertions(+), 13 deletions(-) delete mode 100644 types/bitcoinjs-lib/bitcoinjs-lib-tests.ts diff --git a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index a5e5c6179b..8e5cdcf9fa 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -60,7 +60,7 @@ export class Block { toHex(headersOnly?: boolean): string; - static calculateMerkleRoot(transactions: Transaction[] | { getHash(): Buffer; }[]): Buffer; + static calculateMerkleRoot(transactions: Transaction[] | Array<{ getHash(): Buffer; }>): Buffer; static calculateTarget(bits: number): Buffer; @@ -70,7 +70,6 @@ export class Block { } export class ECPair { - constructor(d: BigInteger, Q?: null | undefined, options?: { compressed?: boolean, network?: Network }); constructor(d: null | undefined, Q: any, options?: { compressed?: boolean, network?: Network }); // Q should be ECPoint, but not sure how to define such type @@ -95,7 +94,6 @@ export class ECPair { } export class ECSignature { - constructor(r: BigInteger, s: BigInteger); toCompact(i: number, compressed: boolean): Buffer; @@ -109,7 +107,6 @@ export class ECSignature { static parseCompact(buffer: Buffer): { compressed: boolean, i: number, signature: ECSignature }; static parseScriptSignature(buffer: Buffer): { signature: ECSignature, hashType: number }; - } export class HDNode { @@ -154,7 +151,6 @@ export class HDNode { static fromSeedHex(hex: string, network?: Network): HDNode; static MASTER_SECRET: Buffer; - } export class Transaction { @@ -402,16 +398,16 @@ export namespace crypto { } export namespace script { + function classifyInput(script: Buffer | Array, allowIncomplete: boolean): "pubkeyhash" | "scripthash" | "multisig" | "pubkey" | "nonstandard"; - function classifyInput(script: Buffer | (Buffer | number)[], allowIncomplete: boolean): "pubkeyhash" | "scripthash" | "multisig" | "pubkey" | "nonstandard"; + function classifyOutput(script: Buffer | Array): "witnesspubkeyhash" | "witnessscripthash" | "pubkeyhash" + | "scripthash" | "multisig" | "pubkey" | "witnesscommitment" | "nulldata" | "nonstandard"; - function classifyOutput(script: Buffer | (Buffer | number)[]): "witnesspubkeyhash" | "witnessscripthash" | "pubkeyhash" | "scripthash" | "multisig" | "pubkey" | "witnesscommitment" | "nulldata" | "nonstandard"; + function classifyWitness(script: Buffer | Array, allowIncomplete: boolean): "witnesspubkeyhash" | "witnessscripthash" | "nonstandard"; - function classifyWitness(script: Buffer | (Buffer | number)[], allowIncomplete: boolean): "witnesspubkeyhash" | "witnessscripthash" | "nonstandard"; + function compile(chunks: Array): Buffer; - function compile(chunks: (Buffer | number)[]): Buffer; - - function decompile(buffer: Buffer): (Buffer | number)[]; + function decompile(buffer: Buffer): Array; function fromASM(asm: string): Buffer; @@ -423,9 +419,9 @@ export namespace script { function isPushOnly(value: any): boolean; - function toASM(chunks: Buffer | (Buffer | number)[]): string; + function toASM(chunks: Buffer | Array): string; - function toStack(chunks: Buffer | (Buffer | number)[]): Buffer[]; + function toStack(chunks: Buffer | Array): Buffer[]; namespace number { function decode(buffer: Buffer, maxLength: number, minimal: boolean): number; From 47689f36ce4c5859d12246b8967ba28bd22e1a94 Mon Sep 17 00:00:00 2001 From: Daniel Lebrecht Date: Fri, 7 Jul 2017 23:09:57 +0200 Subject: [PATCH 0236/1618] small style fixes --- types/bitcoinjs-lib/bitcoinjs-lib-tests.ts | 1 + types/bitcoinjs-lib/index.d.ts | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 types/bitcoinjs-lib/bitcoinjs-lib-tests.ts diff --git a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts new file mode 100644 index 0000000000..ed54b008e0 --- /dev/null +++ b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -0,0 +1 @@ +console.log('no tests yet'); diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index 8e5cdcf9fa..dc2af73403 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -90,9 +90,11 @@ export class ECPair { static fromWIF(string: string, network: Network): ECPair; - static makeRandom(options?: { compressed?: boolean, network?: Network, rng?: (size: number) => Buffer }): ECPair; + static makeRandom(options?: { compressed?: boolean, network?: Network, rng?: Rng }): ECPair; } +export type Rng = (size: number) => Buffer; + export class ECSignature { constructor(r: BigInteger, s: BigInteger); From 6b527c5f44f31cff4d8d0296775e0c9f98cddacb Mon Sep 17 00:00:00 2001 From: Hendrik Liebau Date: Fri, 7 Jul 2017 12:28:31 +0200 Subject: [PATCH 0237/1618] declare fetchMock as namespace --- types/fetch-mock/fetch-mock-tests.ts | 5 + types/fetch-mock/index.d.ts | 758 ++++++++++++++------------- 2 files changed, 385 insertions(+), 378 deletions(-) diff --git a/types/fetch-mock/fetch-mock-tests.ts b/types/fetch-mock/fetch-mock-tests.ts index d3ea2c374c..c9b1737a47 100644 --- a/types/fetch-mock/fetch-mock-tests.ts +++ b/types/fetch-mock/fetch-mock-tests.ts @@ -60,3 +60,8 @@ fetchMock fetchMock .mock("http://test.com", 200) .spy(); + +const myMatcher: fetchMock.MockMatcherFunction = ( + url: string, + opts: fetchMock.MockRequest +) => true; diff --git a/types/fetch-mock/index.d.ts b/types/fetch-mock/index.d.ts index 650045e7ac..f1c109bb53 100644 --- a/types/fetch-mock/index.d.ts +++ b/types/fetch-mock/index.d.ts @@ -4,395 +4,397 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -type MockRequest = Request | RequestInit; +declare namespace fetchMock { + type MockRequest = Request | RequestInit; -/** - * Mock matcher function - * @param url - * @param opts - */ -type MockMatcherFunction = (url: string, opts: MockRequest) => boolean; -/** - * Mock matcher. Can be one of following: - * string: Either - * * an exact url to match e.g. 'http://www.site.com/page.html' - * * if the string begins with a `^`, the string following the `^` must - * begin the url e.g. '^http://www.site.com' would match - * 'http://www.site.com' or 'http://www.site.com/page.html' - * * '*' to match any url - * RegExp: A regular expression to test the url against - * Function(url, opts): A function (returning a Boolean) that is passed the - * url and opts fetch() is called with (or, if fetch() was called with one, - * the Request instance) - */ -type MockMatcher = string | RegExp | MockMatcherFunction; + /** + * Mock matcher function + * @param url + * @param opts + */ + type MockMatcherFunction = (url: string, opts: MockRequest) => boolean; + /** + * Mock matcher. Can be one of following: + * string: Either + * * an exact url to match e.g. 'http://www.site.com/page.html' + * * if the string begins with a `^`, the string following the `^` must + * begin the url e.g. '^http://www.site.com' would match + * 'http://www.site.com' or 'http://www.site.com/page.html' + * * '*' to match any url + * RegExp: A regular expression to test the url against + * Function(url, opts): A function (returning a Boolean) that is passed the + * url and opts fetch() is called with (or, if fetch() was called with one, + * the Request instance) + */ + type MockMatcher = string | RegExp | MockMatcherFunction; -/** - * Mock response object - */ -interface MockResponseObject { /** - * Set the response body + * Mock response object */ - body?: string | {}; + interface MockResponseObject { + /** + * Set the response body + */ + body?: string | {}; + /** + * Set the response status + * @default 200 + */ + status?: number; + /** + * Set the response headers. + */ + headers?: { [key: string]: string }; + /** + * If this property is present then a Promise rejected with the value + * of throws is returned + */ + throws?: boolean; + /** + * This property determines whether or not the request body should be + * JSON.stringified before being sent + * @default true + */ + sendAsJson?: boolean; + } /** - * Set the response status - * @default 200 + * Response: A Response instance - will be used unaltered + * number: Creates a response with this status + * string: Creates a 200 response with the string as the response body + * object: As long as the object is not a MockResponseObject it is + * converted into a json string and returned as the body of a 200 response + * If MockResponseObject was given then it's used to configure response + * Function(url, opts): A function that is passed the url and opts fetch() + * is called with and that returns any of the responses listed above */ - status?: number; + type MockResponse = Response | Promise + | number | Promise + | string | Promise + | {} | Promise<{}> + | MockResponseObject | Promise; /** - * Set the response headers. + * Mock response function + * @param url + * @param opts */ - headers?: { [key: string]: string }; - /** - * If this property is present then a Promise rejected with the value - * of throws is returned - */ - throws?: boolean; - /** - * This property determines whether or not the request body should be - * JSON.stringified before being sent - * @default true - */ - sendAsJson?: boolean; -} -/** - * Response: A Response instance - will be used unaltered - * number: Creates a response with this status - * string: Creates a 200 response with the string as the response body - * object: As long as the object is not a MockResponseObject it is - * converted into a json string and returned as the body of a 200 response - * If MockResponseObject was given then it's used to configure response - * Function(url, opts): A function that is passed the url and opts fetch() - * is called with and that returns any of the responses listed above - */ -type MockResponse = Response | Promise - | number | Promise - | string | Promise - | {} | Promise<{}> - | MockResponseObject | Promise; -/** - * Mock response function - * @param url - * @param opts - */ -type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse; + type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse; -/** - * Mock options object - */ -interface MockOptions { /** - * A unique string naming the route. Used to subsequently retrieve - * references to the calls, grouped by name. - * @default matcher.toString() - * - * Note: If a non-unique name is provided no error will be thrown - * (because names are optional, auto-generated ones may legitimately - * clash) + * Mock options object */ - name?: string; - /** - * http method to match - */ - method?: string; - /** - * as specified above - */ - matcher?: MockMatcher; - /** - * as specified above - */ - response?: MockResponse | MockResponseFunction; - /** - * integer, n, limiting the number of times the matcher can be used. - * If the route has already been called n times the route will be - * ignored and the call to fetch() will fall through to be handled by - * any other routes defined (which may eventually result in an error - * if nothing matches it). - */ - times?: number; + interface MockOptions { + /** + * A unique string naming the route. Used to subsequently retrieve + * references to the calls, grouped by name. + * @default matcher.toString() + * + * Note: If a non-unique name is provided no error will be thrown + * (because names are optional, auto-generated ones may legitimately + * clash) + */ + name?: string; + /** + * http method to match + */ + method?: string; + /** + * as specified above + */ + matcher?: MockMatcher; + /** + * as specified above + */ + response?: MockResponse | MockResponseFunction; + /** + * integer, n, limiting the number of times the matcher can be used. + * If the route has already been called n times the route will be + * ignored and the call to fetch() will fall through to be handled by + * any other routes defined (which may eventually result in an error + * if nothing matches it). + */ + times?: number; + } + + type MockCall = [string, MockRequest]; + + interface MatchedRoutes { + matched: MockCall[]; + unmatched: MockCall[]; + } + + interface MockOptionsMethodGet extends MockOptions { + method: 'GET'; + } + + interface MockOptionsMethodPost extends MockOptions { + method: 'POST'; + } + + interface MockOptionsMethodPut extends MockOptions { + method: 'PUT'; + } + + interface MockOptionsMethodDelete extends MockOptions { + method: 'DELETE'; + } + + interface MockOptionsMethodHead extends MockOptions { + method: 'HEAD'; + } + + interface FetchMockStatic { + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptions): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Calls to .mock() can be chained. + * @param options The route to mock + */ + mock(options: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() limited to being + * called one time only. Calls to .once() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Optional additional properties defining the route to mock + */ + once(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptions): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the GET + * method. Calls to .get() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + get(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the GET + * method and limited to being called one time only. Calls to .getOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + getOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the POST + * method. Calls to .post() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + post(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the POST + * method and limited to being called one time only. Calls to .postOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + postOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PUT + * method. Calls to .put() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + put(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PUT + * method and limited to being called one time only. Calls to .putOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + putOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the + * DELETE method. Calls to .delete() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + delete(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the + * DELETE method and limited to being called one time only. Calls to + * .deleteOnce() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + deleteOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the HEAD + * method. Calls to .head() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + head(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the HEAD + * method and limited to being called one time only. Calls to .headOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + headOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PATCH + * method. Calls to .patch() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + patch(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + * route, and optionally returns a mocked Response object or passes the + * call through to fetch(). Shorthand for mock() restricted to the PATCH + * method and limited to being called one time only. Calls to .patchOnce() + * can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + patchOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + + /** + * Chainable method that defines how to respond to calls to fetch that + * don't match any of the defined mocks. It accepts the same types of + * response as a normal call to .mock(matcher, response). It can also + * take an arbitrary function to completely customise behaviour of + * unmatched calls. If .catch() is called without any parameters then + * every unmatched call will receive a 200 response. + * @param [response] Configures the http response returned by the mock + */ + catch(response?: MockResponse | MockResponseFunction): this; + + /** + * Chainable method that records the call history of unmatched calls, + * but instead of responding with a stubbed response, the request is + * passed through to native fetch() and is allowed to communicate + * over the network. Similar to catch(). + */ + spy(response?: MockResponse | MockResponseFunction): this; + + /** + * Chainable method that restores fetch() to its unstubbed state and + * clears all data recorded for its calls. + */ + restore(): this; + + /** + * Chainable method that clears all data recorded for fetch()'s calls + */ + reset(): this; + + /** + * Returns all calls to fetch, grouped by whether fetch-mock matched + * them or not. + */ + calls(): MatchedRoutes; + /** + * Returns all calls to fetch matching matcherName. + */ + calls(matcherName?: string): MockCall[]; + + /** + * Returns a Boolean indicating whether fetch was called and a route + * was matched (or a specific route if matcherName is passed). + * @param [matcherName] either the name of a route or equal to + * matcher.toString() for any unnamed route + */ + called(matcherName?: string): boolean; + + /** + * Returns a Boolean indicating whether fetch was called the expected + * number of times (or at least once if the route defines no expectation + * is set) for every route (or for a specific route if matcherName is + * passed). + * @param [matcherName] either the name of a route or equal to + * matcher.toString() for any unnamed route + */ + done(matcherName?: string): boolean; + + /** + * Returns the arguments for the last matched call to fetch (or the + * last call to specific route is matcherName is passed). + * @param [matcherName] either the name of a route or equal to + * matcher.toString() for any unnamed route + */ + lastCall(matcherName?: string): MockCall; + + /** + * Returns the url for the last matched call to fetch (or the last + * call to specific route is matcherName is passed). + * @param [matcherName] either the name of a route or equal to + * matcher.toString() for any unnamed route + */ + lastUrl(matcherName?: string): string; + + /** + * Returns the options for the last matched call to fetch (or the + * last call to a specific route is matcherName is passed). + * @param [matcherName] either the name of a route or equal to + * matcher.toString() for any unnamed route + */ + lastOptions(matcherName?: string): MockRequest; + + /** + * Set some global config options, which include + * sendAsJson [default `true`] - by default fetchMock will + * convert objects to JSON before sending. This is overrideable + * for each call but for some scenarios, e.g. when dealing with a + * lot of array buffers, it can be useful to default to `false` + */ + configure(opts: {}): void; + } } -type MockCall = [string, MockRequest]; - -interface MatchedRoutes { - matched: MockCall[]; - unmatched: MockCall[]; -} - -interface MockOptionsMethodGet extends MockOptions { - method: 'GET'; -} - -interface MockOptionsMethodPost extends MockOptions { - method: 'POST'; -} - -interface MockOptionsMethodPut extends MockOptions { - method: 'PUT'; -} - -interface MockOptionsMethodDelete extends MockOptions { - method: 'DELETE'; -} - -interface MockOptionsMethodHead extends MockOptions { - method: 'HEAD'; -} - -interface FetchMockStatic { - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Calls to .mock() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptions): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Calls to .mock() can be chained. - * @param options The route to mock - */ - mock(options: MockOptions): this; - - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() limited to being - * called one time only. Calls to .once() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Optional additional properties defining the route to mock - */ - once(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptions): this; - - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the GET - * method. Calls to .get() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - get(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the GET - * method and limited to being called one time only. Calls to .getOnce() - * can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - getOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; - - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the POST - * method. Calls to .post() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - post(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the POST - * method and limited to being called one time only. Calls to .postOnce() - * can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - postOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; - - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the PUT - * method. Calls to .put() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - put(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the PUT - * method and limited to being called one time only. Calls to .putOnce() - * can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - putOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; - - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the - * DELETE method. Calls to .delete() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - delete(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the - * DELETE method and limited to being called one time only. Calls to - * .deleteOnce() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - deleteOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; - - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the HEAD - * method. Calls to .head() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - head(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the HEAD - * method and limited to being called one time only. Calls to .headOnce() - * can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - headOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; - - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the PATCH - * method. Calls to .patch() can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - patch(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; - /** - * Replaces fetch() with a stub which records its calls, grouped by - * route, and optionally returns a mocked Response object or passes the - * call through to fetch(). Shorthand for mock() restricted to the PATCH - * method and limited to being called one time only. Calls to .patchOnce() - * can be chained. - * @param matcher Condition for selecting which requests to mock - * @param response Configures the http response returned by the mock - * @param [options] Additional properties defining the route to mock - */ - patchOnce(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; - - /** - * Chainable method that defines how to respond to calls to fetch that - * don't match any of the defined mocks. It accepts the same types of - * response as a normal call to .mock(matcher, response). It can also - * take an arbitrary function to completely customise behaviour of - * unmatched calls. If .catch() is called without any parameters then - * every unmatched call will receive a 200 response. - * @param [response] Configures the http response returned by the mock - */ - catch(response?: MockResponse | MockResponseFunction): this; - - /** - * Chainable method that records the call history of unmatched calls, - * but instead of responding with a stubbed response, the request is - * passed through to native fetch() and is allowed to communicate - * over the network. Similar to catch(). - */ - spy(response?: MockResponse | MockResponseFunction): this; - - /** - * Chainable method that restores fetch() to its unstubbed state and - * clears all data recorded for its calls. - */ - restore(): this; - - /** - * Chainable method that clears all data recorded for fetch()'s calls - */ - reset(): this; - - /** - * Returns all calls to fetch, grouped by whether fetch-mock matched - * them or not. - */ - calls(): MatchedRoutes; - /** - * Returns all calls to fetch matching matcherName. - */ - calls(matcherName?: string): MockCall[]; - - /** - * Returns a Boolean indicating whether fetch was called and a route - * was matched (or a specific route if matcherName is passed). - * @param [matcherName] either the name of a route or equal to - * matcher.toString() for any unnamed route - */ - called(matcherName?: string): boolean; - - /** - * Returns a Boolean indicating whether fetch was called the expected - * number of times (or at least once if the route defines no expectation - * is set) for every route (or for a specific route if matcherName is - * passed). - * @param [matcherName] either the name of a route or equal to - * matcher.toString() for any unnamed route - */ - done(matcherName?: string): boolean; - - /** - * Returns the arguments for the last matched call to fetch (or the - * last call to specific route is matcherName is passed). - * @param [matcherName] either the name of a route or equal to - * matcher.toString() for any unnamed route - */ - lastCall(matcherName?: string): MockCall; - - /** - * Returns the url for the last matched call to fetch (or the last - * call to specific route is matcherName is passed). - * @param [matcherName] either the name of a route or equal to - * matcher.toString() for any unnamed route - */ - lastUrl(matcherName?: string): string; - - /** - * Returns the options for the last matched call to fetch (or the - * last call to a specific route is matcherName is passed). - * @param [matcherName] either the name of a route or equal to - * matcher.toString() for any unnamed route - */ - lastOptions(matcherName?: string): MockRequest; - - /** - * Set some global config options, which include - * sendAsJson [default `true`] - by default fetchMock will - * convert objects to JSON before sending. This is overrideable - * for each call but for some scenarios, e.g. when dealing with a - * lot of array buffers, it can be useful to default to `false` - */ - configure(opts: {}): void; -} - -declare var fetchMock: FetchMockStatic; +declare var fetchMock: fetchMock.FetchMockStatic; export = fetchMock; From 40f37a17ddd46fff21969e471d9efb5f860238b3 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Sat, 8 Jul 2017 01:21:20 +0200 Subject: [PATCH 0238/1618] Add newly added option to DumpOptions --- types/js-yaml/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index d19f10a61c..37d817fb8c 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -51,6 +51,8 @@ declare namespace jsyaml { noRefs?: boolean; // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) noCompatMode?: boolean; + // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) + condenseFlow?: boolean; } export interface TypeConstructorOptions { From 6a01609d453864260da098f6871864590f023f49 Mon Sep 17 00:00:00 2001 From: tedbcsgpro Date: Fri, 7 Jul 2017 16:27:41 -0700 Subject: [PATCH 0239/1618] adds v4 history --- types/dropzone/v4/dropzone-tests.ts | 296 ++++++++++++++++++++++++++++ types/dropzone/v4/index.d.ts | 0 types/dropzone/v4/tsconfig.json | 26 +++ 3 files changed, 322 insertions(+) create mode 100644 types/dropzone/v4/dropzone-tests.ts create mode 100644 types/dropzone/v4/index.d.ts create mode 100644 types/dropzone/v4/tsconfig.json diff --git a/types/dropzone/v4/dropzone-tests.ts b/types/dropzone/v4/dropzone-tests.ts new file mode 100644 index 0000000000..3b56c0c50a --- /dev/null +++ b/types/dropzone/v4/dropzone-tests.ts @@ -0,0 +1,296 @@ +const dropzoneFromString = new Dropzone(".test"); +const dropzoneFromElement = new Dropzone(document.getElementById("test")); +const dropzoneRenameFunction = function (name:string):string { + return name + 'new'; +}; + +const dropzoneWithOptions = new Dropzone(".test", { + url: "/some/url", + method: "post", + withCredentials: false, + parallelUploads: 2, + uploadMultiple: true, + maxFilesize: 1024, + paramName: "file", + createImageThumbnails: true, + maxThumbnailFilesize: 1024, + thumbnailWidth: 50, + thumbnailHeight: 50, + filesizeBase: 1000, + maxFiles: 100, + params: { + additional: "param" + }, + headers: { + "Some-Header": "Value" + }, + clickable: true, + ignoreHiddenFiles: true, + acceptedFiles: "image/*", + renameFilename: dropzoneRenameFunction, + autoProcessQueue: true, + autoQueue: true, + addRemoveLinks: true, + previewsContainer: "
    ", + hiddenInputContainer: document.createElement("input"), + capture: "camera", + + dictDefaultMessage: "", + dictFallbackMessage: "", + dictFallbackText: "", + dictFileTooBig: "", + dictInvalidFileType: "", + dictResponseError: "", + dictCancelUpload: "", + dictCancelUploadConfirmation: "", + dictRemoveFile: "", + dictRemoveFileConfirmation: "", + dictMaxFilesExceeded: "", + + accept: (file:Dropzone.DropzoneFile, done:(error?:string|Error) => void) => { + if (file.accepted) { + file.previewElement.classList.add("accepted"); + file.previewTemplate.classList.add("accepted"); + file.previewsContainer.classList.add("accepted"); + done(); + } + else { + done(new Error(file.status)); + } + }, + init: () => console.log("Initialized"), + forceFallback: false, + fallback: () => console.log("Fallback"), + resize: (file:Dropzone.DropzoneFile) => ({ + srcX: 0, + srcY: 0, + trgX: 10, + trgY: 10, + srcWidth: 100, + srcHeight: 100, + trgWidth: 50, + trgHeight: 50, + optWidth: 50, + optHeight: 50 + }), + + drop: (e:DragEvent) => console.log("Drop"), + dragstart: (e:DragEvent) => console.log("Dragstart"), + dragend: (e:DragEvent) => console.log("Dragend"), + dragenter: (e:DragEvent) => console.log("Dragenter"), + dragover: (e:DragEvent) => console.log("Dragover"), + dragleave: (e:DragEvent) => console.log("Dragleave"), + paste: (e:DragEvent) => console.log("Paste"), + + reset: () => console.log("Reset"), + + addedfile: (file:Dropzone.DropzoneFile) => console.log("Addedfile"), + addedfiles: (files:Dropzone.DropzoneFile[]) => console.log("Addedfiles"), + removedfile: (file:Dropzone.DropzoneFile) => console.log("Removedfile"), + thumbnail: (file:Dropzone.DropzoneFile, dataUrl:string) => console.log("Thumbnail"), + + error: (file:Dropzone.DropzoneFile, message:string|Error) => console.log("Error"), + errormultiple: (files:Dropzone.DropzoneFile[], message:string|Error) => console.log("Errormultiple"), + + processing: (file:Dropzone.DropzoneFile) => console.log("Processing"), + processingmultiple: (files:Dropzone.DropzoneFile[]) => console.log("Processingmultiple"), + + uploadprogress: (file:Dropzone.DropzoneFile, progress:number, bytesSent:number) => console.log("Uploadprogress"), + totaluploadprogress: (totalProgress:number, totalBytes:number, totalBytesSent:number) => console.log("Totaluploadprogress"), + + sending: (file:Dropzone.DropzoneFile, xhr:XMLHttpRequest, formData:{}) => console.log("Sending"), + sendingmultiple: (files:Dropzone.DropzoneFile[], xhr:XMLHttpRequest, formData:{}) => console.log("Sendingmultiple"), + + success: (file:Dropzone.DropzoneFile) => console.log("Success"), + successmultiple: (files:Dropzone.DropzoneFile[]) => console.log("Successmultiple"), + + canceled: (file:Dropzone.DropzoneFile) => console.log("Canceled"), + canceledmultiple: (file:Dropzone.DropzoneFile[]) => console.log("Canceledmultiple"), + + complete: (file:Dropzone.DropzoneFile) => console.log("Complete"), + completemultiple: (file:Dropzone.DropzoneFile[]) => console.log("Completemultiple"), + + maxfilesexceeded: (file:Dropzone.DropzoneFile) => console.log("Maxfilesexceeded"), + maxfilesreached: (files:Dropzone.DropzoneFile[]) => console.log("Maxfilesreached"), + queuecomplete: () => console.log("Queuecomplete"), + + previewTemplate: "
    ", +}); + +var dropzoneWithOptionsVariations:Dropzone; +dropzoneWithOptionsVariations = new Dropzone(".test", { + clickable: ".test" +}); +dropzoneWithOptionsVariations = new Dropzone(".test", { + clickable: document.getElementById("test") +}); +dropzoneWithOptionsVariations = new Dropzone(".test", { + clickable: [".test", ".test"] +}); +dropzoneWithOptionsVariations = new Dropzone(".test", { + clickable: [document.getElementById("test"), document.getElementById("test")] +}); +dropzoneWithOptionsVariations = new Dropzone(".test", { + clickable: ["test", document.getElementById("test")] +}); + +dropzoneWithOptionsVariations = new Dropzone(".test", { + success: (file:Dropzone.DropzoneFile, response:Object) => console.log(file, response) +}); +dropzoneWithOptionsVariations = new Dropzone(".test", { + success: (file:Dropzone.DropzoneFile, response:string) => console.log(file, response) +}); + +const dropzone = new Dropzone(".test"); + +dropzone.enable(); +dropzone.disable(); + +dropzone.files.forEach(f => { + if (f.xhr) { + console.log(f.xhr.readyState) + } + if (f.accepted) { + f.previewElement.classList.add("accepted"); + f.previewTemplate.classList.add("accepted"); + f.previewsContainer.classList.add("accepted"); + } + else { + console.log(f.status.toUpperCase()); + } +}); + +const firstFile = dropzone.files[0]; +dropzone.removeFile(firstFile); +dropzone.addFile(firstFile); +dropzone.enqueueFile(firstFile); +dropzone.processFile(firstFile); +dropzone.uploadFile(firstFile); +dropzone.cancelUpload(firstFile); +dropzone.createThumbnail(firstFile, () => { + console.log("createThumbnail") +}); +dropzone.createThumbnailFromUrl(firstFile, "/some/url", () => { + console.log("createThumbnailFromUrl") +}); +dropzone.accept(firstFile, (e:string|Error) => { + console.log(e); +}); + +const acceptedFiles = dropzone.getAcceptedFiles(); +dropzone.processFiles(acceptedFiles); + +const rejectedFiles = dropzone.getRejectedFiles(); +dropzone.enqueueFiles(rejectedFiles); + +const queuedFiles = dropzone.getQueuedFiles(); +dropzone.processFiles(queuedFiles); + +const uploadingFiles = dropzone.getUploadingFiles(); +dropzone.processFiles(uploadingFiles); + +const activeFiles = dropzone.getActiveFiles(); +dropzone.processFiles(activeFiles); + +const addedFiles = dropzone.getFilesWithStatus(Dropzone.ADDED); +dropzone.processFiles(addedFiles); + +dropzone.processQueue(); +dropzone.removeAllFiles(true); + +dropzone + .on("drop", () => { + console.count('drop'); + }) + .on("dragstart", () => { + console.count('dragstart'); + }) + .on("dragend", () => { + console.count('dragend'); + }) + .on("dragenter", () => { + console.count('dragenter'); + }) + .on("dragover", () => { + console.count('dragover'); + }) + .on("dragleave", () => { + console.count('dragleave'); + }) + .on("paste", () => { + console.count('paste'); + }) + .on("reset", () => { + console.count('reset'); + }) + .on("addedfile", () => { + console.count('addedfile'); + }) + .on("addedfiles", () => { + console.count('addedfiles'); + }) + .on("removedfile", () => { + console.count('removedfile'); + }) + .on("thumbnail", () => { + console.count('thumbnail'); + }) + .on("error", () => { + console.count('error'); + }) + .on("errormultiple", () => { + console.count('errormultiple'); + }) + .on("processing", () => { + console.count('processing'); + }) + .on("processingmultiple", () => { + console.count('processingmultiple'); + }) + .on("uploadprogress", () => { + console.count('uploadprogress'); + }) + .on("totaluploadprogress", () => { + console.count('totaluploadprogress'); + }) + .on("sending", () => { + console.count('sending'); + }) + .on("sendingmultiple", () => { + console.count('sendingmultiple'); + }) + .on("success", () => { + console.count('success'); + }) + .on("successmultiple", () => { + console.count('successmultiple'); + }) + .on("canceled", () => { + console.count('canceled'); + }) + .on("canceledmultiple", () => { + console.count('canceledmultiple'); + }) + .on("complete", () => { + console.count('complete'); + }) + .on("completemultiple", () => { + console.count('completemultiple'); + }) + .on("maxfilesexceeded", () => { + console.count('maxfilesexceeded'); + }) + .on("maxfilesreached", () => { + console.count('maxfilesreached'); + }) + .on("queuecomplete", () => { + console.count('queuecomplete'); + }); + + dropzone.off("drop", () => { + console.count('drop'); + }) + .off("dragstart") + .off(); + +dropzone.destroy(); \ No newline at end of file diff --git a/types/dropzone/v4/index.d.ts b/types/dropzone/v4/index.d.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/dropzone/v4/tsconfig.json b/types/dropzone/v4/tsconfig.json new file mode 100644 index 0000000000..10f2d83747 --- /dev/null +++ b/types/dropzone/v4/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "history": ["history/v4"] + } + }, + "files": [ + "index.d.ts", + "dropzone-tests.ts" + ] +} \ No newline at end of file From 0e36eefc5fefe53784a5062666f4d818f676d930 Mon Sep 17 00:00:00 2001 From: Daniel Perez Alvarez Date: Fri, 7 Jul 2017 14:29:12 -0700 Subject: [PATCH 0240/1618] Update types for auto-launch v5.0.1 --- types/auto-launch/auto-launch-tests.ts | 35 ++++++------- types/auto-launch/index.d.ts | 72 ++++++++++++++------------ types/auto-launch/tsconfig.json | 4 +- types/auto-launch/tslint.json | 1 + 4 files changed, 59 insertions(+), 53 deletions(-) create mode 100644 types/auto-launch/tslint.json diff --git a/types/auto-launch/auto-launch-tests.ts b/types/auto-launch/auto-launch-tests.ts index ae6ace9620..af141358bd 100644 --- a/types/auto-launch/auto-launch-tests.ts +++ b/types/auto-launch/auto-launch-tests.ts @@ -1,24 +1,23 @@ - - import AutoLaunch = require('auto-launch'); -var a1 = new AutoLaunch({ - name: 'Foo', +const minecraftAutoLauncher = new AutoLaunch({ + name: 'Minecraft', + path: '/Applications/Minecraft.app', + mac: { + useLaunchAgent: true + } }); -var a2 = new AutoLaunch({ - name: 'Foo', - path: '/Applications/Foo.app', - isHidden: true, -}); +minecraftAutoLauncher.enable(); +minecraftAutoLauncher.disable(); -a1.enable(); -a2.disable(); - -a1.isEnabled(function(enabled: boolean) { - if (enabled) { - return; +minecraftAutoLauncher.isEnabled() + .then((isEnabled) => { + if (isEnabled) { + return; } - - a1.enable(function(err){ console.log(err.message); }); -}); + minecraftAutoLauncher.enable(); + }) + .catch((err) => { + console.error(err); + }); diff --git a/types/auto-launch/index.d.ts b/types/auto-launch/index.d.ts index 8a6af4e5dd..1ea4fcc25a 100644 --- a/types/auto-launch/index.d.ts +++ b/types/auto-launch/index.d.ts @@ -1,41 +1,47 @@ -// Type definitions for auto-launch 0.1.18 +// Type definitions for auto-launch 5.0 // Project: https://github.com/Teamwork/node-auto-launch -// Definitions by: rhysd +// Definitions by: rhysd , Daniel Perez Alvarez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface AutoLaunchOption { - /** - * Application name. - */ - name: string; - /** - * Hidden on launch or not. Default is false. - */ - isHidden?: boolean; - /** - * Path to application directory. - * Default is process.execPath. - */ - path?: string; +interface AutoLaunchOptions { + /** + * Application name. + */ + name: string; + /** + * Path to application. Default is `process.execPath`. + */ + path?: string; + /** + * Hidden on launch. Default is `false`. + */ + isHidden?: boolean; + /** + * For Mac-only options. + */ + mac?: { + /** + * By default, AppleScript is used to add a Login Item. If this is `true`, Launch Agent will be used to auto-launch your app. Defaults is `false`. + */ + useLaunchAgent?: boolean; + }; } declare class AutoLaunch { - constructor(opts: AutoLaunchOption); - /** - * Enables to launch at start up - */ - enable(callback?: (err: Error) => void): void; - /** - * Disables to launch at start up - */ - disable(callback?: (err: Error) => void): void; - /** - * Returns if auto start up is enabled - */ - isEnabled(callback: (enabled: boolean) => void): void; + constructor(options: AutoLaunchOptions); + + /** + * Enables auto-launch at start up. + */ + enable(): Promise; + /** + * Disables auto-launch at start up. + */ + disable(): Promise; + /** + * Returns true if auto-launch is enabled. + */ + isEnabled(): Promise; } -declare module "auto-launch" { - var al: typeof AutoLaunch; - export = al; -} +export = AutoLaunch; diff --git a/types/auto-launch/tsconfig.json b/types/auto-launch/tsconfig.json index 2200ea7a60..ba69bba12b 100644 --- a/types/auto-launch/tsconfig.json +++ b/types/auto-launch/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "index.d.ts", "auto-launch-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/auto-launch/tslint.json b/types/auto-launch/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/auto-launch/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f2ed9c9e73baef98be989bbebbecd291975952cb Mon Sep 17 00:00:00 2001 From: tedbcsgpro Date: Fri, 7 Jul 2017 16:40:08 -0700 Subject: [PATCH 0241/1618] attempt 1 to fix Travis CI build errors --- .../{dropzone-tests.ts => history-tests.ts} | 0 types/dropzone/v4/index.d.ts | 279 ++++++++++++++++++ types/dropzone/v4/tsconfig.json | 2 +- 3 files changed, 280 insertions(+), 1 deletion(-) rename types/dropzone/v4/{dropzone-tests.ts => history-tests.ts} (100%) diff --git a/types/dropzone/v4/dropzone-tests.ts b/types/dropzone/v4/history-tests.ts similarity index 100% rename from types/dropzone/v4/dropzone-tests.ts rename to types/dropzone/v4/history-tests.ts diff --git a/types/dropzone/v4/index.d.ts b/types/dropzone/v4/index.d.ts index e69de29bb2..171552a240 100644 --- a/types/dropzone/v4/index.d.ts +++ b/types/dropzone/v4/index.d.ts @@ -0,0 +1,279 @@ +// Type definitions for Dropzone 4.3.0 +// Project: http://www.dropzonejs.com/ +// Definitions by: Natan Vivo , Andy Hawkins , Vasya Aksyonov , Simon Huber , Sebastiaan de Rooij +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import * as $ from "jquery"; + +declare namespace Dropzone { + export interface DropzoneResizeInfo { + srcX?:number; + srcY?:number; + trgX?:number; + trgY?:number; + srcWidth?:number; + srcHeight?:number; + trgWidth?:number; + trgHeight?:number; + optWidth?:number; + optHeight?:number; + } + + export interface DropzoneFile extends File { + previewElement: HTMLElement; + previewTemplate: HTMLElement; + previewsContainer: HTMLElement; + status: string; + accepted: boolean; + xhr?: XMLHttpRequest; + } + + export interface DropzoneOptions { + url?: string; + method?: string; + withCredentials?: boolean; + parallelUploads?: number; + uploadMultiple?: boolean; + maxFilesize?: number; + paramName?: string; + createImageThumbnails?: boolean; + maxThumbnailFilesize?: number; + thumbnailWidth?: number; + thumbnailHeight?: number; + filesizeBase?: number; + maxFiles?: number; + params?: {}; + headers?: {}; + clickable?: boolean|string|HTMLElement|(string|HTMLElement)[]; + ignoreHiddenFiles?: boolean; + acceptedFiles?: string; + renameFilename?(name:string): string; + autoProcessQueue?: boolean; + autoQueue?: boolean; + addRemoveLinks?: boolean; + previewsContainer?: boolean|string|HTMLElement; + hiddenInputContainer?: HTMLElement; + capture?: string; + + dictDefaultMessage?: string; + dictFallbackMessage?: string; + dictFallbackText?: string; + dictFileTooBig?: string; + dictInvalidFileType?: string; + dictResponseError?: string; + dictCancelUpload?: string; + dictCancelUploadConfirmation?: string; + dictRemoveFile?: string; + dictRemoveFileConfirmation?: string; + dictMaxFilesExceeded?: string; + + accept?(file:DropzoneFile, done:(error?:string|Error) => void):void; + init?():void; + forceFallback?: boolean; + fallback?():void; + resize?(file:DropzoneFile):DropzoneResizeInfo; + + drop?(e:DragEvent):void; + dragstart?(e:DragEvent):void; + dragend?(e:DragEvent):void; + dragenter?(e:DragEvent):void; + dragover?(e:DragEvent):void; + dragleave?(e:DragEvent):void; + paste?(e:DragEvent):void; + + reset?():void; + + addedfile?(file:DropzoneFile):void; + addedfiles?(files:DropzoneFile[]):void; + removedfile?(file:DropzoneFile):void; + thumbnail?(file:DropzoneFile, dataUrl:string):void; + + error?(file:DropzoneFile, message:string|Error, xhr:XMLHttpRequest):void; + errormultiple?(files:DropzoneFile[], message:string|Error, xhr:XMLHttpRequest):void; + + processing?(file:DropzoneFile):void; + processingmultiple?(files:DropzoneFile[]):void; + + uploadprogress?(file:DropzoneFile, progress:number, bytesSent:number):void; + totaluploadprogress?(totalProgress:number, totalBytes:number, totalBytesSent:number):void; + + sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; + + success?(file: DropzoneFile, response: Object|string): void; + successmultiple?(files:DropzoneFile[], responseText:string):void; + + canceled?(file:DropzoneFile):void; + canceledmultiple?(file:DropzoneFile[]):void; + + complete?(file:DropzoneFile):void; + completemultiple?(file:DropzoneFile[]):void; + + maxfilesexceeded?(file:DropzoneFile):void; + maxfilesreached?(files:DropzoneFile[]):void; + queuecomplete?():void; + + previewTemplate?: string; + } +} + +declare class Dropzone { + constructor(container:string|HTMLElement, options?:Dropzone.DropzoneOptions); + + static autoDiscover:boolean; + static options:any; + static confirm:(question:string, accepted:() => void, rejected?:() => void) => void; + + static ADDED:string; + static QUEUED:string; + static ACCEPTED:string; + static UPLOADING:string; + static PROCESSING:string; + static CANCELED:string; + static ERROR:string; + static SUCCESS:string; + + files:Dropzone.DropzoneFile[]; + + enable():void; + + disable():void; + + destroy():Dropzone; + + addFile(file:Dropzone.DropzoneFile):void; + + removeFile(file:Dropzone.DropzoneFile):void; + + removeAllFiles(cancelIfNecessary?:boolean):void; + + processQueue():void; + + cancelUpload(file:Dropzone.DropzoneFile):void; + + processFiles(files:Dropzone.DropzoneFile[]):void; + + processFile(file:Dropzone.DropzoneFile):void; + + uploadFile(file:Dropzone.DropzoneFile):void; + + getAcceptedFiles():Dropzone.DropzoneFile[]; + + getRejectedFiles():Dropzone.DropzoneFile[]; + + getQueuedFiles():Dropzone.DropzoneFile[]; + + getUploadingFiles():Dropzone.DropzoneFile[]; + + accept(file:Dropzone.DropzoneFile, done:(error?:string|Error) => void):void; + + getActiveFiles():Dropzone.DropzoneFile[]; + + getFilesWithStatus(status:string):Dropzone.DropzoneFile[]; + + enqueueFile(file:Dropzone.DropzoneFile):void; + + enqueueFiles(file:Dropzone.DropzoneFile[]):void; + + createThumbnail(file:Dropzone.DropzoneFile, callback?:(...args:any[]) => void):any; + + createThumbnailFromUrl(file:Dropzone.DropzoneFile, url:string, callback?:(...args:any[]) => void):any; + + on(eventName:string, callback:(...args:any[]) => void):Dropzone; + + off(): Dropzone; + off(eventName:string, callback?:(...args:any[]) => void):Dropzone; + + emit(eventName:string, ...args:any[]):Dropzone; + + on(eventName:"drop", callback:(e:DragEvent) => any):Dropzone; + on(eventName:"dragstart", callback:(e:DragEvent) => any):Dropzone; + on(eventName:"dragend", callback:(e:DragEvent) => any):Dropzone; + on(eventName:"dragenter", callback:(e:DragEvent) => any):Dropzone; + on(eventName:"dragover", callback:(e:DragEvent) => any):Dropzone; + on(eventName:"dragleave", callback:(e:DragEvent) => any):Dropzone; + on(eventName:"paste", callback:(e:DragEvent) => any):Dropzone; + + on(eventName:"reset"):Dropzone; + + on(eventName:"addedfile", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; + on(eventName:"addedfiles", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; + on(eventName:"removedfile", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; + on(eventName:"thumbnail", callback:(file:Dropzone.DropzoneFile, dataUrl:string) => any):Dropzone; + + on(eventName:"error", callback:(file:Dropzone.DropzoneFile, message:string|Error) => any):Dropzone; + on(eventName:"errormultiple", callback:(files:Dropzone.DropzoneFile[], message:string|Error) => any):Dropzone; + + on(eventName:"processing", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; + on(eventName:"processingmultiple", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; + + on(eventName:"uploadprogress", callback:(file:Dropzone.DropzoneFile, progress:number, bytesSent:number) => any):Dropzone; + on(eventName:"totaluploadprogress", callback:(totalProgress:number, totalBytes:number, totalBytesSent:number) => any):Dropzone; + + on(eventName:"sending", callback:(file:Dropzone.DropzoneFile, xhr:XMLHttpRequest, formData:FormData) => any):Dropzone; + on(eventName:"sendingmultiple", callback:(files:Dropzone.DropzoneFile[], xhr:XMLHttpRequest, formData:FormData) => any):Dropzone; + + on(eventName:"success", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; + on(eventName:"successmultiple", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; + + on(eventName:"canceled", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; + on(eventName:"canceledmultiple", callback:(file:Dropzone.DropzoneFile[]) => any):Dropzone; + + on(eventName:"complete", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; + on(eventName:"completemultiple", callback:(file:Dropzone.DropzoneFile[]) => any):Dropzone; + + on(eventName:"maxfilesexceeded", callback:(file:Dropzone.DropzoneFile) => any):Dropzone; + on(eventName:"maxfilesreached", callback:(files:Dropzone.DropzoneFile[]) => any):Dropzone; + on(eventName:"queuecomplete"):Dropzone; + + emit(eventName:"drop", e:DragEvent):Dropzone; + emit(eventName:"dragstart", e:DragEvent):Dropzone; + emit(eventName:"dragend", e:DragEvent):Dropzone; + emit(eventName:"dragenter", e:DragEvent):Dropzone; + emit(eventName:"dragover", e:DragEvent):Dropzone; + emit(eventName:"dragleave", e:DragEvent):Dropzone; + emit(eventName:"paste", e:DragEvent):Dropzone; + + emit(eventName:"reset"):Dropzone; + + emit(eventName:"addedfile", file:Dropzone.DropzoneFile):Dropzone; + emit(eventName:"addedfiles", files:Dropzone.DropzoneFile[]):Dropzone; + emit(eventName:"removedfile", file:Dropzone.DropzoneFile):Dropzone; + emit(eventName:"thumbnail", file:Dropzone.DropzoneFile, dataUrl:string):Dropzone; + + emit(eventName:"error", file:Dropzone.DropzoneFile, message:string|Error):Dropzone; + emit(eventName:"errormultiple", files:Dropzone.DropzoneFile[], message:string|Error):Dropzone; + + emit(eventName:"processing", file:Dropzone.DropzoneFile):Dropzone; + emit(eventName:"processingmultiple", files:Dropzone.DropzoneFile[]):Dropzone; + + emit(eventName:"uploadprogress", file:Dropzone.DropzoneFile, progress:number, bytesSent:number):Dropzone; + emit(eventName:"totaluploadprogress", totalProgress:number, totalBytes:number, totalBytesSent:number):Dropzone; + + emit(eventName:"sending", file:Dropzone.DropzoneFile, xhr:XMLHttpRequest, formData:FormData):Dropzone; + emit(eventName:"sendingmultiple", files:Dropzone.DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):Dropzone; + + emit(eventName:"success", file:Dropzone.DropzoneFile):Dropzone; + emit(eventName:"successmultiple", files:Dropzone.DropzoneFile[]):Dropzone; + + emit(eventName:"canceled", file:Dropzone.DropzoneFile):Dropzone; + emit(eventName:"canceledmultiple", file:Dropzone.DropzoneFile[]):Dropzone; + + emit(eventName:"complete", file:Dropzone.DropzoneFile):Dropzone; + emit(eventName:"completemultiple", file:Dropzone.DropzoneFile[]):Dropzone; + + emit(eventName:"maxfilesexceeded", file:Dropzone.DropzoneFile):Dropzone; + emit(eventName:"maxfilesreached", files:Dropzone.DropzoneFile[]):Dropzone; + emit(eventName:"queuecomplete"):Dropzone; + +} + +interface JQuery { + dropzone(options:Dropzone.DropzoneOptions): Dropzone; +} + +export = Dropzone; +export as namespace Dropzone; \ No newline at end of file diff --git a/types/dropzone/v4/tsconfig.json b/types/dropzone/v4/tsconfig.json index 10f2d83747..5c818e33c5 100644 --- a/types/dropzone/v4/tsconfig.json +++ b/types/dropzone/v4/tsconfig.json @@ -21,6 +21,6 @@ }, "files": [ "index.d.ts", - "dropzone-tests.ts" + "history-tests.ts" ] } \ No newline at end of file From e91d21d658d20f73ea6f278a3b42a7a4500cb74b Mon Sep 17 00:00:00 2001 From: Daniel Perez Alvarez Date: Fri, 7 Jul 2017 16:45:04 -0700 Subject: [PATCH 0242/1618] Add types for electron-store 1.2 --- types/electron-store/electron-store-tests.ts | 34 +++++++++ types/electron-store/index.d.ts | 79 ++++++++++++++++++++ types/electron-store/tsconfig.json | 22 ++++++ types/electron-store/tslint.json | 7 ++ 4 files changed, 142 insertions(+) create mode 100644 types/electron-store/electron-store-tests.ts create mode 100644 types/electron-store/index.d.ts create mode 100644 types/electron-store/tsconfig.json create mode 100644 types/electron-store/tslint.json diff --git a/types/electron-store/electron-store-tests.ts b/types/electron-store/electron-store-tests.ts new file mode 100644 index 0000000000..61d74d6f18 --- /dev/null +++ b/types/electron-store/electron-store-tests.ts @@ -0,0 +1,34 @@ +import ElectronStore = require('electron-store'); + +new ElectronStore({ + defaults: {} +}); + +new ElectronStore({ + name: 'myConfiguration', + cwd: 'unicorn' +}); + +const electronStore = new ElectronStore(); + +electronStore.set('foo', 'bar'); +electronStore.set({ + foo: 'bar', + foo2: 'bar2' +}); +electronStore.delete('foo'); +electronStore.get('foo'); +electronStore.get('foo', 42); +electronStore.has('foo'); +electronStore.clear(); + +electronStore.openInEditor(); + +electronStore.size; +electronStore.store; + +electronStore.store = { + foo: 'bar' +}; + +electronStore.path; diff --git a/types/electron-store/index.d.ts b/types/electron-store/index.d.ts new file mode 100644 index 0000000000..e270fb2b8e --- /dev/null +++ b/types/electron-store/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for electron-store 1.2 +// Project: https://github.com/sindresorhus/electron-store +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface ElectronStoreOptions { + /** + * Default config. + */ + defaults?: {}; + + /** + * Name of the config file (without extension). + */ + name?: string; + + /** + * Storage file location. *Don't specify this unless absolutely necessary!* + */ + cwd?: string; +} + +declare class ElectronStore implements Iterable<[string, string | number | boolean | symbol | {}]> { + constructor(options?: ElectronStoreOptions); + + /** + * Sets an item. + */ + set(key: string, value: any): void; + + /** + * Sets multiple items at once. + */ + set(object: {}): void; + + /** + * Retrieves an item. + */ + get(key: string, defaultValue?: any): any; + + /** + * Checks if an item exists. + */ + has(key: string): boolean; + + /** + * Deletes an item. + */ + delete(key: string): void; + + /** + * Deletes all items. + */ + clear(): void; + + /** + * Open the storage file in the user's editor. + */ + openInEditor(): void; + + /** + * Gets the item count. + */ + size: number; + + /** + * Gets all the config as an object or replace the current config with an object. + */ + store: {}; + + /** + * Gets the path to the config file. + */ + path: string; + + [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; +} + +export = ElectronStore; diff --git a/types/electron-store/tsconfig.json b/types/electron-store/tsconfig.json new file mode 100644 index 0000000000..311e831103 --- /dev/null +++ b/types/electron-store/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "electron-store-tests.ts" + ] +} diff --git a/types/electron-store/tslint.json b/types/electron-store/tslint.json new file mode 100644 index 0000000000..e830836d23 --- /dev/null +++ b/types/electron-store/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json" , + "rules": { + "no-namespace":false, + "object-literal-key-quotes": false + } +} From 04a8ccaf652baaac4f30f5d17fb2bad29ecbd893 Mon Sep 17 00:00:00 2001 From: Andre Wiggins Date: Fri, 7 Jul 2017 16:52:27 -0700 Subject: [PATCH 0243/1618] Add gulp-connect typings --- types/gulp-connect/gulp-connect-tests.ts | 120 +++++++++++++++++++++++ types/gulp-connect/index.d.ts | 76 ++++++++++++++ types/gulp-connect/tsconfig.json | 22 +++++ types/gulp-connect/tslint.json | 1 + 4 files changed, 219 insertions(+) create mode 100644 types/gulp-connect/gulp-connect-tests.ts create mode 100644 types/gulp-connect/index.d.ts create mode 100644 types/gulp-connect/tsconfig.json create mode 100644 types/gulp-connect/tslint.json diff --git a/types/gulp-connect/gulp-connect-tests.ts b/types/gulp-connect/gulp-connect-tests.ts new file mode 100644 index 0000000000..03722a4c15 --- /dev/null +++ b/types/gulp-connect/gulp-connect-tests.ts @@ -0,0 +1,120 @@ +// Copying examples from Readme which currently depend on gulp v3 +import * as gulp from 'gulp/v3'; +import * as connect from 'gulp-connect'; + +// Simple example +gulp.task('connect', () => { + connect.server(); +}); + +gulp.task('default', ['connect']); + +// LiveReload +gulp.task('connect', () => { + connect.server({ + root: 'app', + livereload: true + }); +}); + +gulp.task('html', () => { + gulp.src('./app/*.html') + .pipe(connect.reload()); +}); + +gulp.task('watch', () => { + gulp.watch(['./app/*.html'], ['html']); +}); + +gulp.task('default', ['connect', 'watch']); + +// Start and stop server +gulp.task('jenkins-tests', () => { + connect.server({ + port: 8888 + }); + // run some headless tests with phantomjs + // when process exits: + connect.serverClose(); +}); + +// Multiple server +gulp.task('connectDev', () => { + connect.server({ + name: 'Dev App', + root: ['app', 'tmp'], + port: 8000, + livereload: true + }); +}); + +gulp.task('connectDist', () => { + connect.server({ + name: 'Dist App', + root: 'dist', + port: 8001, + livereload: true + }); +}); + +gulp.task('html', () => { + gulp.src('./app/*.html') + .pipe(connect.reload()); +}); + +gulp.task('stylus', () => { + gulp.src('./app/stylus/*.styl') + // .pipe(stylus()) // just here for demonstration purposes + .pipe(gulp.dest('./app/css')) + .pipe(connect.reload()); +}); + +gulp.task('watch', () => { + gulp.watch(['./app/*.html'], ['html']); + gulp.watch(['./app/stylus/*.styl'], ['stylus']); +}); + +gulp.task('default', ['connectDist', 'connectDev', 'watch']); + +// Barebones middleware example from Readme +gulp.task('connect', () => { + connect.server({ + root: "app", + middleware(connect, opt) { + return []; + } + }); +}); + +// The following tests are custom tests to validate the more complicated APIs + +// Validate gulp-connect typings allow express apps to be passed in as middleware +import * as express from "express"; + +gulp.task('connect', () => { + let middleware = [ + express() + ]; + + return connect.server({ + root: [__dirname], + port: 8081, + livereload: true, + middleware: (connect, opt) => middleware + }); +}); + +// Validate using paths to restrict handler functions works +gulp.task('connect', () => { + let middleware: connect.ConnectRouteHandler[] = [ + ["/path", express()], + ["/path2", express()], + ]; + + return connect.server({ + root: [__dirname], + port: 8081, + livereload: true, + middleware: (connect, opt) => middleware + }); +}); diff --git a/types/gulp-connect/index.d.ts b/types/gulp-connect/index.d.ts new file mode 100644 index 0000000000..f023c2bff1 --- /dev/null +++ b/types/gulp-connect/index.d.ts @@ -0,0 +1,76 @@ +// Type definitions for gulp-connect 5.0 +// Project: https://github.com/avevlad/gulp-connect#readme +// Definitions by: Andre Wiggins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as http from "http"; +import * as https from "https"; +import * as connectModule from "connect"; + +export interface LiveReloadOptions { + /** Port to run live reload server on. Defauls to 35729. */ + port: number; + + /** Hostname to bind live reload server to */ + hostname?: string; +} + +/** a list of [string, HandlerFunction] where the string is the path (i.e. route) that the handler function should be invoked for */ +export type ConnectRouteHandler = [ string, connectModule.HandleFunction ]; + +/** + * Factory function that returns a list of middleware handlers to pass to a connect server's use function. + * The list contain normal Connect middleware handler functions or ConnectRoutHandlers + */ +export type MiddlewareFactory = (connect: typeof connectModule, options: ConnectAppOptions) => Array; + +export interface ConnectAppOptions { + /** The name of this server. Used in logs. Defaults to "Server". */ + name?: string; + + /** The root path. Defaults to directory with gulpfile */ + root?: string | string[]; + + /** The connect webserver port. Defaults to 8080 */ + port?: number; + + /** Host to bind server to. Defaults to localhost. */ + host?: string; + + /** Don't log any messages. Defaults to false. */ + slient?: boolean; + + /** + * Options to pass to http.createServer (or false to disable https). + * Defaults to false. When https is just set to true, then internally + * some defaults will be used. + */ + https?: boolean | https.ServerOptions; + + /** Enable/disable livereload or set live reload options. Defaults to false. */ + livereload?: boolean | LiveReloadOptions; + + /** A function to run custom initialization on the underlying http or https server */ + serverInit?(server: http.Server | https.Server): void; + + /** File to serve if url results in a 404. Defaults to undefined */ + fallback?: string; + + /** Middleware factory function which should return a list of connect handler functions . Defaults to () => []; */ + middleware?: MiddlewareFactory; + + /** Whether or not to log debug messages. Defaults to false. */ + debug?: boolean; + + /** Value to pass into the serve-static's index option. See serve-static documentation for details. Defaults to true. */ + index?: boolean | string | string[]; +} + +/** Create a gulp-connect server with the given options */ +export function server(options?: ConnectAppOptions): ConnectAppOptions; + +/** Reload all gulp-connect servers that have livereload enabled */ +export function reload(): any; + +/** Close all gulp-connect servers */ +export function serverClose(): void; diff --git a/types/gulp-connect/tsconfig.json b/types/gulp-connect/tsconfig.json new file mode 100644 index 0000000000..750605f81f --- /dev/null +++ b/types/gulp-connect/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-connect-tests.ts" + ] +} diff --git a/types/gulp-connect/tslint.json b/types/gulp-connect/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-connect/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 203ec964fda0d7dbd9897c2c53caa6f45073cf14 Mon Sep 17 00:00:00 2001 From: Daniel Perez Alvarez Date: Fri, 7 Jul 2017 16:57:31 -0700 Subject: [PATCH 0244/1618] Add types for nslog 3.0 --- types/nslog/index.d.ts | 12 ++++++++++++ types/nslog/nslog-tests.ts | 4 ++++ types/nslog/tsconfig.json | 22 ++++++++++++++++++++++ types/nslog/tslint.json | 1 + 4 files changed, 39 insertions(+) create mode 100644 types/nslog/index.d.ts create mode 100644 types/nslog/nslog-tests.ts create mode 100644 types/nslog/tsconfig.json create mode 100644 types/nslog/tslint.json diff --git a/types/nslog/index.d.ts b/types/nslog/index.d.ts new file mode 100644 index 0000000000..e351c8117d --- /dev/null +++ b/types/nslog/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for nslog 3.0 +// Project: https://github.com/atom/node-nslog +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Outputs a message to the native console. + */ +type NSLog = (...args: any[]) => void; + +declare var nslog: NSLog; +export = nslog; diff --git a/types/nslog/nslog-tests.ts b/types/nslog/nslog-tests.ts new file mode 100644 index 0000000000..3a80c5a13b --- /dev/null +++ b/types/nslog/nslog-tests.ts @@ -0,0 +1,4 @@ +import NSLog = require('nslog'); + +NSLog('Hello world!'); +NSLog('My number is %i and my text is %s.', 42, 'foobar'); diff --git a/types/nslog/tsconfig.json b/types/nslog/tsconfig.json new file mode 100644 index 0000000000..885e4f0dc0 --- /dev/null +++ b/types/nslog/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "nslog-tests.ts" + ] +} diff --git a/types/nslog/tslint.json b/types/nslog/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/nslog/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3e76717ca119b83d3cb7d6cd25cfdb785045b3de Mon Sep 17 00:00:00 2001 From: tedbcsgpro Date: Fri, 7 Jul 2017 17:06:40 -0700 Subject: [PATCH 0245/1618] fixes test errors --- types/dropzone/v4/{history-tests.ts => dropzone-tests.ts} | 0 types/dropzone/v4/tsconfig.json | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename types/dropzone/v4/{history-tests.ts => dropzone-tests.ts} (100%) diff --git a/types/dropzone/v4/history-tests.ts b/types/dropzone/v4/dropzone-tests.ts similarity index 100% rename from types/dropzone/v4/history-tests.ts rename to types/dropzone/v4/dropzone-tests.ts diff --git a/types/dropzone/v4/tsconfig.json b/types/dropzone/v4/tsconfig.json index 5c818e33c5..36eb5f0aef 100644 --- a/types/dropzone/v4/tsconfig.json +++ b/types/dropzone/v4/tsconfig.json @@ -16,11 +16,11 @@ "noEmit": true, "forceConsistentCasingInFileNames": true, "paths": { - "history": ["history/v4"] + "dropzone": ["dropzone/v4"] } }, "files": [ "index.d.ts", - "history-tests.ts" + "dropzone-tests.ts" ] } \ No newline at end of file From 55fd3f7c86a08184f9016da44209d4f59485da0b Mon Sep 17 00:00:00 2001 From: Dolan Date: Sat, 8 Jul 2017 01:11:05 +0100 Subject: [PATCH 0246/1618] Initial commit --- types/google-images/google-images-tests.ts | 27 ++++++++++++++++++++++ types/google-images/index.d.ts | 12 ++++++++++ types/google-images/tsconfig.json | 22 ++++++++++++++++++ types/google-images/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/google-images/google-images-tests.ts create mode 100644 types/google-images/index.d.ts create mode 100644 types/google-images/tsconfig.json create mode 100644 types/google-images/tslint.json diff --git a/types/google-images/google-images-tests.ts b/types/google-images/google-images-tests.ts new file mode 100644 index 0000000000..b50e8f2ac1 --- /dev/null +++ b/types/google-images/google-images-tests.ts @@ -0,0 +1,27 @@ +import * as GoogleImages from "google-images"; + +const client = new GoogleImages('CSE ID', 'API KEY'); + +client.search('Steve Angello') + .then(images => { + /* + [{ + "url": "http://steveangello.com/boss.jpg", + "type": "image/jpeg", + "width": 1024, + "height": 768, + "size": 102451, + "thumbnail": { + "url": "http://steveangello.com/thumbnail.jpg", + "width": 512, + "height": 512 + } + }] + */ + }); + +// paginate results +client.search('Steve Angello', {page: 2}); + +// search for certain size +client.search('Steve Angello', {size: 'large'}); diff --git a/types/google-images/index.d.ts b/types/google-images/index.d.ts new file mode 100644 index 0000000000..eceb0ca445 --- /dev/null +++ b/types/google-images/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for google-images 1.2 +// Project: https://github.com/beatgammit/base64-js +// Definitions by: Dolan Miu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace GoogleImages { + interface GoogleImages { + + } +} + +export = GoogleImages; diff --git a/types/google-images/tsconfig.json b/types/google-images/tsconfig.json new file mode 100644 index 0000000000..692c9ac5a5 --- /dev/null +++ b/types/google-images/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google-images-tests.ts" + ] +} diff --git a/types/google-images/tslint.json b/types/google-images/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-images/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From aa41e744cffe27d462f4e9a124d7649060f4c381 Mon Sep 17 00:00:00 2001 From: nearbydelta Date: Sat, 8 Jul 2017 10:36:34 +0900 Subject: [PATCH 0247/1618] Revised: Class BarNote has new constructor - rollback: constructor in class Note. - creation: constructor() in class BarNote. --- types/vexflow/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/vexflow/index.d.ts b/types/vexflow/index.d.ts index 873e6cc044..01c8d75381 100644 --- a/types/vexflow/index.d.ts +++ b/types/vexflow/index.d.ts @@ -187,6 +187,7 @@ declare namespace Vex { class BarNote extends Note { static DEBUG : boolean; + constructor(); getType() : Barline.type; setType(type : Barline.type) : BarNote; getBoundingBox() : BoundingBox; @@ -619,7 +620,7 @@ declare namespace Vex { applyTickMultiplier(numerator : number, denominator : number) : void; setDuration(duration : Fraction) : void; - constructor(note_struct? : {type? : string, dots? : number, duration : string}); + constructor(note_struct : {type? : string, dots? : number, duration : string}); getPlayNote() : any; setPlayNote(note : any) : Note; isRest() : boolean; From 465a604e475c4f4c743de2682615abf73bdab9c5 Mon Sep 17 00:00:00 2001 From: "Adrian (Grim) Roach" Date: Fri, 7 Jul 2017 21:17:02 -0700 Subject: [PATCH 0248/1618] Update index.d.ts --- types/ebongarde-root/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/ebongarde-root/index.d.ts b/types/ebongarde-root/index.d.ts index bd9563f991..c83037744b 100644 --- a/types/ebongarde-root/index.d.ts +++ b/types/ebongarde-root/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for ebongarde-root 1.7 // Project: https://github.com/Ebongarde/ebongarde-root#readme -// Definitions by: My Self +// Definitions by: Adrian Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 3cc29a7e3609e40a0c982513387a0e12d226b439 Mon Sep 17 00:00:00 2001 From: kepennar Date: Sat, 8 Jul 2017 12:17:51 +0200 Subject: [PATCH 0249/1618] Add GraphQL Subscription type definition --- types/graphql/index.d.ts | 5 ++-- types/graphql/subscription/index.d.ts | 1 + types/graphql/subscription/subscribe.d.ts | 29 +++++++++++++++++++++++ types/graphql/tsconfig.json | 4 ++-- 4 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 types/graphql/subscription/index.d.ts create mode 100644 types/graphql/subscription/subscribe.d.ts diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index de2a1405e6..f6c9750723 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for graphql 0.9 +// Type definitions for graphql 0.10 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang , Caleb Meredith , Dominic Watson , Firede +// Definitions by: TonyYang , Caleb Meredith , Dominic Watson , Firede , Kepennar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -18,6 +18,7 @@ export * from './type'; // Parse and operate on GraphQL language source files. export * from './language'; +export * from './subscription'; // Execute GraphQL queries. export { diff --git a/types/graphql/subscription/index.d.ts b/types/graphql/subscription/index.d.ts new file mode 100644 index 0000000000..11b0a7f26d --- /dev/null +++ b/types/graphql/subscription/index.d.ts @@ -0,0 +1 @@ +export { subscribe, createSourceEventStream } from './subscribe'; diff --git a/types/graphql/subscription/subscribe.d.ts b/types/graphql/subscription/subscribe.d.ts new file mode 100644 index 0000000000..b7b40076bf --- /dev/null +++ b/types/graphql/subscription/subscribe.d.ts @@ -0,0 +1,29 @@ +import { GraphQLSchema } from '../type/schema'; +import { DocumentNode } from '../language/ast'; +import { GraphQLFieldResolver } from '../type/definition'; +import { ExecutionResult } from '../execution/execute'; + +export function subscribe( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: { + [key: string]: any; + }, + operationName?: string, + fieldResolver?: GraphQLFieldResolver, + subscribeFieldResolver?: GraphQLFieldResolver +): AsyncIterator; + +export function createSourceEventStream( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: any, + contextValue?: any, + variableValues?: { + [key: string]: any; + }, + operationName?: string, + fieldResolver?: GraphQLFieldResolver +): AsyncIterable; diff --git a/types/graphql/tsconfig.json b/types/graphql/tsconfig.json index c6d95ebc38..3d48b9b553 100644 --- a/types/graphql/tsconfig.json +++ b/types/graphql/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, @@ -19,4 +19,4 @@ "index.d.ts", "graphql-tests.ts" ] -} \ No newline at end of file +} From 9746c28496f289ce53109d9a866a9c05f3bdf40e Mon Sep 17 00:00:00 2001 From: kepennar Date: Sat, 8 Jul 2017 12:49:12 +0200 Subject: [PATCH 0250/1618] [GraphQL] force typescript 2.3 --- types/graphql/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index f6c9750723..fbd724ff4a 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.npmjs.com/package/graphql // Definitions by: TonyYang , Caleb Meredith , Dominic Watson , Firede , Kepennar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 // The primary entry point into fulfilling a GraphQL request. export { From 372dece74cbf618cd1cfa0aa6a9a185aadff5fcc Mon Sep 17 00:00:00 2001 From: Dolan Date: Sat, 8 Jul 2017 12:02:48 +0100 Subject: [PATCH 0251/1618] Added typings --- types/google-images/index.d.ts | 41 +++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/types/google-images/index.d.ts b/types/google-images/index.d.ts index eceb0ca445..935cbda432 100644 --- a/types/google-images/index.d.ts +++ b/types/google-images/index.d.ts @@ -1,12 +1,43 @@ -// Type definitions for google-images 1.2 -// Project: https://github.com/beatgammit/base64-js +// Type definitions for google-images 2.1 +// Project: https://github.com/vadimdemedes/google-images // Definitions by: Dolan Miu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace GoogleImages { - interface GoogleImages { +export as namespace GoogleImages; +export = GoogleImages; +declare namespace GoogleImages { + type SearchImageSize = "icon" | "small" | "medium" | "large" | "xlarge" | "xxlarge" | "huge"; + type SearchImageType = "clipart" | "face" | "lineart" | "news" | "photo"; + type SearchDominantColor = "black" | "blue" | "brown" | "gray" | "green" | "pink" | "purple" | "teal" | "white" | "yellow"; + type SearchColorType = "color" | "gray" | "mono"; + type SearchSafe = "high" | "medium" | "off"; + + interface SearchOptions { + page?: number; + size?: SearchImageSize; + type?: SearchImageType; + dominantColor?: SearchDominantColor; + colorType?: SearchColorType; + safe?: SearchSafe; + } + + interface Image { + url: string; + type: string; + width: number; + height: number; + size: number; + thumbnail: { + url: string, + width: number, + height: number + }; } } -export = GoogleImages; +declare class GoogleImages { + constructor(engineId: string, apiKey: string); + + search(searchTerm: string, options?: GoogleImages.SearchOptions): Promise; +} From 2d0f4f99e2f9b706f5192373393f7827004f2539 Mon Sep 17 00:00:00 2001 From: Flur Date: Sat, 8 Jul 2017 14:50:46 +0300 Subject: [PATCH 0252/1618] -add DDSLoader -add test file for OBJLoader, MTLLoader, DDSLoader - minor changes in core --- types/three/index.d.ts | 1 + .../examples/loaders/webgl_loader_obj_mtl.ts | 83 +++++++++++++++++++ types/three/three-core.d.ts | 2 +- types/three/three-ddsloader.d.ts | 11 +++ types/three/three-mtlloader.d.ts | 2 + types/three/three-objloader.d.ts | 1 + types/three/tsconfig.json | 3 +- 7 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 types/three/test/examples/loaders/webgl_loader_obj_mtl.ts create mode 100644 types/three/three-ddsloader.d.ts diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 17156bed94..2df7c306ed 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -27,5 +27,6 @@ export * from "./three-vrcontrols"; export * from "./three-vreffect"; export * from "./three-objloader"; export * from "./three-mtlloader"; +export * from "./three-ddsloader"; export as namespace THREE; diff --git a/types/three/test/examples/loaders/webgl_loader_obj_mtl.ts b/types/three/test/examples/loaders/webgl_loader_obj_mtl.ts new file mode 100644 index 0000000000..3f11216c5a --- /dev/null +++ b/types/three/test/examples/loaders/webgl_loader_obj_mtl.ts @@ -0,0 +1,83 @@ +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_obj_mtl.html + +() => { + + var container: HTMLElement; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer; + var mouseX = 0, mouseY = 0; + var windowHalfX = window.innerWidth / 2; + var windowHalfY = window.innerHeight / 2; + + init(); + animate(); + + function init() { + container = document.createElement( 'div' ); + document.body.appendChild( container ); + camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 ); + camera.position.z = 250; + // scene + scene = new THREE.Scene(); + var ambient = new THREE.AmbientLight( 0x444444 ); + scene.add( ambient ); + var directionalLight = new THREE.DirectionalLight( 0xffeedd ); + directionalLight.position.set( 0, 0, 1 ).normalize(); + scene.add( directionalLight ); + // model + var onProgress = function ( xhr: ProgressEvent ) { + if ( xhr.lengthComputable ) { + var percentComplete = xhr.loaded / xhr.total * 100; + console.log( Math.round(percentComplete) + '% downloaded' ); + } + }; + var onError = function ( xhr: ErrorEvent ) { }; + THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() ); + var mtlLoader: THREE.MTLLoader = new THREE.MTLLoader(); + mtlLoader.setPath( 'obj/male02/' ); + mtlLoader.load( 'male02_dds.mtl', function( materials: THREE.MaterialCreator ) { + materials.preload(); + var objLoader: THREE.OBJLoader = new THREE.OBJLoader(); + objLoader.setMaterials( materials ); + objLoader.setPath( 'obj/male02/' ); + objLoader.load( 'male02.obj', function ( object: THREE.Object3D ) { + object.position.y = - 95; + scene.add( object ); + }, onProgress, onError ); + }); + + renderer = new THREE.WebGLRenderer(); + renderer.setPixelRatio( window.devicePixelRatio ); + renderer.setSize( window.innerWidth, window.innerHeight ); + container.appendChild( renderer.domElement ); + document.addEventListener( 'mousemove', onDocumentMouseMove, false ); + // + window.addEventListener( 'resize', onWindowResize, false ); + } + + function onWindowResize() { + windowHalfX = window.innerWidth / 2; + windowHalfY = window.innerHeight / 2; + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + renderer.setSize( window.innerWidth, window.innerHeight ); + } + + function onDocumentMouseMove( event: MouseEvent ) { + mouseX = ( event.clientX - windowHalfX ) / 2; + mouseY = ( event.clientY - windowHalfY ) / 2; + } + + // + function animate() { + requestAnimationFrame( animate ); + render(); + } + + function render() { + camera.position.x += ( mouseX - camera.position.x ) * .05; + camera.position.y += ( - mouseY - camera.position.y ) * .05; + camera.lookAt( scene.position ); + renderer.render( scene, camera ); + } + +} diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index ea0e6f917c..3b89456ba9 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -2087,7 +2087,7 @@ export class Loader { export interface LoaderHandler { handlers: (RegExp | Loader)[]; - add(regex: RegExp, loader: Loader): void; + add(regex: RegExp, loader: Loader | CompressedTextureLoader): void; get(file: string): Loader; } diff --git a/types/three/three-ddsloader.d.ts b/types/three/three-ddsloader.d.ts new file mode 100644 index 0000000000..7f2587adcc --- /dev/null +++ b/types/three/three-ddsloader.d.ts @@ -0,0 +1,11 @@ +// https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/DDSLoader.js + +import {CompressedPixelFormat, CompressedTextureLoader} from "./three-core"; + +export class DDSLoader extends CompressedTextureLoader { + + constructor(); + + parse(buffer: string, loadMipmaps: boolean) : { mipmaps: { data: Uint8Array, width: number, height: number }[], width: number, height: number, format: CompressedPixelFormat, mipmapCount: number }; + +} diff --git a/types/three/three-mtlloader.d.ts b/types/three/three-mtlloader.d.ts index 5113d67df2..8cac40cef2 100644 --- a/types/three/three-mtlloader.d.ts +++ b/types/three/three-mtlloader.d.ts @@ -1,3 +1,5 @@ +// https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/MTLLoader.js + import {Material} from "./three-core"; import {LoadingManager} from "./three-core"; diff --git a/types/three/three-objloader.d.ts b/types/three/three-objloader.d.ts index 25a3adf93f..b98a00f9c5 100644 --- a/types/three/three-objloader.d.ts +++ b/types/three/three-objloader.d.ts @@ -1,3 +1,4 @@ +// https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/OBJLoader.js import {Material} from "./three-core"; import {LoadingManager} from "./three-core"; diff --git a/types/three/tsconfig.json b/types/three/tsconfig.json index b2038f113c..b3bb3fc8f7 100644 --- a/types/three/tsconfig.json +++ b/types/three/tsconfig.json @@ -52,6 +52,7 @@ "test/examples/effects/vreffect.ts", "test/examples/controls/vrcontrols.ts", "test/examples/ctm/ctmloader.ts", - "test/examples/octree.ts" + "test/examples/octree.ts", + "test/examples/loaders/webgl_loader_obj_mtl.ts" ] } From d8e69d70f2ffa4d5cd9b343c954b9cee904cb649 Mon Sep 17 00:00:00 2001 From: Jan Karres Date: Sat, 8 Jul 2017 15:20:41 +0200 Subject: [PATCH 0253/1618] Bugfix --- types/react-tag-input/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/react-tag-input/index.d.ts b/types/react-tag-input/index.d.ts index 2720520766..1ab94f7f89 100644 --- a/types/react-tag-input/index.d.ts +++ b/types/react-tag-input/index.d.ts @@ -1,9 +1,8 @@ -// Type definitions for React-Tags (react-tag-input) 4.7.2 +// Type definitions for React-Tags (react-tag-input) 4.7 // Project: https://github.com/prakhar1989/react-tags // Definitions by: Ogglas // Jan Karres // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 import * as React from "react"; From 67956c91ec65c1919792ed25a398e6e790684d61 Mon Sep 17 00:00:00 2001 From: strajuser Date: Sat, 8 Jul 2017 16:23:32 +0300 Subject: [PATCH 0254/1618] - Definitions for FeatureLayer --- types/esri-leaflet/esri-leaflet-tests.ts | 95 ++++++ types/esri-leaflet/index.d.ts | 360 ++++++++++++++++++++++- 2 files changed, 453 insertions(+), 2 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index c5db206559..a237441ad5 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -230,6 +230,101 @@ dynamicMapLayer.query() .within(latlngbounds) .run(function(error, featureCollection, response){ }); +let featureLayerOptions: L.esri.FeatureLayerOptions; +let featureLayer: L.esri.FeatureLayer; + +featureLayerOptions = { + url: 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/stops/FeatureServer/0/' +}; +featureLayerOptions = { + url: 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/stops/FeatureServer/0/', + pointToLayer: (feature, latLng) => { }, + style: (feature, layer) => { }, + onEachFeature: (feature, layer) => { }, + where: '1=1', + maxZoom: 19, + minZoom: 3, + cacheLayers: true, + fields: ['a', 'b'], + from: new Date(), + to: new Date(), + timeField: { start: 'startTime', end: 'endTime' }, + timeFilterMode: 'client', + simplifyFactor: 0.1, + precision: 0.1, + renderer: new L.SVG(), + isModern: true, + ignoreRenderer: true, +}; + +featureLayer = L.esri.featureLayer(featureLayerOptions); +featureLayer = L.esri.featureLayer({ + url: 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/stops/FeatureServer/0/' +}); +featureLayer = L.esri.featureLayer({ + url: 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/stops/FeatureServer/0/', + pointToLayer: (feature, latLng) => { }, + style: (feature, layer) => { }, + onEachFeature: (feature, layer) => { }, + where: '1=1', + maxZoom: 19, + minZoom: 3, + cacheLayers: true, + fields: ['a', 'b'], + from: new Date(), + to: new Date(), + timeField: { start: 'startTime', end: 'endTime' }, + timeFilterMode: 'client', + simplifyFactor: 0.1, + precision: 0.1, + renderer: new L.SVG(), + isModern: true, + ignoreRenderer: true, +}); + +featureLayer = new L.esri.FeatureLayer(featureLayerOptions); +featureLayer = new L.esri.FeatureLayer({ + url: 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/stops/FeatureServer/0/' +}); +featureLayer = new L.esri.FeatureLayer({ + url: 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/stops/FeatureServer/0/', + pointToLayer: (feature, latLng) => { }, + style: (feature, layer) => { }, + onEachFeature: (feature, layer) => { }, + where: '1=1', + maxZoom: 19, + minZoom: 3, + cacheLayers: true, + fields: ['a', 'b'], + from: new Date(), + to: new Date(), + timeField: { start: 'startTime', end: 'endTime' }, + timeFilterMode: 'client', + simplifyFactor: 0.1, + precision: 0.1, + renderer: new L.SVG(), + isModern: true, + ignoreRenderer: true, +}); + +featureLayer.setStyle({ + color: 'white' +}) +featureLayer.setStyle(function(feature){ + return { + weight: feature.properties.pixelWidth + }; +}) + +featureLayer.eachFeature(function(layer){ }); + +featureLayer.query() + .within(latlngbounds) + .where("Direction = 'WEST'") + .run(function(error, featureCollection){ }); + +featureLayer.metadata(function(error, metadata){ }); + let mapServiceOptions: L.esri.MapServiceOptions; let mapService: L.esri.MapService; diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index f1c84b3588..d7bd0603e1 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -341,8 +341,6 @@ declare namespace L { dynamicLayers?: any; } - type FeatureRequestCallbackFn = (err: any, featureCollection: any, response: any) => void; - /** * Render and visualize Map Services from ArcGIS Online and ArcGIS Server. L.esri.DynamicMapLayer also supports custom popups and identification of features. * Map Services are used when its preferable to ask the server to draw layers at a particular location and scale and pass back the image which was generated on the fly. They also expose capabilities for querying and identifying individual features. @@ -474,6 +472,364 @@ declare namespace L { * @returns {DynamicMapLayer} */ function dynamicMapLayer(options: DynamicMapLayerOptions): DynamicMapLayer; + + /** + * Options for FeatureLayer + * + * @interface FeatureLayerOptions + * @extends {LayerOptionsBase} + */ + interface FeatureLayerOptions extends LayerOptionsBase { + /** + * Function that will be used for creating layers for GeoJSON points. If the option is not specified, simple markers will be created). For point layers, custom panes should be passed through pointToLayer (example here). + * + * @memberof FeatureLayerOptions + */ + pointToLayer?: (feature: any, latLng: LatLngExpression) => void; + /** + * Function that will be used to get style options for vector layers created for GeoJSON features. + * + * @memberof FeatureLayerOptions + */ + style?: (feature: any, layer: L.Layer) => void; + /** + * Provides an opportunity to introspect individual GeoJSON features in the layer. + * + * @memberof FeatureLayerOptions + */ + onEachFeature?: (feature: any, layer: L.Layer) => void; + /** + * An optional expression to filter features server side. String values should be denoted using single quotes ie: where: "FIELDNAME = 'field value'"; More information about valid SQL syntax can be found here. + * + * @type {string} + * @memberof FeatureLayerOptions + */ + where?: string; + /** + * Closest zoom level the layer will be displayed on the map. example: maxZoom:19 + * + * @type {number} + * @memberof FeatureLayerOptions + */ + maxZoom?: number; + /** + * Furthest zoom level the layer will be displayed on the map. example: minZoom:3 + * + * @type {number} + * @memberof FeatureLayerOptions + */ + minZoom?: number; + /** + * Will remove layers from the internal cache when they are removed from the map. + * + * @type {boolean} + * @memberof FeatureLayerOptions + */ + cacheLayers?: boolean; + /** + * An array of fieldnames to pull from the service. Includes all fields by default. You should always specify the name of the unique id for the service. Usually either 'FID' or 'OBJECTID'. + * + * @type {Array} + * @memberof FeatureLayerOptions + */ + fields?: Array; + /** + * When paired with to defines the time range of features to display. Requires the Feature Layer to be time enabled. + * + * @type {Date} + * @memberof FeatureLayerOptions + */ + from?: Date; + /** + * When paired with from defines the time range of features to display. Requires the Feature Layer to be time enabled. + * + * @type {Date} + * @memberof FeatureLayerOptions + */ + to?: Date; + /** + * The name of the field to lookup the time of the feature. Can be an object like {start:'startTime', end:'endTime'} or a string like 'created'. + * + * @type {*} + * @memberof FeatureLayerOptions + */ + timeField?: any; + /** + * Determines where features are filtered by time. By default features will be filtered by the server. If set to 'client' all features are requested and filtered by the app before display. + * + * @type {('server' | 'client')} + * @memberof FeatureLayerOptions + */ + timeFilterMode?: 'server' | 'client'; + /** + * How much to simplify polygons and polylines. A higher value gives better performance, a lower value gives a more accurate representation. + * + * @type {number} + * @memberof FeatureLayerOptions + */ + simplifyFactor?: number; + /** + * How many digits of precision to request from the server. Wikipedia has a great reference of digit precision to meters. + * + * @type {number} + * @memberof FeatureLayerOptions + */ + precision?: number; + /** + * The vector renderer to use to draw the service. Usually L.svg() is preferable but setting to L.canvas() can have performance benefits for large polygon layers. + * + * @type {(L.SVG | L.Canvas)} + * @memberof FeatureLayerOptions + */ + renderer?: L.SVG | L.Canvas; + /** + * Set this to false if your own service supports GeoJSON as an output format but you'd like to ask for Geoservices JSON instead. + * + * @type {boolean} + * @memberof FeatureLayerOptions + */ + isModern?: boolean; + /** + * When utilizing esri-leaflet-renderers '2.0.2' or above, this option makes it possible to override the symbology defined by the service itself. + * + * @type {boolean} + * @memberof FeatureLayerOptions + */ + ignoreRenderer?: boolean; + } + + type StyleCallback = (feature: any) => any; + + // TODO: VirtualGrid extends support + + /** + * L.esri.FeatureLayer is used to visualize, style, query and edit vector geographic data hosted in both ArcGIS Online and published using ArcGIS Server. Copyright text from the service is added to map attribution automatically. + * Feature Layers reference an individual data source in either a parent Map Service or Feature Service that can contain multiple layers. You can see a sample Map Service URL below: http://sampleserver6.arcgisonline.com/arcgis/rest/services/Hurricanes/MapServer + * This particular service includes two different data sources. The URL for the 'Hurricane Tracks' feature layer will end in a number (representing its position among the other layers). http://sampleserver6.arcgisonline.com/arcgis/rest/services/Hurricanes/MapServer/1 + * Feature Layer URLs always end in a number (ex: /FeatureServer/{LAYER_ID} or /MapServer/{LAYER_ID}). + * You can create a new empty feature service with a single layer on the ArcGIS for Developers website or you can use ArcGIS Online to create a Feature Service from a CSV or Shapefile + * L.esri.FeatureLayer divides the current map extent into a grid of individual cells and uses them to fire queries to fetch nearby features. This technique is comparable to MODE_ONDEMAND in the ArcGIS API for JavaScript. + * + * @class FeatureLayer + * @extends {L.Layer} + */ + class FeatureLayer extends L.Layer { + constructor(options: FeatureLayerOptions); + /** + * Sets the given path options to each layer that has a setStyle method. Can also be a Function that will receive a feature argument and should return Path Options +featureLayer.setStyle({ + color: 'white' +}) +featureLayer.setStyle(function(feature){ + return { + weight: feature.properties.pixelWidth + }; +}) + * + * @param {(L.PathOptions | StyleCallback)} style + * @returns {this} + * @memberof FeatureLayer + */ + setStyle(style: L.PathOptions | StyleCallback): this; + /** + * Changes the style on a specfic feature. + * + * @param {(string | number)} id + * @param {(L.PathOptions | StyleCallback)} style + * @returns {this} + * @memberof FeatureLayer + */ + setFeatureStyle(id: string | number, style: L.PathOptions | StyleCallback): this; + /** + * Given the ID of a feature, reset that feature to the original style. + * + * @returns {this} + * @memberof FeatureLayer + */ + resetStyle(): this; + /** + * Calls the passed function against every feature. The function will be passed the layer that represents the feature. +featureLayer.eachFeature(function(layer){ + console.log( + layer.feature.properties.NAME); +}); + * + * @param {(feature: any) => void} fn + * @param {*} [context] + * @returns {this} + * @memberof FeatureLayer + */ + eachFeature(fn: (feature: any) => void, context?: any): this; + /** + * Calls the passed function against every feature that is currently being displayed. + * + * @param {(feature: any) => void} fn + * @param {*} [context] + * @returns {this} + * @memberof FeatureLayer + */ + eachActiveFeature(fn: (feature: any) => void, context?: any): this; + /** + * Given the id of a Feature return the layer on the map that represents it. This will usually be a Leaflet vector layer like Polyline or Polygon, or a Leaflet Marker. + * + * @param {(string | number)} id + * @returns {L.Layer} + * @memberof FeatureLayer + */ + getFeature(id: string | number): L.Layer; + /** + * Returns the current where setting + * + * @returns {string} + * @memberof FeatureLayer + */ + getWhere(): string; + /** + * Sets the new where option and refreshes the layer to reflect the new where filter. Accepts an optional callback and function context. + * + * @param {string} where + * @param {FeatureCallbackHandler} [callback] + * @param {*} [context] + * @returns {this} + * @memberof FeatureLayer + */ + setWhere(where: string, callback?: FeatureCallbackHandler, context?: any): this; + /** + * Returns the current time range as an array like [from, to] + * + * @returns {Date[]} + * @memberof FeatureLayer + */ + getTimeRange(): Date[]; + /** + * Sets the current time filter applied to features. An optional callback is run upon completion if timeFilterMode is set to 'server'. Also accepts function context as the last argument. + * + * @param {Date} from + * @param {Date} to + * @param {FeatureCallbackHandler} [callback] + * @param {*} [context] + * @returns {this} + * @memberof FeatureLayer + */ + setTimeRange(from: Date, to: Date, callback?: FeatureCallbackHandler, context?: any): this; + /** + * Adds a new feature to the feature layer. this also adds the feature to the map if creation is successful. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Create capability be enabled on the service. You can check if creation exists by checking the metadata of your service under capabilities. + * + * @param {GeoJSONFeature} feature + * @param {ResponseCallbackHandler} [callback] + * @param {*} context + * @returns {this} + * @memberof FeatureLayer + */ + // TODO: GeoJSONFeature + addFeature(feature: any, callback?: ResponseCallbackHandler, context?: any): this; + /** + * Update the provided feature on the Feature Layer. This also updates the feature on the map. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Update capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. + * + * @param {GeoJSONFeature} feature + * @param {ResponseCallbackHandler} [callback] + * @param {*} context + * @returns {this} + * @memberof FeatureLayer + */ + // TODO: GeoJSONFeature + updateFeature(feature: any, callback?: ResponseCallbackHandler, context?: any): this; + /** + * Remove the feature with the provided id from the feature layer. This will also remove the feature from the map if it exists. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Delete capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. + * + * @param {(string | number)} id + * @param {ResponseCallbackHandler} [callback] + * @param {*} context + * @returns {this} + * @memberof FeatureLayer + */ + deleteFeature(id: string | number, callback?: ResponseCallbackHandler, context?: any): this; + /** + * Removes an array of features with the provided ids from the feature layer. This will also remove the features from the map if they exist. + * Requires authentication as a user who has permission to edit the service in ArcGIS Online or the user who created the service. + * Requires the Delete capability be enabled on the service. You can check if this operation exists by checking the metadata of your service under capabilities. + * + * @param {(Array)} ids + * @param {ResponseCallbackHandler} [callback] + * @param {*} context + * @returns {this} + * @memberof FeatureLayer + */ + deleteFeatures(ids: Array, callback?: ResponseCallbackHandler, context?: any): this; + /** + * Redraws a feature with the provided id from the feature layer. + * + * @param {(string | number)} id + * @returns {this} + * @memberof FeatureLayer + */ + redraw(id: string | number): this; + /** + * Redraws all features from the feature layer that exist on the map. + * + * @returns {this} + * @memberof FeatureLayer + */ + refresh(): this + + /** + * Authenticates this service with a new token and runs any pending requests that required a token. + * + * @param {string} token + * @returns {this} + * @memberof TiledMapLayer + */ + authenticate(token: string): this; + /** + * Requests metadata about this Feature Layer. Callback will be called with error and metadata. + * + * @param {CallbackHandler} callback + * @param {*} context + * @returns {this} + * @memberof TiledMapLayer + */ + metadata(callback: CallbackHandler, context?: any): this; + /** + * Returns a new L.esri.services.IdentifyFeatures object that can be used to identify features on this layer. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof TiledMapLayer + */ + identify(): IdentifyFeatures; + /** + * Returns a new L.esri.services.Find object that can be used to find features. Your callback function will be passed a GeoJSON FeatureCollection with the results or an error. + * + * @returns {*} + * @memberof TiledMapLayer + */ + find(): Find; + /** + * Returns a new L.esri.Query object that can be used to query this service. + * + * @returns {*} + * @memberof TiledMapLayer + */ + query(): Query; + } + + /** + * L.esri.FeatureLayer is used to visualize, style, query and edit vector geographic data hosted in both ArcGIS Online and published using ArcGIS Server. Copyright text from the service is added to map attribution automatically. + * Feature Layers reference an individual data source in either a parent Map Service or Feature Service that can contain multiple layers. You can see a sample Map Service URL below: http://sampleserver6.arcgisonline.com/arcgis/rest/services/Hurricanes/MapServer + * This particular service includes two different data sources. The URL for the 'Hurricane Tracks' feature layer will end in a number (representing its position among the other layers). http://sampleserver6.arcgisonline.com/arcgis/rest/services/Hurricanes/MapServer/1 + * Feature Layer URLs always end in a number (ex: /FeatureServer/{LAYER_ID} or /MapServer/{LAYER_ID}). + * You can create a new empty feature service with a single layer on the ArcGIS for Developers website or you can use ArcGIS Online to create a Feature Service from a CSV or Shapefile + * L.esri.FeatureLayer divides the current map extent into a grid of individual cells and uses them to fire queries to fetch nearby features. This technique is comparable to MODE_ONDEMAND in the ArcGIS API for JavaScript. + * + * @param {FeatureLayerOptions} options + * @returns {FeatureLayer} + */ + function featureLayer(options: FeatureLayerOptions): FeatureLayer; } } From 9284c5c30d38c2ab00fd99f2b6c5491e7adac1c5 Mon Sep 17 00:00:00 2001 From: strajuser Date: Sat, 8 Jul 2017 16:57:55 +0300 Subject: [PATCH 0255/1618] - lint fixes --- types/esri-leaflet/esri-leaflet-tests.ts | 181 ++++++++++++----------- types/esri-leaflet/index.d.ts | 51 +++---- 2 files changed, 117 insertions(+), 115 deletions(-) diff --git a/types/esri-leaflet/esri-leaflet-tests.ts b/types/esri-leaflet/esri-leaflet-tests.ts index a237441ad5..7198c06d06 100644 --- a/types/esri-leaflet/esri-leaflet-tests.ts +++ b/types/esri-leaflet/esri-leaflet-tests.ts @@ -1,6 +1,12 @@ +// tslint:disable:no-trailing-whitespace +// tslint:disable:prefer-method-signature +// tslint:disable:no-single-declare-module +// tslint:disable:only-arrow-functions +// tslint:disable:space-before-function-paren + import L = require('esri-leaflet'); -let latlng: L.LatLng = new L.LatLng(0, 0);; +let latlng: L.LatLng = new L.LatLng(0, 0); let latlngbounds: L.LatLngBounds = new L.LatLngBounds(latlng, latlng); let map: L.Map = new L.Map('map'); @@ -95,16 +101,16 @@ tiledMapLayer.authenticate('secret'); tiledMapLayer.metadata((err, metadata) => { }); tiledMapLayer.identify() - .at(latlng) - .run(function(error, featureCollection){ }); + .at(latlng) + .run(function (error, featureCollection) { }); tiledMapLayer.find() - .layers('18') - .text('Colorado') - .run(function(error, featureCollection){ }); + .layers('18') + .text('Colorado') + .run(function (error, featureCollection) { }); tiledMapLayer.query() - .layer(0) - .within(latlngbounds) - .run(function(error, featureCollection, response){ }); + .layer(0) + .within(latlngbounds) + .run(function (error, featureCollection, response) { }); let dynamicMapLayer: L.esri.DynamicMapLayer; let dynamicMapLayerOptions: L.esri.DynamicMapLayerOptions; @@ -125,16 +131,16 @@ dynamicMapLayerOptions = { maxZoom: 1, minZoom: 1, dynamicLayers: [{ - "id": 501, - "source": { - "type": "mapLayer", - "mapLayerId": 0 + id: 501, + source: { + type: 'mapLayer', + mapLayerId: 0 }, - "drawingInfo": { - "showLabels": false + drawingInfo: { + showLabels: false }, - "layerTimeOptions": { - "useTime": false + layerTimeOptions: { + useTime: false } }], proxy: '//localhost/proxy', @@ -159,16 +165,16 @@ dynamicMapLayer = L.esri.dynamicMapLayer({ maxZoom: 1, minZoom: 1, dynamicLayers: [{ - "id": 501, - "source": { - "type": "mapLayer", - "mapLayerId": 0 + id: 501, + source: { + type: 'mapLayer', + mapLayerId: 0 }, - "drawingInfo": { - "showLabels": false + drawingInfo: { + showLabels: false }, - "layerTimeOptions": { - "useTime": false + layerTimeOptions: { + useTime: false } }], proxy: '//localhost/proxy', @@ -193,16 +199,16 @@ dynamicMapLayer = new L.esri.DynamicMapLayer({ maxZoom: 1, minZoom: 1, dynamicLayers: [{ - "id": 501, - "source": { - "type": "mapLayer", - "mapLayerId": 0 + id: 501, + source: { + type: 'mapLayer', + mapLayerId: 0 }, - "drawingInfo": { - "showLabels": false + drawingInfo: { + showLabels: false }, - "layerTimeOptions": { - "useTime": false + layerTimeOptions: { + useTime: false } }], proxy: '//localhost/proxy', @@ -210,25 +216,24 @@ dynamicMapLayer = new L.esri.DynamicMapLayer({ token: 'token' }); -dynamicMapLayer.bindPopup( - function (err, featureCollection, response) { - var count = featureCollection.features.length; - return (count) ? count + ' features' : false; - }); +dynamicMapLayer.bindPopup(function (err, featureCollection, response) { + let count = featureCollection.features.length; + return (count) ? count + ' features' : false; +}); dynamicMapLayer.metadata(function (error, metadata) { }); dynamicMapLayer.identify() - .at(latlng) - .run(function(error, featureCollection){ }); + .at(latlng) + .run(function (error, featureCollection) { }); dynamicMapLayer.find() - .layers('18') - .text('Colorado') - .run(function(error, featureCollection){ }); + .layers('18') + .text('Colorado') + .run(function (error, featureCollection) { }); dynamicMapLayer.query() - .layer(0) - .within(latlngbounds) - .run(function(error, featureCollection, response){ }); + .layer(0) + .within(latlngbounds) + .run(function (error, featureCollection, response) { }); let featureLayerOptions: L.esri.FeatureLayerOptions; let featureLayer: L.esri.FeatureLayer; @@ -308,22 +313,22 @@ featureLayer = new L.esri.FeatureLayer({ }); featureLayer.setStyle({ - color: 'white' -}) -featureLayer.setStyle(function(feature){ - return { - weight: feature.properties.pixelWidth - }; -}) + color: 'white' +}); +featureLayer.setStyle(function (feature) { + return { + weight: feature.properties.pixelWidth + }; +}); -featureLayer.eachFeature(function(layer){ }); +featureLayer.eachFeature(function (layer) { }); featureLayer.query() - .within(latlngbounds) - .where("Direction = 'WEST'") - .run(function(error, featureCollection){ }); + .within(latlngbounds) + .where("Direction = 'WEST'") + .run(function (error, featureCollection) { }); -featureLayer.metadata(function(error, metadata){ }); +featureLayer.metadata(function (error, metadata) { }); let mapServiceOptions: L.esri.MapServiceOptions; let mapService: L.esri.MapService; @@ -356,31 +361,31 @@ mapService = new L.esri.MapService({ }); mapService.query() - .layer(0) - .within(latlngbounds) - .run(function(error, featureCollection, response){ }); + .layer(0) + .within(latlngbounds) + .run(function (error, featureCollection, response) { }); mapService.identify() - .on(map) - .at(latlng) - .run(function(error, featureCollection, response){ }); + .on(map) + .at(latlng) + .run(function (error, featureCollection, response) { }); mapService.find() - .layers('18') - .text('Colorado') - .fields('name') - .run(function(error, featureCollection, response){ }); + .layers('18') + .text('Colorado') + .fields('name') + .run(function (error, featureCollection, response) { }); mapService.identify() .on(map) .at([45.543, -122.621]) .layers('visible:1') - .run(function(error, featureCollection, response){ }); + .run(function (error, featureCollection, response) { }); mapService.find() .layers('18') .text('Colorado') .fields('GNIS_NAME') - .run(function(error, featureCollection, response){ }); + .run(function (error, featureCollection, response) { }); -let imageServiceOptions : L.esri.ImageServiceOptions; +let imageServiceOptions: L.esri.ImageServiceOptions; let imageService: L.esri.ImageService; imageServiceOptions = { @@ -410,7 +415,7 @@ imageService = new L.esri.ImageService({ timeout: 1000 }); -let featureLayerServiceOptions : L.esri.FeatureLayerServiceOptions; +let featureLayerServiceOptions: L.esri.FeatureLayerServiceOptions; let featureLayerService: L.esri.FeatureLayerService; featureLayerServiceOptions = { @@ -441,9 +446,9 @@ featureLayerService = new L.esri.FeatureLayerService({ }); featureLayerService.query() - .within(latlngbounds) - .where("Direction = 'WEST'") - .run(function(error, featureCollection, response){ }); + .within(latlngbounds) + .where("Direction = 'WEST'") + .run(function (error, featureCollection, response) { }); let feature = { type: 'Feature', @@ -455,7 +460,7 @@ let feature = { name: 'Hello World' } }; -featureLayerService.addFeature(feature, function(error, response){ }); +featureLayerService.addFeature(feature, function (error, response) { }); let feature2 = { type: 'Feature', @@ -468,14 +473,14 @@ let feature2 = { name: 'Hi I\'m Feature 2' } }; -featureLayerService.updateFeature(feature2, function(error, response){ }); +featureLayerService.updateFeature(feature2, function (error, response) { }); -featureLayerService.deleteFeature(2, function(error, response){ }); +featureLayerService.deleteFeature(2, function (error, response) { }); featureLayerService .query() .where("name='Hello World'") - .run(function(error, featureCollection, response){ }); + .run(function (error, featureCollection, response) { }); let queryOptions: L.esri.QueryOptions; let query: L.esri.Query; @@ -508,17 +513,17 @@ query = new L.esri.Query({ }); query.within(latlngbounds); -query.run(function(error, featureCollection, response){ }); -query.bounds(function(error, latLngBounds, response){ }); +query.run(function (error, featureCollection, response) { }); +query.bounds(function (error, latLngBounds, response) { }); query.nearby(latlng, 500); -query.run(function(error, featureCollection, response){ }); +query.run(function (error, featureCollection, response) { }); query.nearby(latlng, 2000).where("direction='East'").orderBy('stop_id', 'ASC'); -query.count(function(error, count, response){ }); -query.ids(function(error, ids, response){ }); +query.count(function (error, count, response) { }); +query.ids(function (error, ids, response) { }); -query.where("zone_id='B'").bounds(function(error, latLngBounds, response){ }); +query.where("zone_id='B'").bounds(function (error, latLngBounds, response) { }); let identifyFeaturesOptions: L.esri.IdentifyFeaturesOptions; let identifyFeatures: L.esri.IdentifyFeatures; @@ -554,7 +559,7 @@ identifyFeatures .on(map) .at([45.543, -122.621]) .layers('visible:1') - .run(function(error, featureCollection, response) { }); + .run(function (error, featureCollection, response) { }); let findOptions: L.esri.FindOptions; let find: L.esri.Find; @@ -588,9 +593,9 @@ find = new L.esri.Find({ find.layers('18') .text('Colorado'); -find.run(function(error, featureCollection, response){ }); +find.run(function (error, featureCollection, response) { }); find.layers('13') .text('198133') .fields('GNIS_ID'); -find.run(function(error, featureCollection, response) { }); +find.run(function (error, featureCollection, response) { }); diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index d7bd0603e1..da7c02735d 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -3,6 +3,13 @@ // Definitions by: strajuser // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// tslint:disable:whitespace +// tslint:disable:no-trailing-whitespace +// tslint:disable:prefer-method-signature +// tslint:disable:no-single-declare-module +// tslint:disable:max-line-length +// tslint:disable:no-empty-interface + /// declare namespace L { @@ -387,7 +394,7 @@ declare namespace L { * @returns {Array} * @memberof DynamicMapLayer */ - getLayers(): Array; + getLayers(): any[]; /** * Redraws the layer to show the passed array of layer ids. * @@ -395,7 +402,7 @@ declare namespace L { * @returns {this} * @memberof DynamicMapLayer */ - setLayers(layers: Array): this; + setLayers(layers: any[]): this; /** * Returns the current layer definition(s) being used for rendering. * @@ -417,9 +424,9 @@ declare namespace L { * @returns {*} * @memberof DynamicMapLayer */ - getTimeOptions(): any + getTimeOptions(): any; /** - * Sets the current time options being used to render the layer. Corresponds to the layerTimeOptions option on the export API. + * Sets the current time options being used to render the layer. Corresponds to the layerTimeOptions option on the export API. * * @param {*} timeOptions * @returns {this} @@ -532,7 +539,7 @@ declare namespace L { * @type {Array} * @memberof FeatureLayerOptions */ - fields?: Array; + fields?: string[]; /** * When paired with to defines the time range of features to display. Requires the Feature Layer to be time enabled. * @@ -617,14 +624,8 @@ declare namespace L { constructor(options: FeatureLayerOptions); /** * Sets the given path options to each layer that has a setStyle method. Can also be a Function that will receive a feature argument and should return Path Options -featureLayer.setStyle({ - color: 'white' -}) -featureLayer.setStyle(function(feature){ - return { - weight: feature.properties.pixelWidth - }; -}) + * featureLayer.setStyle({ color: 'white' }) + * featureLayer.setStyle(function(feature){ return { weight: feature.properties.pixelWidth };}) * * @param {(L.PathOptions | StyleCallback)} style * @returns {this} @@ -648,11 +649,8 @@ featureLayer.setStyle(function(feature){ */ resetStyle(): this; /** - * Calls the passed function against every feature. The function will be passed the layer that represents the feature. -featureLayer.eachFeature(function(layer){ - console.log( - layer.feature.properties.NAME); -}); + * Calls the passed function against every feature. The function will be passed the layer that represents the feature. + * featureLayer.eachFeature(function(layer){ console.log(layer.feature.properties.NAME); }); * * @param {(feature: any) => void} fn * @param {*} [context] @@ -761,7 +759,7 @@ featureLayer.eachFeature(function(layer){ * @returns {this} * @memberof FeatureLayer */ - deleteFeatures(ids: Array, callback?: ResponseCallbackHandler, context?: any): this; + deleteFeatures(ids: string[] | number[], callback?: ResponseCallbackHandler, context?: any): this; /** * Redraws a feature with the provided id from the feature layer. * @@ -776,8 +774,7 @@ featureLayer.eachFeature(function(layer){ * @returns {this} * @memberof FeatureLayer */ - refresh(): this - + refresh(): this; /** * Authenticates this service with a new token and runs any pending requests that required a token. * @@ -1119,7 +1116,7 @@ declare namespace L { * @returns {this} * @memberof FeatureLayerService */ - deleteFeatures(ids: Array, callback?: ResponseCallbackHandler, context?: any): this; + deleteFeatures(ids: string[] | number[], callback?: ResponseCallbackHandler, context?: any): this; } /** @@ -1239,7 +1236,7 @@ declare namespace L { * @returns {this} * @memberof Query */ - fields(fields: string | Array): this; + fields(fields: string | string[]): this; /** * Return geometry with results. Default is true. * @@ -1273,7 +1270,7 @@ declare namespace L { * @returns {this} * @memberof Query */ - featureIds(ids: Array): this; + featureIds(ids: any[]): this; /** * Return only this many decimal points of precision in the output geometries. * @@ -1405,7 +1402,7 @@ declare namespace L { * @returns {this} * @memberof IdentifyFeatures */ - layers(layers: string | Array): this; + layers(layers: string | string[]): this; /** * Return only this many decimal points of precision in the output geometries. * @@ -1497,7 +1494,7 @@ declare namespace L { * @returns {this} * @memberof Find */ - fields(fields: string | Array): this; + fields(fields: string | string[]): this; /** * The well known ID (ex. 4326) for the results. * @@ -1522,7 +1519,7 @@ declare namespace L { * @returns {this} * @memberof Find */ - layers(layers: string | Array): this; + layers(layers: string | string[]): this; /** * Return geometry with results. Default is true. * From 89124e21558d608d7ca86db6c5e7a4488e7687cc Mon Sep 17 00:00:00 2001 From: strajuser Date: Sat, 8 Jul 2017 17:38:36 +0300 Subject: [PATCH 0256/1618] - Incorrect override fix --- types/esri-leaflet/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/esri-leaflet/index.d.ts b/types/esri-leaflet/index.d.ts index da7c02735d..e2ccf9f6a8 100644 --- a/types/esri-leaflet/index.d.ts +++ b/types/esri-leaflet/index.d.ts @@ -366,6 +366,7 @@ declare namespace L { * @memberof DynamicMapLayer */ bindPopup(fn: FeatureCallbackHandler, popupOptions?: L.PopupOptions): this; + bindPopup(content: ((layer: Layer) => Content) | Content | Popup, options?: PopupOptions): this; /** * Removes a popup previously bound with bindPopup. * From e4f89b34f9444a224656cda5ff186110ef9c17e8 Mon Sep 17 00:00:00 2001 From: Erik Seliger Date: Sat, 8 Jul 2017 17:28:29 +0200 Subject: [PATCH 0257/1618] Update version --- types/js-yaml/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 37d817fb8c..2817689c29 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-yaml 3.5.2 +// Type definitions for js-yaml 3.9.0 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 6b4e9553fe79364d513b4cd10fd1a69a65710c05 Mon Sep 17 00:00:00 2001 From: Jakob Krigovsky Date: Sat, 8 Jul 2017 21:03:45 +0200 Subject: [PATCH 0258/1618] Use SVG for Travis CI badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f3c4fe78f..0d1c87b82b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) +# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) [![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) From 30d9e497dfc115e43904717d4a013ca094cc0f98 Mon Sep 17 00:00:00 2001 From: Fei YU Date: Sat, 8 Jul 2017 13:53:08 -0700 Subject: [PATCH 0259/1618] Fix typo from arb -> abr --- types/hls.js/index.d.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 66ad839da1..e80eecae3f 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -757,39 +757,39 @@ declare namespace Hls { * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. * parameter should be a float greater than abrEwmaFastLive */ - arbEwmaSlowLive: number; + abrEwmaSlowLive: number; /** * (default: 4.0) * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. * parameter should be a float greater than 0 */ - arbEwmaFastVod: number; + abrEwmaFastVod: number; /** * (default: 15.0) * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. * parameter should be a float greater than abrEwmaFastVoD */ - arbEwmaSlowVod: number; + abrEwmaSlowVod: number; /** * (default: 500000) * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. * parameter should be a float */ - arbEwmaDefaultEstimate: number; + abrEwmaDefaultEstimate: number; /** * (default: 0.8) * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. */ - arbBandWidthFactor: number; + abrBandWidthFactor: number; /** * (default: 0.7) * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. */ - arbBandWidthUpFactor: number; + abrBandWidthUpFactor: number; /** * (default: false) * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, @@ -1161,39 +1161,39 @@ declare namespace Hls { * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. * parameter should be a float greater than abrEwmaFastLive */ - arbEwmaSlowLive?: number; + abrEwmaSlowLive?: number; /** * (default: 4.0) * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. * parameter should be a float greater than 0 */ - arbEwmaFastVod?: number; + abrEwmaFastVod?: number; /** * (default: 15.0) * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. * parameter should be a float greater than abrEwmaFastVoD */ - arbEwmaSlowVod?: number; + abrEwmaSlowVod?: number; /** * (default: 500000) * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. * parameter should be a float */ - arbEwmaDefaultEstimate?: number; + abrEwmaDefaultEstimate?: number; /** * (default: 0.8) * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. */ - arbBandWidthFactor?: number; + abrBandWidthFactor?: number; /** * (default: 0.7) * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. */ - arbBandWidthUpFactor?: number; + abrBandWidthUpFactor?: number; /** * (default: false) * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, From 114f6f2787da2838d656171c6e8141d8e6b3a9cb Mon Sep 17 00:00:00 2001 From: Dan Dascalescu Date: Sat, 8 Jul 2017 15:42:07 -0700 Subject: [PATCH 0260/1618] toMatchObject can also match arrays https://github.com/facebook/jest/pull/3994 --- types/jest/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index b886bdeaac..ee7e25a9de 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -275,8 +275,8 @@ declare namespace jest { toHaveProperty(propertyPath: string, value?: any): R; /** Check that a string matches a regular expression. */ toMatch(expected: string | RegExp): R; - /** Used to check that a JavaScript object matches a subset of the properties of an objec */ - toMatchObject(expected: {}): R; + /** Used to check that a JavaScript object matches a subset of the properties of an object */ + toMatchObject(expected: {} | any[]): R; /** This ensures that a value matches the most recent snapshot. Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */ toMatchSnapshot(snapshotName?: string): R; /** Used to test that a function throws when it is called. */ From f11190042e949ec0c3176ccec5473196547c5e2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Sun, 9 Jul 2017 02:16:08 +0300 Subject: [PATCH 0261/1618] Added json2md types. --- types/json2md/index.d.ts | 66 +++++++++++ types/json2md/json2md-tests.ts | 202 +++++++++++++++++++++++++++++++++ types/json2md/tsconfig.json | 22 ++++ types/json2md/tslint.json | 1 + 4 files changed, 291 insertions(+) create mode 100644 types/json2md/index.d.ts create mode 100644 types/json2md/json2md-tests.ts create mode 100644 types/json2md/tsconfig.json create mode 100644 types/json2md/tslint.json diff --git a/types/json2md/index.d.ts b/types/json2md/index.d.ts new file mode 100644 index 0000000000..ec40a753b5 --- /dev/null +++ b/types/json2md/index.d.ts @@ -0,0 +1,66 @@ +// Type definitions for json2md 1.5 +// Project: https://github.com/IonicaBizau/json2md#readme +// Definitions by: MartynasZilinskas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = json2md; + +declare function json2md(data: json2md.ConverterObject | json2md.ConverterObject[] | string | string[], prefix?: string): string; +type json2md = typeof json2md; + +declare namespace json2md { + interface ConverterObject { + [converter: string]: any; + blockquote?: string | string[]; + code?: CodeInput; + h1?: string | string[]; + h2?: string | string[]; + h3?: string | string[]; + h4?: string | string[]; + h5?: string | string[]; + h6?: string | string[]; + img?: ImgInput | ImgInput[]; + ol?: string[]; + p?: string | string[]; + table?: TableInput; + ul?: string[]; + } + + type ConverterCallback = (input: TInput, json2md: json2md) => string; + + const converters: ConvertersMethods; + + interface ConvertersMethods { + [converter: string]: ConverterCallback; + + blockquote(input: string | string[], json2md: json2md): string; + code(input: CodeInput, json2md: json2md): string; + h1(input: string, json2md: json2md): string; + h2(input: string, json2md: json2md): string; + h3(input: string, json2md: json2md): string; + h4(input: string, json2md: json2md): string; + h5(input: string, json2md: json2md): string; + h6(input: string, json2md: json2md): string; + img(input: ImgInput | ImgInput[] | string, json2md: json2md): string; + ol(input: string, json2md: json2md): string; + p(input: string, json2md: json2md): string; + table(input: TableInput, json2md: json2md): string; + ul(input: string, json2md: json2md): string; + } + + interface ImgInput { + title: string; + source: string; + } + + interface CodeInput { + language?: string; + content: string | string[]; + } + + interface TableInput { + headers: string[]; + rows: Array<{ [column: string]: string }> | string[][]; + } +} diff --git a/types/json2md/json2md-tests.ts b/types/json2md/json2md-tests.ts new file mode 100644 index 0000000000..bdb071517b --- /dev/null +++ b/types/json2md/json2md-tests.ts @@ -0,0 +1,202 @@ +import * as json2md from 'json2md'; + +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; + +const exampleString: string = "example string"; +const exampleStringArray: string[] = ["A", "B"]; + +describe("Default elements", () => { + it("Headings", () => { + json2md([ + { + h1: exampleString + }, + { + h2: exampleString + }, + { + h3: exampleString + }, + { + h4: exampleString + }, + { + h5: exampleString + }, + { + h6: exampleString + } + ]); + }); + + it("Paragraphs", () => { + json2md([{ + p: exampleString + }]); + + json2md([{ + p: exampleStringArray + }]); + }); + + it("Blockquote", () => { + json2md([{ + blockquote: exampleString + }]); + + json2md([{ + blockquote: exampleStringArray + }]); + }); + + it("Image", () => { + json2md([{ + img: { + title: exampleString, + source: exampleString + } + }]); + + json2md([{ + img: [ + { + title: exampleString, + source: exampleString + } + ] + }]); + }); + + it("Unordered list", () => { + json2md([ + { + ul: exampleStringArray + } + ]); + }); + + it("Ordered list", () => { + json2md([ + { + ol: exampleStringArray + } + ]); + }); + + it("Code block element", () => { + json2md([ + { + code: { + language: "js", + content: exampleString + } + } + ]); + }); + + it("Table", () => { + json2md([ + { + table: { + headers: exampleStringArray, + rows: [ + { + A: exampleString, + B: exampleString + } + ] + } + } + ]); + + json2md([ + { + table: { + headers: exampleStringArray, + rows: [ + exampleStringArray + ] + } + } + ]); + }); +}); + +it("Custom types", () => { + const customConverter: json2md.ConverterCallback = (input, json2md) => { + return `Hello ${input} world!`; + }; + + json2md.converters.customConverter = customConverter; + + json2md([ + { + customConverter: exampleString + } + ]); +}); + +it("Big example", () => { + const md: string = json2md([ + { + h1: "JSON To Markdown" + }, + { + blockquote: "A JSON to Markdown converter." + }, + { + img: [ + { + title: "Some image", + source: "https://example.com/some-image.png" + }, + { + title: "Another image", + source: "https://example.com/some-image1.png" + }, + { + title: "Yet another image", + source: "https://example.com/some-image2.png" + } + ] + }, + { + h2: "Features" + }, + { + ul: [ + "Easy to use", + "You can programatically generate Markdown content", + "..." + ] + }, + { + h2: "How to contribute" + }, + { + ol: [ + "Fork the project", + "Create your branch", + "Raise a pull request" + ] + }, + { + h2: "Code blocks" + }, + { + p: "Below you can see a code block example." + }, + { + code: { + language: "js", + content: [ + "function sum (a, b) {", + " return a + b;", + "}", + "sum(1, 2);" + ] + } + } + ]); +}); diff --git a/types/json2md/tsconfig.json b/types/json2md/tsconfig.json new file mode 100644 index 0000000000..8fec5e6f49 --- /dev/null +++ b/types/json2md/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "json2md-tests.ts" + ] +} diff --git a/types/json2md/tslint.json b/types/json2md/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json2md/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 8ab835ba1b61ef6dc63a03a6fa4303ffe15c127b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Sun, 9 Jul 2017 02:17:16 +0300 Subject: [PATCH 0262/1618] Renamed interface. --- types/json2md/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/json2md/index.d.ts b/types/json2md/index.d.ts index ec40a753b5..c07e065629 100644 --- a/types/json2md/index.d.ts +++ b/types/json2md/index.d.ts @@ -6,11 +6,13 @@ export = json2md; -declare function json2md(data: json2md.ConverterObject | json2md.ConverterObject[] | string | string[], prefix?: string): string; +declare function json2md(data: json2md.DataObject | json2md.DataObject[] | string | string[], prefix?: string): string; type json2md = typeof json2md; declare namespace json2md { - interface ConverterObject { + const converters: ConvertersMethods; + + interface DataObject { [converter: string]: any; blockquote?: string | string[]; code?: CodeInput; @@ -29,8 +31,6 @@ declare namespace json2md { type ConverterCallback = (input: TInput, json2md: json2md) => string; - const converters: ConvertersMethods; - interface ConvertersMethods { [converter: string]: ConverterCallback; From 95390bf278190e856e7aebaa93cbc6747c776cbd Mon Sep 17 00:00:00 2001 From: Benjamin Lim Date: Sun, 9 Jul 2017 14:18:48 +0800 Subject: [PATCH 0263/1618] fix: change Compiler to ICompiler - Updates the WebpackDevMiddleware function to accept MultiCompilers - Updates deprecated names Closes #17608 --- types/webpack-dev-middleware/index.d.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/types/webpack-dev-middleware/index.d.ts b/types/webpack-dev-middleware/index.d.ts index 471a0f92ba..594a0f9bf1 100644 --- a/types/webpack-dev-middleware/index.d.ts +++ b/types/webpack-dev-middleware/index.d.ts @@ -4,12 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { NextHandleFunction } from 'connect'; -import { compiler } from 'webpack'; +import * as webpack from 'webpack'; export = WebpackDevMiddleware; declare function WebpackDevMiddleware( - compiler: compiler.Compiler, + compiler: webpack.ICompiler, options?: WebpackDevMiddleware.Options ): WebpackDevMiddleware.WebpackDevMiddleware & NextHandleFunction; @@ -18,13 +18,13 @@ declare namespace WebpackDevMiddleware { noInfo?: boolean; quiet?: boolean; lazy?: boolean; - watchOptions?: compiler.WatchOptions; + watchOptions?: webpack.WatchOptions; publicPath: string; index?: string; headers?: { [name: string]: string; }; - stats?: compiler.StatsToStringOptions; + stats?: webpack.Stats.ToStringOptions; reporter?: Reporter | null; serverSideRender?: boolean; @@ -36,7 +36,7 @@ declare namespace WebpackDevMiddleware { interface ReporterOptions { state: boolean; - stats: compiler.Stats; + stats: webpack.Stats; options: Options; } @@ -46,7 +46,7 @@ declare namespace WebpackDevMiddleware { interface WebpackDevMiddleware { close(callback?: () => void): void; - invalidate(callback?: (stats: compiler.Stats) => void): void; - waitUntilValid(callback?: (stats: compiler.Stats) => void): void; + invalidate(callback?: (stats: webpack.Stats) => void): void; + waitUntilValid(callback?: (stats: webpack.Stats) => void): void; } } From df4cf485085314595a751e45610a06f9184d96bd Mon Sep 17 00:00:00 2001 From: Benjamin Lim Date: Sun, 9 Jul 2017 14:27:03 +0800 Subject: [PATCH 0264/1618] refactor: use type aliases in webpack options namespace --- types/webpack-dev-middleware/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/webpack-dev-middleware/index.d.ts b/types/webpack-dev-middleware/index.d.ts index 594a0f9bf1..a497cc8cd1 100644 --- a/types/webpack-dev-middleware/index.d.ts +++ b/types/webpack-dev-middleware/index.d.ts @@ -18,13 +18,13 @@ declare namespace WebpackDevMiddleware { noInfo?: boolean; quiet?: boolean; lazy?: boolean; - watchOptions?: webpack.WatchOptions; + watchOptions?: webpack.Options.WatchOptions; publicPath: string; index?: string; headers?: { [name: string]: string; }; - stats?: webpack.Stats.ToStringOptions; + stats?: webpack.Options.Stats; reporter?: Reporter | null; serverSideRender?: boolean; From a4fd4c5f5447919f64d4211034598cecde49d108 Mon Sep 17 00:00:00 2001 From: Benjamin Lim Date: Sun, 9 Jul 2017 15:53:58 +0800 Subject: [PATCH 0265/1618] feat: add Devtool options type Closes #17387 --- types/webpack/index.d.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 49c42740f2..13b2de85cd 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -30,13 +30,7 @@ declare namespace webpack { context?: string; entry?: string | string[] | Entry; /** Choose a style of source mapping to enhance the debugging process. These values can affect build and rebuild speed dramatically. */ - // tslint:disable-next-line:max-line-length - devtool?: 'eval' | 'inline-source-map' | 'cheap-eval-source-map' | 'cheap-source-map' | 'cheap-module-eval-source-map' | 'cheap-module-source-map' | 'eval-source-map' | 'source-map' | - 'nosources-source-map' | 'hidden-source-map' | 'nosources-source-map' | '@eval' | '@inline-source-map' | '@cheap-eval-source-map' | '@cheap-source-map' | '@cheap-module-eval-source-map' | - '@cheap-module-source-map' | '@eval-source-map' | '@source-map' | '@nosources-source-map' | '@hidden-source-map' | '@nosources-source-map' | '#eval' | '#inline-source-map' | - '#cheap-eval-source-map' | '#cheap-source-map' | '#cheap-module-eval-source-map' | '#cheap-module-source-map' | '#eval-source-map' | '#source-map' | '#nosources-source-map' | - '#hidden-source-map' | '#nosources-source-map' | '#@eval' | '#@inline-source-map' | '#@cheap-eval-source-map' | '#@cheap-source-map' | '#@cheap-module-eval-source-map' | - '#@cheap-module-source-map' | '#@eval-source-map' | '#@source-map' | '#@nosources-source-map' | '#@hidden-source-map' | '#@nosources-source-map' | boolean; + devtool?: Options.Devtool; /** Options affecting the output. */ output?: Output; /** Options affecting the normal modules (NormalModuleFactory) */ @@ -509,6 +503,14 @@ declare namespace webpack { type Rule = LoaderRule | UseRule | RulesRule | OneOfRule; namespace Options { + // tslint:disable-next-line:max-line-length + type Devtool = 'eval' | 'inline-source-map' | 'cheap-eval-source-map' | 'cheap-source-map' | 'cheap-module-eval-source-map' | 'cheap-module-source-map' | 'eval-source-map' | 'source-map' | + 'nosources-source-map' | 'hidden-source-map' | 'nosources-source-map' | '@eval' | '@inline-source-map' | '@cheap-eval-source-map' | '@cheap-source-map' | '@cheap-module-eval-source-map' | + '@cheap-module-source-map' | '@eval-source-map' | '@source-map' | '@nosources-source-map' | '@hidden-source-map' | '@nosources-source-map' | '#eval' | '#inline-source-map' | + '#cheap-eval-source-map' | '#cheap-source-map' | '#cheap-module-eval-source-map' | '#cheap-module-source-map' | '#eval-source-map' | '#source-map' | '#nosources-source-map' | + '#hidden-source-map' | '#nosources-source-map' | '#@eval' | '#@inline-source-map' | '#@cheap-eval-source-map' | '#@cheap-source-map' | '#@cheap-module-eval-source-map' | + '#@cheap-module-source-map' | '#@eval-source-map' | '#@source-map' | '#@nosources-source-map' | '#@hidden-source-map' | '#@nosources-source-map' | boolean; + interface Performance { /** This property allows webpack to control what files are used to calculate performance hints. */ assetFilter?(assetFilename: string): boolean; From 1f64f18a900aa80a5492dbceaa98840095cccc7a Mon Sep 17 00:00:00 2001 From: Andrey Date: Sun, 9 Jul 2017 16:12:36 +0600 Subject: [PATCH 0266/1618] Update index.d.ts Update MobilePhoneLocale to support string 'any' --- types/validator/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/validator/index.d.ts b/types/validator/index.d.ts index 74bf331ed6..7c7283ebee 100644 --- a/types/validator/index.d.ts +++ b/types/validator/index.d.ts @@ -6,7 +6,7 @@ declare namespace ValidatorJS { type AlphaLocale = "ar" | "ar-AE" | "ar-BH" | "ar-DZ" | "ar-EG" | "ar-IQ" | "ar-JO" | "ar-KW" | "ar-LB" | "ar-LY" | "ar-MA" | "ar-QA" | "ar-QM" | "ar-SA" | "ar-SD" | "ar-SY" | "ar-TN" | "ar-YE" | "cs-CZ" | "de-DE" | "en-AU" | "en-GB" | "en-HK" | "en-IN" | "en-NZ" | "en-US" | "en-ZA" | "en-ZM" | "es-ES" | "fr-FR" | "hu-HU" | "nl-NL" | "pl-PL" | "pt-BR" | "pt-PT" | "ru-RU" | "sr-RS" | "sr-RS@latin" | "tr-TR"; type AlphanumericLocale = "ar" | "ar-AE" | "ar-BH" | "ar-DZ" | "ar-EG" | "ar-IQ" | "ar-JO" | "ar-KW" | "ar-LB" | "ar-LY" | "ar-MA" | "ar-QA" | "ar-QM" | "ar-SA" | "ar-SD" | "ar-SY" | "ar-TN" | "ar-YE" | "cs-CZ" | "de-DE" | "en-AU" | "en-GB" | "en-HK" | "en-IN" | "en-NZ" | "en-US" | "en-ZA" | "en-ZM" | "es-ES" | "fr-FR" | "fr-BE" | "hu-HU" | "nl-BE" | "nl-NL" | "pl-PL" | "pt-BR" | "pt-PT" | "ru-RU" | "sr-RS" | "sr-RS@latin" | "tr-TR"; - type MobilePhoneLocale = "ar-DZ" | "ar-SA" | "ar-SY" | "cs-CZ" | "de-DE" | "da-DK" | "el-GR" | "en-AU" | "en-GB" | "en-HK" | "en-IN" | "en-NZ" | "en-US" | "en-CA" | "en-ZA" | "en-ZM" | "es-ES" | "fi-FI" | "fr-FR" | "hu-HU" | "it-IT" | "ja-JP" | "ms-MY" | "nb-NO" | "nn-NO" | "pl-PL" | "pt-PT" | "ru-RU" | "sr-RS" | "tr-TR" | "vi-VN" | "zh-CN" | "zh-TW" + type MobilePhoneLocale = "ar-DZ" | "ar-SA" | "ar-SY" | "cs-CZ" | "de-DE" | "da-DK" | "el-GR" | "en-AU" | "en-GB" | "en-HK" | "en-IN" | "en-NZ" | "en-US" | "en-CA" | "en-ZA" | "en-ZM" | "es-ES" | "fi-FI" | "fr-FR" | "hu-HU" | "it-IT" | "ja-JP" | "ms-MY" | "nb-NO" | "nn-NO" | "pl-PL" | "pt-PT" | "ru-RU" | "sr-RS" | "tr-TR" | "vi-VN" | "zh-CN" | "zh-TW" | "any"; interface ValidatorStatic { From 82a14c721f87dca5167e4495b3afd1ecb372bfa3 Mon Sep 17 00:00:00 2001 From: benny-medflyt Date: Sun, 9 Jul 2017 14:42:26 +0300 Subject: [PATCH 0267/1618] [googlemaps] Fix DirectionsRequest to support LatLngLiteral --- types/googlemaps/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index ac9566757f..b36032d298 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1255,7 +1255,7 @@ declare namespace google.maps { * Location of destination. This can be specified as either a string to be geocoded, or a LatLng, * or a Place. Required. */ - destination?: string|LatLng|Place; + destination?: string|LatLng|LatLngLiteral|Place; /** Deprecated. Use drivingOptions field instead */ durationInTraffic?: boolean; /** @@ -1273,7 +1273,7 @@ declare namespace google.maps { * Location of origin. This can be specified as either a string to be geocoded, or a LatLng, or a Place. * Required. */ - origin?: string|LatLng|Place; + origin?: string|LatLng|LatLngLiteral|Place; /** Whether or not route alternatives should be provided. Optional. */ provideRouteAlternatives?: boolean; /** Region code used as a bias for geocoding requests. Optional. */ From 43ffe03a9b62684b06e12ae61f52e61919aa9008 Mon Sep 17 00:00:00 2001 From: Stepan Burguchev Date: Sun, 9 Jul 2017 14:52:31 +0300 Subject: [PATCH 0268/1618] enforce strong typing for partial objects and property names --- types/seamless-immutable/index.d.ts | 81 +++++++----- .../seamless-immutable-tests.ts | 123 ++++++++++++------ 2 files changed, 132 insertions(+), 72 deletions(-) diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index ceeccd7b3f..046a60259a 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -15,49 +15,60 @@ export = SeamlessImmutable; declare namespace SeamlessImmutable { - interface MergeConfig { - deep?: boolean; - merger?: Function; - } + type DeepPartial = { + [P in keyof T]?: DeepPartial; + }; - interface Options { - prototype?: any; - } + interface MergeConfig { + deep?: boolean; + merger?: Function; + } - interface AsMutableOptions { - deep: boolean; - } + interface Options { + prototype?: any; + } - export interface ImmutableObject { - set(property: string, value: any): ImmutableObject; - setIn(propertyPath: Array, value: any): ImmutableObject; + interface AsMutableOptions { + deep: boolean; + } - asMutable(): T; - asMutable(opts: AsMutableOptions): T; + export interface ImmutableObject { + set(property: K, value: T[K]): T & ImmutableObject; + setIn + (propertyPath: [ K ], value: T[K]): T & ImmutableObject; + setIn + (propertyPath: [ K, L ], value: T[K][L]): T & ImmutableObject; + setIn + (propertyPath: [ K, L, M ], value: T[K][L][M]): T & ImmutableObject; + setIn + (propertyPath: [ K, L, M, N ], value: T[K][L][M][N]): T & ImmutableObject; - merge(part: any, config?: MergeConfig): ImmutableObject; + asMutable(): T; + asMutable(opts: AsMutableOptions): T; - update(property: string, updaterFunction: (value: any, ...additionalParamters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn(propertyPath: Array, updaterFunction: (value: any, ...additionalParamters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + merge(part: DeepPartial, config?: MergeConfig): T & ImmutableObject; - without(property: string): ImmutableObject; - without(...properties: string[]): ImmutableObject; - without(filter: (value: any, key: string) => boolean): ImmutableObject; - } + update(property: string, updaterFunction: (value: any, ...additionalParamters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn(propertyPath: Array, updaterFunction: (value: any, ...additionalParamters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - export interface ImmutableArray { - asMutable(): Array; - asMutable(opts: AsMutableOptions): Array; - asObject(toKeyValue: (item: T) => Array): ImmutableObject; - flatMap(mapFunction: (item: T) => Array): ImmutableArray; - } + without(property: string): ImmutableObject; + without(...properties: string[]): ImmutableObject; + without(filter: (value: any, key: string) => boolean): ImmutableObject; + } - // an immutable object is both of Type T (i.e., looks like a normal T) and of type Immutable - export type Immutable = T & (ImmutableObject | ImmutableArray); + export interface ImmutableArray { + asMutable(): Array; + asMutable(opts: AsMutableOptions): Array; + asObject(toKeyValue: (item: T) => [string, any]): ImmutableObject; + flatMap(mapFunction: (item: T) => Array): TTarget[] & ImmutableArray; + } - export function from(obj: Array, options?: Options): Array & ImmutableArray; - export function from(obj: T, options?: Options): T & ImmutableObject; + // an immutable object is both of Type T (i.e., looks like a normal T) and of type Immutable + export type Immutable = T & (ImmutableObject | ImmutableArray); - export function isImmutable(target: any): boolean; - export function ImmutableError(message: string): Error; -} \ No newline at end of file + export function from(obj: Array, options?: Options): Array & ImmutableArray; + export function from(obj: T, options?: Options): T & ImmutableObject; + + export function isImmutable(target: any): boolean; + export function ImmutableError(message: string): Error; +} diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index 745135b6a9..6ab7fd25be 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -1,51 +1,100 @@ -import SI = require("seamless-immutable"); +import * as Immutable from 'seamless-immutable'; -// Immutable instance method test -const isImmutable: boolean = SI.isImmutable(SI.from([0, 2])); -const error: Error = SI.ImmutableError("error"); +// Test types -// Immutable Array tests -const siArray: SI.ImmutableArray = SI.from([0, 1, 2]); - -const mutableArray: Array = siArray.asMutable(); -const mutableArray2: Array = siArray.asMutable({ deep: true }); -const arrayToObject: SI.ImmutableObject = siArray.asObject((value: number) => - [value.toString(), value] -); -const flatMappedArray: SI.ImmutableArray = siArray.flatMap((value: number) => - [value, value] -); - -// Immutable Object tests interface User { - firstName: string; - lastName: string; + firstName: string; + lastName: string; }; interface Address { - line1: string; + line1: string; } interface ExtendedUser extends User { - address: Address; + address: Address; } -const siObject: SI.ImmutableObject = SI.from({ - firstName: "Mike", - lastName: "test" -}); -const extUser: SI.ImmutableObject = siObject.set("address", { - line1: "test" -}); +// +// Constructors +// --------------------------------------------------------------- -const updatedAddress: SI.ImmutableObject = extUser.setIn(["address", "line1"], "test2"); -const mutableUser: ExtendedUser = updatedAddress.asMutable(); -const mutableUser2: ExtendedUser = updatedAddress.asMutable({ deep: true }); -const mergedUser: SI.ImmutableObject = siObject.merge({ lastName: "hello" }); -const updatedUser: SI.ImmutableObject = extUser.update("firstName", (firstName): string => - firstName + "hehe" +{ + interface User { + firstName: string; + lastName: string; + }; + + const arrayOfNumbers: number[] & Immutable.ImmutableArray = Immutable.from([0, 2]); + const user: User & Immutable.ImmutableObject = Immutable.from({ + firstName: 'Angry', + lastName: 'Monkey' + }); + const error: Error = Immutable.ImmutableError('error'); +} + +// +// Static utilities +// --------------------------------------------------------------- + +{ + const isImmutable: boolean = Immutable.isImmutable(Immutable.from([0, 2])); +} + +// +// Instance syntax: immutable array +// --------------------------------------------------------------- +{ + const array: User[] & Immutable.ImmutableArray = Immutable.from([ { firstName: 'Angry', lastName: 'Monkey' } ]); + + // asMutable + const mutableArray1: User[] = array.asMutable(); + const mutableArray2: User[] = array.asMutable({ deep: true }); + + // flatMap + const flatMappedArray: User[] & Immutable.ImmutableArray = array.flatMap((value: User) => + [value, value] + ); + + // asObject + const arrayToObject1: Immutable.ImmutableObject = array.asObject((value) => [value.toString(), value]); +} + +// +// Instance syntax: immutable object +// --------------------------------------------------------------- + +{ + const immutableUser: Immutable.ImmutableObject = Immutable.from({ + firstName: 'Pure', + lastName: 'Gold' + }); + const immutableUserEx: Immutable.ImmutableObject = Immutable.from({ + firstName: 'Hairy', + lastName: 'Dog', + address: { + line1: 'Big house' + } + }); + + // set: property name is strongly checked + const updatedUser: Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); + + // setIn: property path is strongly checked for up to 4 arguments + const updatedUser2: Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); + + // asMutable + const mutableUser1: User = immutableUser.asMutable(); + const mutableUser2: User = immutableUser.asMutable({ deep: true }); + + // merge: merged part is strongly checked as a deeply partial object + const mergedUser: Immutable.ImmutableObject = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); +} + +const updatedUser: Immutable.ImmutableObject = extUser.update("firstName", (firstName): string => + firstName + "hehe" ); -const updatedInUser: SI.ImmutableObject = extUser.updateIn(["address", "line1"], (line): string => - line + "new address" +const updatedInUser: Immutable.ImmutableObject = extUser.updateIn(["address", "line1"], (line): string => + line + "new address" ); -const userWithoutAddress: SI.ImmutableObject = extUser.without("address"); +const userWithoutAddress: Immutable.ImmutableObject = extUser.without("address"); From 8158a75e87bcd55b83147cf8f3af210d12cb2fb6 Mon Sep 17 00:00:00 2001 From: Flur Date: Sun, 9 Jul 2017 16:41:18 +0300 Subject: [PATCH 0269/1618] - changes accrording to review --- types/three/index.d.ts | 6 +++--- types/three/three-core.d.ts | 4 ++-- types/three/three-ddsloader.d.ts | 10 +++++++++- types/three/three-mtlloader.d.ts | 2 +- types/three/three-objloader.d.ts | 2 +- 5 files changed, 16 insertions(+), 8 deletions(-) diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 2df7c306ed..afe64c399e 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -10,11 +10,14 @@ export * from "./three-colladaLoader"; export * from "./three-copyshader"; export * from "./three-css3drenderer"; export * from "./three-ctmloader"; +export * from "./three-ddsloader"; export * from "./three-editorcontrols"; export * from "./three-effectcomposer"; export * from "./three-examples"; export * from "./three-FirstPersonControls"; export * from "./three-maskpass"; +export * from "./three-mtlloader"; +export * from "./three-objloader"; export * from "./three-octree"; export * from "./three-orbitcontrols"; export * from "./three-orthographictrackballcontrols"; @@ -25,8 +28,5 @@ export * from "./three-trackballcontrols"; export * from "./three-transformcontrols"; export * from "./three-vrcontrols"; export * from "./three-vreffect"; -export * from "./three-objloader"; -export * from "./three-mtlloader"; -export * from "./three-ddsloader"; export as namespace THREE; diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 3b89456ba9..a666411d24 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -1609,13 +1609,13 @@ export class Object3D extends EventDispatcher { * Calls before rendering object */ onBeforeRender: (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, geometry: THREE.Geometry | THREE.BufferGeometry, - material: THREE.Material, group: THREE.Group) => any; + material: THREE.Material, group: THREE.Group) => void; /** * Calls after rendering object */ onAfterRender: (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, geometry: THREE.Geometry | THREE.BufferGeometry, - material: THREE.Material, group: THREE.Group) => any; + material: THREE.Material, group: THREE.Group) => void; /** * diff --git a/types/three/three-ddsloader.d.ts b/types/three/three-ddsloader.d.ts index 7f2587adcc..8d8f85bd0e 100644 --- a/types/three/three-ddsloader.d.ts +++ b/types/three/three-ddsloader.d.ts @@ -2,10 +2,18 @@ import {CompressedPixelFormat, CompressedTextureLoader} from "./three-core"; +export interface Dds { + mipmaps: ImageData[], + width: number, + height: number, + format: CompressedPixelFormat, + mipmapCount: number +} + export class DDSLoader extends CompressedTextureLoader { constructor(); - parse(buffer: string, loadMipmaps: boolean) : { mipmaps: { data: Uint8Array, width: number, height: number }[], width: number, height: number, format: CompressedPixelFormat, mipmapCount: number }; + parse(buffer: string, loadMipmaps: boolean) : Dds; } diff --git a/types/three/three-mtlloader.d.ts b/types/three/three-mtlloader.d.ts index 8cac40cef2..a795a293de 100644 --- a/types/three/three-mtlloader.d.ts +++ b/types/three/three-mtlloader.d.ts @@ -49,6 +49,6 @@ export class MaterialCreator { create( materialName: string ) : Material; createMaterial_( materialName: string ) : Material; getTextureParams( value: string, matParams: any ) : any; - loadTexture(url: string, mapping: any, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): Texture; + loadTexture(url: string, mapping: any, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Texture; } diff --git a/types/three/three-objloader.d.ts b/types/three/three-objloader.d.ts index b98a00f9c5..62403eeebb 100644 --- a/types/three/three-objloader.d.ts +++ b/types/three/three-objloader.d.ts @@ -13,7 +13,7 @@ export class OBJLoader { materials: Material[]; path: string; - load(url: string, onLoad: (group: Group) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + load(url: string, onLoad: (group: Group) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; parse(data: string) : Group; setPath(value: string) : void; setMaterials(materials: MaterialCreator) : void; From 1b91b09021f33ca11d466eb99509b114ebdab5d7 Mon Sep 17 00:00:00 2001 From: Stepan Burguchev Date: Sun, 9 Jul 2017 16:49:49 +0300 Subject: [PATCH 0270/1618] enforce strong typing in update, updateIn, without --- types/seamless-immutable/index.d.ts | 20 +++++++++------ .../seamless-immutable-tests.ts | 25 +++++++++++-------- 2 files changed, 27 insertions(+), 18 deletions(-) diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index 046a60259a..a121e584f1 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -48,12 +48,19 @@ declare namespace SeamlessImmutable { merge(part: DeepPartial, config?: MergeConfig): T & ImmutableObject; - update(property: string, updaterFunction: (value: any, ...additionalParamters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn(propertyPath: Array, updaterFunction: (value: any, ...additionalParamters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + update(property: K, updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + updateIn + (propertyPath: [ K ], updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + updateIn + (propertyPath: [ K, L ], updaterFunction: (value: T[K][L], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + updateIn + (propertyPath: [ K, L, M ], updaterFunction: (value: T[K][L][M], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + updateIn + (propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; - without(property: string): ImmutableObject; - without(...properties: string[]): ImmutableObject; - without(filter: (value: any, key: string) => boolean): ImmutableObject; + without(property: keyof T): TTarget & ImmutableObject; + without(...properties: Array): TTarget & ImmutableObject; + without(filter: (value: T[keyof T], key: keyof T) => boolean): TTarget & ImmutableObject; } export interface ImmutableArray { @@ -63,8 +70,7 @@ declare namespace SeamlessImmutable { flatMap(mapFunction: (item: T) => Array): TTarget[] & ImmutableArray; } - // an immutable object is both of Type T (i.e., looks like a normal T) and of type Immutable - export type Immutable = T & (ImmutableObject | ImmutableArray); + export type Immutable = ImmutableObject | ImmutableArray; export function from(obj: Array, options?: Options): Array & ImmutableArray; export function from(obj: T, options?: Options): T & ImmutableObject; diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index 6ab7fd25be..e5f7411d55 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -78,23 +78,26 @@ interface ExtendedUser extends User { }); // set: property name is strongly checked - const updatedUser: Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); + const updatedUser: User & Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); // setIn: property path is strongly checked for up to 4 arguments - const updatedUser2: Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); + const updatedUser2: ExtendedUser & Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); // asMutable const mutableUser1: User = immutableUser.asMutable(); const mutableUser2: User = immutableUser.asMutable({ deep: true }); // merge: merged part is strongly checked as a deeply partial object - const mergedUser: Immutable.ImmutableObject = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); -} + const mergedUser: User & Immutable.ImmutableObject = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); -const updatedUser: Immutable.ImmutableObject = extUser.update("firstName", (firstName): string => - firstName + "hehe" -); -const updatedInUser: Immutable.ImmutableObject = extUser.updateIn(["address", "line1"], (line): string => - line + "new address" -); -const userWithoutAddress: Immutable.ImmutableObject = extUser.without("address"); + // update: property name is strongly checked + const updatedUser3: User & Immutable.ImmutableObject = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); + + // updateIn: property path is strongly checked for up to 4 arguments + const updatedUser4: User & Immutable.ImmutableObject = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); + + // without: the return type must be specified explicitly or it will be `any` + const simpleUser1: Immutable.ImmutableObject = immutableUserEx.without('address'); + const simpleUser2: User & Immutable.ImmutableObject = immutableUserEx.without('address'); + const simpleUser3: Immutable.ImmutableObject = immutableUserEx.without('firstName', 'lastName'); +} From 8869554ffe7a46177a1856c202cd9c7898492439 Mon Sep 17 00:00:00 2001 From: Ifiok Jr Date: Sun, 9 Jul 2017 15:48:19 +0100 Subject: [PATCH 0271/1618] initial additions for react-native-fbsdk --- types/react-native-fbsdk/index.d.ts | 1039 +++++++++++++++++ .../react-native-fbsdk-tests.tsx | 36 + types/react-native-fbsdk/tsconfig.json | 24 + types/react-native-fbsdk/tslint.json | 1 + 4 files changed, 1100 insertions(+) create mode 100644 types/react-native-fbsdk/index.d.ts create mode 100644 types/react-native-fbsdk/react-native-fbsdk-tests.tsx create mode 100644 types/react-native-fbsdk/tsconfig.json create mode 100644 types/react-native-fbsdk/tslint.json diff --git a/types/react-native-fbsdk/index.d.ts b/types/react-native-fbsdk/index.d.ts new file mode 100644 index 0000000000..c27fdb7671 --- /dev/null +++ b/types/react-native-fbsdk/index.d.ts @@ -0,0 +1,1039 @@ +// Type definitions for react-native-fbsdk 0.6 +// Project: https://github.com/facebook/react-native-fbsdk +// Definitions by: Ifiok Jr. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { ComponentClass, Component } from 'react'; +import { StyleSheet } from 'react-native'; +import { LoginManager } from 'react-native-fbsdk'; +declare namespace FBSDK { + /** + * Specifies the privacy of a group. + */ + type AppGroupPrivacy = + // Anyone can see the group, who's in in and what members post. + 'Open' | + // Anyone can see the group and who's in it, but only members can see posts. + 'Closed'; + + /** + * A model for app invites. + */ + interface AppGroupCreationContent { + /** + * The description of the group. + */ + description: string; + + /** + * The name of the group. + */ + name: string; + + /** + * The privacy for the group. + */ + privacy: AppGroupPrivacy; + } + + /** + * A model for app invites. + */ + interface AppInviteContent { + /** + * A URL to a preview image that will be displayed with the app invite. + * This is optional. If you don't include it, a fallback image will be used. + */ + previewImageUrl?: string; + + /** + * An app link target that will be used as a target when the user accepts the invite. + */ + applinkUrl: string; + + /** + * Promotional code to be displayed while sending and receiving the invite. + * This is optional. This can be between 0 and 10 characters long and can contain + * alphanumeric characters only. To set a promo code, you need to set promo text. + */ + promotionCode?: string; + + /** + * Promotional text to be displayed while sending and receiving the invite. + * This is optional. This can be between 0 and 80 characters long and can contain + * alphanumeric and spaces only. + */ + promotionText?: string; + } + + type GameRequestActionType = + // The user is sending an object to their friends. + 'send' | + // The user is asking for an object from friends. + 'askfor' | + // It is the turn of the friends to play against the user in a match. + 'turn'; + + type GameRequestFilters = + // Friends using the app can be displayed. + 'app_users' | + // Friends not using the app can be displayed. + 'app_non_users'; + + /** + * A model for a game request. + */ + interface GameRequestContent { + /** + * A plain-text message to be sent as part of the request. Required. + */ + message: string; + + /** + * Used when defining additional context about the nature of the request. + * The parameter 'objectID' is required if the action type is either 'send' or 'ask-for'. + */ + actionType?: GameRequestActionType; + + /** + * Additional freeform data you may pass for tracking. The maximum length is 255 characters. + */ + data?: string; + + /** + * Controls the set of friends someone sees if a multi-friend selector is shown. + */ + filters?: GameRequestFilters; + + /** + * The Open Graph object ID of the object being sent/asked for. This cannot be null for ActionType SEND and + * ASKFOR. + */ + objectId?: string; + + /** + * An array of user IDs, usernames or invite tokens of people to send requests to. + */ + recipients?: string[]; + + /** + * An array of user IDs that will be included in the dialog as the first suggested friends. + * Can't be used together with filters. + */ + suggestions?: string[]; + + /** + * The title for the dialog. + */ + title?: string; + } + + type ObjectIdActionType = 'unknown' | 'open_graph' | 'page'; + + /** + * A base interface for content to be shared. + */ + interface ObjectIdAndType { + /** + * The object ID, this can be a URL or a Facebook ID. + */ + objectId: string; + + /** + * Encapsulates the valid values for the facebook:object_type + * attribute for a LikeView + */ + objectType: ObjectIdActionType; + } + + type ShareContent = ShareLinkContent | SharePhotoContent | ShareVideoContent | ShareOpenGraphContent; + /** + * A base interface for content to be shared. + */ + interface ShareContentCommonParameters { + /** + * List of IDs for taggable people to tag with this content. + */ + peopleIds?: string[]; + + /** + * The ID for a place to tag with this content. + */ + placeId?: string; + + /** + * A value to be added to the referrer URL when a person follows a link from + * this shared content on feed. + */ + ref?: string; + + /** + * A hashtag to be added to the share interface. The hashtag must be 32 characters or less. + */ + hashtag?: string; + } + + /** + * A model for status and link content to be shared. + */ + interface ShareLinkContent { + /** + * The type of content to be shared is link. + */ + contentType: 'link'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl: string; + + /** + * The Description of the link. + * If not specified, this field is automatically populated by information scraped + * from the contentURL, typically the title of the page. + * @deprecated `contentDescription` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. + */ + contentDescription?: string; + + /** + * The title to display for this link. + * @deprecated `contentTitle` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. + */ + contentTitle?: string; + + /** + * The URL of a picture to attach to this comment. + * @deprecated `imageUrl` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. + */ + imageUrl?: string; + + /** + * The predefined quote to attach to this comment. + * If specified, the quote text will render with custom styling on top of the link. + */ + quote?: string; + } + + interface OpenGraphProperties { + [key: string]: OpenGraphValue; + } + + interface OpenGraphValue { + type: OpenGraphValueType; + + value: any; + } + + type OpenGraphValueType = + 'number' | + 'open-graph-object' | + 'photo' | + 'string'; + + interface ShareOpenGraphValueContainer { + /** + * Sets a number for the specified key. + */ + // tslint:disable-next-line:variable-name + putNumber(key: string, number: number): void; + + /** + * Sets an open graph object for the specified key. + */ + putObject(key: string, object: ShareOpenGraphValueContainer): void; + + /** + * Sets a photo for the specified key. + */ + putPhoto(key: string, photo: SharePhoto): void; + + /** + * Sets a string for the specified key. + */ + // tslint:disable-next-line:variable-name + putString(key: string, string: string): void; + + /** + * Gets an entry for the given key. + */ + getEntry(key: string): OpenGraphValue; + } + + /** + * Represents an interface for adding and retrieving values to open graph objects and actions. + */ + class ShareOpenGraphValueContainer { + private _properties: OpenGraphProperties; + + constructor(properties: OpenGraphProperties); + } + + /** + * Represents an open graph action. + */ + class ShareOpenGraphAction extends ShareOpenGraphValueContainer { + /** + * The action type. + */ + actionType: string; + + constructor(actionType: string); + } + + /** + * Represents a content object containing information about an Open Graph Action. + */ + interface ShareOpenGraphContent { + /** + * The type of content to be shared is open graph content. + */ + contentType: 'open-graph'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Open Graph Action to be shared. + */ + action: ShareOpenGraphAction; + + /** + * Property name that points to the primary Open Graph Object in the action. + */ + previewPropertyName: string; + } + + /** + * Represents an open graph object. + */ + class ShareOpenGraphObject extends ShareOpenGraphValueContainer {} + + /** + * A photo for sharing. + */ + interface SharePhoto { + /** + * The URL to the photo. + * Note that when sharing SharePhotoContent with Share Button, the imageUrl + * of a SharePhoto cannot be the Uri of an image on the web. + */ + imageUrl: string; + + /** + * Specifies whether the photo was generated by the user or the application. + */ + userGenerated?: boolean; + + /** + * The user generated caption for the photo. Note that the 'caption' must + * come from the user, as pre-filled content is forbidden by the platform + * Policies (2.3). + */ + caption?: string; + } + + /** + * A model for photo content to be shared. + */ + interface SharePhotoContent { + /** + * The type of content to be shared is photo. + */ + contentType: 'photo'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Photos to be shared. + */ + photos: SharePhoto[]; + } + + /** + * A video for sharing. + */ + interface ShareVideo { + /** + * The URL to the video. Must point to the location of the video on disk. + */ + localUrl: string; + } + + /** + * A model for video content to be shared. + */ + interface ShareVideoContent { + /** + * The type of content to be shared is photo. + */ + contentType: 'video'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Video to be shared. + */ + video: ShareVideo; + + /** + * Description of the video. + */ + contentDescription?: string; + + /** + * Title of the video. + */ + contentTitle?: string; + + /** + * The photo that represents the video. + */ + previewPhoto?: SharePhoto; + } + + interface AccessTokenMap { + accessToken: string; + applicationID: string; + userID: string; + permissions: string[]; + declinedPermissions: string[]; + accessTokenSource?: string; + expirationTime: number; + lastRefreshTime: number; + } + + /** + * Represents an immutable access token for using Facebook services. + */ + class AccessToken { + /** + * The access token string. + */ + accessToken: string; + + /** + * The app ID. + */ + applicationID: string; + + /** + * The user ID. + */ + userID: string; + + /** + * The known granted permissions. + */ + permissions: string[]; + + /** + * The known declined permissions. + */ + declinedPermissions: string[]; + + /** + * The source of access token. + * @platform android + */ + accessTokenSource?: string; + + /** + * The expiration time of the access token. + * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. + */ + expirationTime: number; + + /** + * The last refresh time of the access token. + * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. + */ + lastRefreshTime: number; + /** + * Getter for the access token that is current for the application. + */ + static getCurrentAccessToken(): Promise; + + /** + * Setter for the access token that is current for the application. + */ + static setCurrentAccessToken(accessToken: AccessTokenMap): void; + + /** + * Updates the current access token with up to date permissions, + * and extends the expiration date, if extension is possible. + */ + + static refreshCurrentAccessTokenAsync(): Promise; + + constructor(tokenMap: AccessTokenMap); + + /** + * Gets the date at which the access token expires. The value is the number of + * milliseconds since Jan. 1, 1970, midnight GMT. + */ + getExpires(): number; + + /** + * Get the list of permissions associated with this access token. Note that the most up-to-date + * list of permissions is maintained by Facebook, so this list may be outdated if permissions + * have been added or removed since the time the AccessToken object was created. See + * https://developers.facebook.com/docs/reference/login/#permissions for details. + */ + getPermissions(): string[]; + + /** + * Gets the list of permissions declined by the user with this access token. It represents the + * entire set of permissions that have been requested and declined. Note that the most + * up-to-date list of permissions is maintained by Facebook, so this list may be outdated if + * permissions have been granted or declined since the last time an AccessToken object was + * created. See https://developers.facebook.com/docs/reference/login/#permissions for details. + */ + getDeclinedPermissions(): string[]; + + /** + * Gets the date at which the token was last refreshed. Since tokens expire, the Facebook SDK + * will attempt to renew them periodically. The value is the number of milliseconds since + * Jan. 1, 1970, midnight GMT. + */ + getLastRefresh(): number; + + /** + * Gets the ID of the Facebook Application associated with this access token. + */ + getApplicationId(): string; + + /** + * Gets user ID associated with this access token. + */ + getUserId(): string; + } + + /** + * Controls when an AppEventsLogger sends log events to the server + */ + type AppEventsFlushBehavior = + /** + * Flush automatically: periodically (every 15 seconds or after every 100 events), and + * always at app reactivation. This is the default value. + */ + 'auto' | + /** + * Only flush when AppEventsLogger.flush() is explicitly invoked. + */ + 'explicity-only'; + + interface Params { + [key: string]: string | number; + } + + interface AppEventsLogger { + /** + * Sets the current event flushing behavior specifying when events + * are sent back to Facebook servers. + */ + setFlushBehavior(flushBehavior: AppEventsFlushBehavior): void; + + /** + * Logs an event with eventName and optional arguments. + * This function supports the following usage: + * logEvent(eventName: string); + * logEvent(eventName: string, valueToSum: number); + * logEvent(eventName: string, parameters: {[key:string]:string|number}); + * logEvent(eventName: string, valueToSum: number, parameters: {[key:string]:string|number}); + * See https://developers.facebook.com/docs/app-events/android for detail. + */ + logEvent(eventName: string, ...args: Array): void; + + /** + * Logs a purchase. See http://en.wikipedia.org/wiki/ISO_4217 for currencyCode. + */ + logPurchase(purchaseAmount: number, currencyCode: string, parameters?: object): void; + + /** + * Logs an app event that tracks that the application was open via Push Notification. + */ + logPushNotificationOpen(payload?: object): void; + + /** + * Explicitly kicks off flushing of events to Facebook. + */ + flush(): void; + + /** + * For iOS only, sets and sends device token to register the current application for push notifications. + * @platform ios + */ + setPushNotificationsDeviceToken(deviceToken: string): void; + + /** + * For Android only, sets and sends registration id to register the current app for push notifications. + * @platform Android + */ + setPushNotificationsRegistrationId(registrationId: string): void; + } + + const AppEventsLogger: AppEventsLogger; + + interface AppInviteDialog { + /** + * Check if the dialog can be shown. + */ + canShow(): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(appInviteContent: AppInviteContent): Promise; + } + + const AppInviteDialog: AppInviteDialog; + + interface GameRequestDialog { + /** + * Check if the dialog can be shown. + */ + canShow(): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(gameRequestContent: GameRequestContent): Promise; + } + + const GameRequestDialog: GameRequestDialog; + + type GraphRequestCallback = (error?: object, result?: object) => void; + interface GraphRequestConfig { + /** + * The httpMethod to use for the request, for example "GET" or "POST". + */ + httpMethod?: string; + /** + * The Graph API version to use (e.g., "v2.0") + */ + version?: string; + /** + * The request parameters. + */ + parameters?: GraphRequestParameters; + /** + * The access token used by the request. + */ + accessToken?: string; + } + + interface GraphRequestParameters { + [key: string]: object; + } + + /** + * Represents a Graph API request and provides batch request supports. + */ + class GraphRequest { + /** + * The Graph API endpoint to use for the request, for example "me". + */ + graphPath: string; + + /** + * The optional config for the request. + */ + config?: GraphRequestConfig; + + /** + * Called upon completion or failure of the request. + */ + callback?: GraphRequestCallback; + + /** + * Constructs a new Graph API request. + */ + constructor(graphPath: string, config?: GraphRequestConfig | null, callback?: GraphRequestCallback); + + /** + * Adds a string parameter to the request. + */ + addStringParameter(paramString: string, key: string): void; + } + + class GraphRequestManager { + requestBatch: GraphRequest[]; + requestCallbacks: Array; + batchCallback: GraphRequestCallback; + constructor(); + + /** + * Add a graph request. + */ + addRequest(request: GraphRequest): GraphRequestManager; + + /** + * Add call back to the GraphRequestManager. Only one callback can be added. + * Note that invocation of the batch callback does not indicate success of every + * graph request made, only that the entire batch has finished executing. + */ + addBatchCallback(callback: GraphRequestCallback): GraphRequestManager; + + /** + * Executes requests in a batch. + * Note that when there's an issue with network connection the batch callback + * behavior differs in Android and iOS. + * On iOS, the batch callback returns an error if the batch fails with a network error. + * On Android, the batch callback always returns {"result": "batch finished executing"} + * after the batch time out. This is because detecting network status requires + * extra permission and it's unncessary for the sdk. Instead, you can use the NetInfo module + * in react-native to get the network status. + */ + start(timeout?: number): void; + } + + type AuxiliaryViewPosition = 'top' | 'bottom' | 'inline'; + type HorizontalAlignment = 'center' | 'left' | 'right'; + type LikeViewStyle = 'button'| // Note 'button' is only available on Android. + 'standard' | + 'box_count'; + + interface LikeViewProps { + /** + * The objectId and type for the object to like. + */ + objectIdAndType: ObjectIdAndType; + + /** + * The style to use for the receiver. Distinct from React styling. + */ + likeViewStyle?: LikeViewStyle; + + /** + * The position for the auxiliary view for the receiver. + */ + auxiliaryViewPosition?: AuxiliaryViewPosition; + + /** + * The text alignment of the social sentence. + */ + horizontalAlignment?: HorizontalAlignment; + + /** + * The foreground color to use for the content of the receiver. + */ + foregroundColor?: number; + + /** + * If true, a sound is played when the receiver is toggled. + */ + soundEnabled?: boolean; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class LikeView extends Component {} + + type TooltipBehaviorIOS = 'auto' | 'force_display' | 'disable'; + + interface LoginButtonProps { + /** + * Represents the read permissions to request when the login button + * is pressed. + */ + readPermissions?: string[]; + + /** + * Represents the publish permissions to request when the login + * button is pressed. + */ + publishPermissions?: string[]; + + /** + * The callback invoked upon error/completion of a login request. + */ + onLoginFinished?(error: object, result: LoginResult): void; + + /** + * The callback invoked upon completion of a logout request. + */ + onLogoutFinished?(): void; + + /** + * The behavior to use when attempting a login. + * @platform android + */ + loginBehaviorAndroid?: LoginBehaviorAndroid; + + /** + * The behavior to use when attempting a login. + * @platform ios + */ + loginBehaviorIOS?: LoginBehaviorIOS; + + /** + * The default audience to target when attempting a login. + */ + defaultAudience?: DefaultAudience; + + /** + * For iOS only, the desired tooltip behavior. + * @platform ios + */ + tooltipBehaviorIOS?: TooltipBehaviorIOS; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class LoginButton extends Component { + private _eventHandler(event: object): void; + } + + /** + * Indicates which default audience to use for sessions that post data to Facebook. + */ + type DefaultAudience = + // Indicates that the user's friends are able to see posts made by the application. + 'friends' | + // Indicates that all Facebook users are able to see posts made by the application. + 'everyone' | + // Indicates that only the user is able to see posts made by the application. + 'only_me'; + + type LoginBehavior = LoginBehaviorIOS | LoginBehaviorAndroid; + + /** + * Indicate how Facebook Login should be attempted on Android. + */ + type LoginBehaviorAndroid = + // Attempt login in using the Facebook App, and if that does not work fall back to web dialog auth. + 'native_with_fallback'| + // Only attempt to login using the Facebook App. + 'native_only'| + // Only the web dialog auth should be used. + 'web_only'; + + /** + * Indicate how Facebook Login should be attempted on iOS. + */ + type LoginBehaviorIOS = + // Attempts log in through the native Facebook app. + // The SDK may still use Safari instead. + // See details in https://developers.facebook.com/blog/post/2015/10/29/Facebook-Login-iOS9/ + 'native' | + // Attempts log in through the Safari browser. + 'browser' | + // Attempts log in through the Facebook account currently signed in through Settings. + 'system_account' | + // Attempts log in through a modal UIWebView pop-up. + 'web'; + + /** + * Shows the results of a login operation. + */ + interface LoginResult { + isCancelled: boolean; + grantedPermissions?: string[]; + declinedPermissions?: string[]; + } + + interface LoginManager { + /** + * Logs the user in with the requested read permissions. + */ + logInWithReadPermissions(permissions: string[]): Promise; + + /** + * Logs the user in with the requested publish permissions. + */ + logInWithPublishPermissions(permissions: string[]): Promise; + + /** + * Getter for the login behavior. + */ + getLoginBehavior(): Promise; + + /** + * Setter for the login behavior. + */ + setLoginBehavior(loginBehavior: LoginBehavior): void; + + /** + * Getter for the default audience. + */ + getDefaultAudience(): Promise; + + /** + * Setter for the default audience. + */ + setDefaultAudience(defaultAudience: DefaultAudience): void; + + /** + * Logs out the user. + */ + logOut(): void; + } + + const LoginManager: LoginManager; + + interface MessageDialog { + /** + * Check if the dialog can be shown. + */ + canShow(shareContent: ShareContent): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(shareContent: ShareContent): Promise; + + /** + * Sets whether or not the native message dialog should fail when it encounters a data error. + */ + setShouldFailOnDataError(shouldFailOnDataError: boolean): void; + } + + const MessageDialog: MessageDialog; + + interface SendButtonProps { + /** + * Content to be shared. + */ + shareContent: ShareContent; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class SendButton extends Component {} + + interface ShareApi { + /** + * Check if the content can be shared via share api. + */ + canShare(shareContent: ShareContent): Promise; + + /** + * For iOS only, creates a User Owned Open Graph object without an action. + * NOTE: Only one share action can be performed at a time. + * @platform ios + */ + createOpenGraphObject(openGraphObject: ShareOpenGraphObject): Promise; + + /** + * Shares the specified content with a message. + * NOTE: Only one share action can be performed at a time. + */ + share(shareContent: ShareContent, graphNode: string, message: string): Promise; + } + + const ShareApi: ShareApi; + + interface ShareButtonProps { + /** + * Content to be shared. + */ + shareContent: ShareContent; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class ShareButton extends Component {} + + type ShareDialogMode = ShareDialogModeIOS | ShareDialogModeAndroid; + type ShareDialogModeAndroid = + /** + * The mode is determined automatically. + */ + 'automatic'| + /** + * The native dialog is used. + */ + 'native'| + /** + * The web dialog is used. + */ + 'web'| + /** + * The feed dialog is used. + */ + 'feed'; + type ShareDialogModeIOS = + /* + * Acts with the most appropriate mode that is available. + */ + 'automatic'| + /* + * Displays the dialog in Safari. + */ + 'browser'| + /* + * Displays the dialog in a UIWebView within the app. + */ + 'webview'; + + interface ShareDialog { + /** + * Check if the dialog can be shown. + */ + canShow(shareContent: ShareContent): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(shareContent: ShareContent): Promise; + + /** + * Sets the mode for the share dialog. + */ + setMode(mode: ShareDialogMode): void; + + /** + * Sets whether or not the native share dialog should fail when it encounters a data error. + */ + setShouldFailOnDataError(shouldFailOnDataError: boolean): void; + } + + const ShareDialog: ShareDialog; +} +export as namespace FBSDK; +// tslint:disable-next-line:export-just-namespace +export = FBSDK; diff --git a/types/react-native-fbsdk/react-native-fbsdk-tests.tsx b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx new file mode 100644 index 0000000000..a6334f2cfc --- /dev/null +++ b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx @@ -0,0 +1,36 @@ +import * as React from 'react'; +import * as FBSDK from 'react-native-fbsdk'; +import { View } from 'react-native'; +import render from '../react-dom/index'; + +const { + LoginButton, + AccessToken +} = FBSDK; + +class Login extends React.Component { + render() { + return ( + + { + if (error) { + alert("login has error: " + result.error); + } else if (result.isCancelled) { + alert("login is cancelled."); + } else { + AccessToken.getCurrentAccessToken().then( + (data) => { + alert(data.accessToken.toString()) + } + ); + } + } + } + onLogoutFinished={() => alert("logout.")}/> + + ); + } +} diff --git a/types/react-native-fbsdk/tsconfig.json b/types/react-native-fbsdk/tsconfig.json new file mode 100644 index 0000000000..52ea75b5cb --- /dev/null +++ b/types/react-native-fbsdk/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-native-elements-tests.tsx" + ] +} diff --git a/types/react-native-fbsdk/tslint.json b/types/react-native-fbsdk/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-fbsdk/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c7ce1df7bf9acc37165ae8dec44467194df9e2be Mon Sep 17 00:00:00 2001 From: ikatyang Date: Sun, 9 Jul 2017 23:05:19 +0800 Subject: [PATCH 0272/1618] feat(yeoman-test): initial commit --- types/yeoman-test/index.d.ts | 242 +++++++++++++++++++++++++ types/yeoman-test/tsconfig.json | 22 +++ types/yeoman-test/tslint.json | 3 + types/yeoman-test/yeoman-test-tests.ts | 65 +++++++ 4 files changed, 332 insertions(+) create mode 100644 types/yeoman-test/index.d.ts create mode 100644 types/yeoman-test/tsconfig.json create mode 100644 types/yeoman-test/tslint.json create mode 100644 types/yeoman-test/yeoman-test-tests.ts diff --git a/types/yeoman-test/index.d.ts b/types/yeoman-test/index.d.ts new file mode 100644 index 0000000000..8d3c79ed22 --- /dev/null +++ b/types/yeoman-test/index.d.ts @@ -0,0 +1,242 @@ +// Type definitions for yeoman-test 1.7 +// Project: https://github.com/yeoman/yeoman-test +// Definitions by: Ika +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import {EventEmitter} from 'events'; +import Generator = require('yeoman-generator'); + +export interface Dictionary { + [key: string]: T; +} +export interface Constructor { + new (...args: any[]): T; +} + +/** + * Dependecies can be path (autodiscovery) or an array [, ] + */ +export type Dependency = string | [Generator, string]; + +/** + * Create a function that will clean up the test directory, + * cd into it, and create a dummy gruntfile inside. Intended for use + * as a callback for the mocha `before` hook. + * + * @param {String} dir - path to the test directory + * @returns {Function} mocha callback + */ +export function setUpTestDirectory(dir: string): (done: (...args: any[]) => void) => void; + +/** + * + * Generates a new Gruntfile.js in the current working directory based on + * options hash passed in. + * + * @param {Object} options - Grunt configuration + * @param {Function} done - callback to call on completion + */ +export function gruntfile(options: Dictionary, done: (...args: any[]) => void): void; + +/** + * Clean-up the test directory and cd into it. + * Call given callback after entering the test directory. + * @param {String} dir - path to the test directory + * @param {Function} cb - callback executed after setting working directory to dir + * @example + * testDirectory(path.join(__dirname, './temp'), function () { + * fs.writeFileSync('testfile', 'Roses are red.'); + * }); + */ +export function testDirectory(dir: string, cb: (error?: any) => void): void; + +/** + * Answer prompt questions for the passed-in generator + * @param {Generator} generator - a Yeoman generator + * @param {Object} answers - an object where keys are the + * generators prompt names and values are the answers to + * the prompt questions + * @example + * mockPrompt(angular, {'bootstrap': 'Y', 'compassBoostrap': 'Y'}); + */ +export function mockPrompt(generator: Generator, answers: Dictionary): void; + +/** + * Restore defaults prompts on a generator. + * @param {Generator} generator + */ +export function restorePrompt(generator: Generator): void; + +/** + * Provide mocked values to the config + * @param {Generator} generator - a Yeoman generator + * @param {Object} localConfig - localConfig - should look just like if called config.getAll() + */ +export function mockLocalConfig(generator: Generator, localConfig: Dictionary): void; + +/** + * Create a simple, dummy generator + */ +export function createDummyGenerator(): Generator; + +/** + * Create a generator, using the given dependencies and controller arguments + * Dependecies can be path (autodiscovery) or an array [, ] + * + * @param {String} name - the name of the generator + * @param {Array} dependencies - paths to the generators dependencies + * @param {Array|String} args - arguments to the generator; + * if String, will be split on spaces to create an Array + * @param {Object} options - configuration for the generator + * @example + * var deps = ['../../app', + * '../../common', + * '../../controller', + * '../../main', + * [createDummyGenerator(), 'testacular:app'] + * ]; + * var angular = createGenerator('angular:app', deps); + */ +export function createGenerator(name: string, dependencies: Dependency[], args?: string | string[], options?: Dictionary): Generator; + +/** + * Register a list of dependent generators into the provided env. + * Dependecies can be path (autodiscovery) or an array [, ] + * + * @param {Array} dependencies - paths to the generators dependencies + */ +export function registerDependencies(env: any, dependencies: Dependency[]): void; + +/** + * Run the provided Generator + * @param {String|Function} GeneratorOrNamespace - Generator constructor or namespace + * @return {RunContext} + */ +export function run(GeneratorOrNamespace: string | Constructor, settings?: RunContextSettings): RunContext; + +export interface RunContextSettings { + tmpdir: boolean; +} + +export interface RunContextConstructor { + /** + * This class provide a run context object to façade the complexity involved in setting + * up a generator for testing + * @constructor + * @param {String|Function} Generator - Namespace or generator constructor. If the later + * is provided, then namespace is assumed to be + * 'gen:test' in all cases + * @param {Object} [settings] + * @param {Boolean} [settings.tmpdir=true] - Automatically run this generator in a tmp dir + * @return {this} + */ + new (Generator: string | Constructor, settings?: RunContextSettings): RunContext; +} + +export interface RunContext extends EventEmitter { + /** + * Hold the execution until the returned callback is triggered + * @return {Function} Callback to notify the normal execution can resume + */ + async(): () => void; + + /** + * Return a promise representing the generator run process + * @return {Promise} Promise resolved on end or rejected on error + */ + toPromise(): Promise; + + /** + * Promise `.then()` duck typing + * @return {Promise} + */ + then: Promise['then']; + + /** + * Promise `.catch()` duck typing + * @return {Promise} + */ + catch: Promise['catch']; + + /** + * Clean the provided directory, then change directory into it + * @param {String} dirPath - Directory path (relative to CWD). Prefer passing an absolute + * file path for predictable results + * @param {Function} [cb] - callback who'll receive the folder path as argument + * @return {this} run context instance + */ + inDir(dirPath: string, cb: (folderPath: string) => void): this; + + /** + * Change directory without deleting directory content. + * @param {String} dirPath - Directory path (relative to CWD). Prefer passing an absolute + * file path for predictable results + * @return {this} run context instance + */ + cd(dirPath: string): this; + + /** + * Cleanup a temporary directy and change the CWD into it + * + * This method is called automatically when creating a RunContext. Only use it if you need + * to use the callback. + * + * @param {Function} [cb] - callback who'll receive the folder path as argument + * @return {this} run context instance + */ + inTmpDir(cb: (folderPath: string) => void): this; + + /** + * Clean the directory used for tests inside inDir/inTmpDir + */ + cleanTestDirectory(): void; + + /** + * Provide arguments to the run context + * @param {String|Array} args - command line arguments as Array or space separated string + * @return {this} + */ + withArguments(args: string | string[]): this; + + /** + * Provide options to the run context + * @param {Object} options - command line options (e.g. `--opt-one=foo`) + * @return {this} + */ + withOptions(options: Dictionary): this; + + /** + * Mock the prompt with dummy answers + * @param {Object} answers - Answers to the prompt questions + * @return {this} + */ + withPrompts(answers: Dictionary): this; + + /** + * Provide dependent generators + * @param {Array} dependencies - paths to the generators dependencies + * @return {this} + * @example + * var angular = new RunContext('../../app'); + * angular.withGenerators([ + * '../../common', + * '../../controller', + * '../../main', + * [helpers.createDummyGenerator(), 'testacular:app'] + * ]); + * angular.on('end', function () { + * // assert something + * }); + */ + withGenerators(dependencies: Dependency[]): this; + + /** + * Mock the local configuration with the provided config + * @param {Object} localConfig - should look just like if called config.getAll() + * @return {this} + */ + withLocalConfig(localConfig: Dictionary): this; +} + +export {}; diff --git a/types/yeoman-test/tsconfig.json b/types/yeoman-test/tsconfig.json new file mode 100644 index 0000000000..2625e68a55 --- /dev/null +++ b/types/yeoman-test/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "yeoman-test-tests.ts" + ] +} diff --git a/types/yeoman-test/tslint.json b/types/yeoman-test/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/yeoman-test/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/yeoman-test/yeoman-test-tests.ts b/types/yeoman-test/yeoman-test-tests.ts new file mode 100644 index 0000000000..c5136c6089 --- /dev/null +++ b/types/yeoman-test/yeoman-test-tests.ts @@ -0,0 +1,65 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import * as helpers from 'yeoman-test'; +import Generator = require('yeoman-generator'); + +declare const env: any; +declare const generator: Generator; +declare function before(done: (...args: any[]) => void): void; + +// helpers.setUpTestDirectory() +before(helpers.setUpTestDirectory('dir')); + +// helpers.gruntfile() +before(done => helpers.gruntfile({foo: 'bar'}, done)); + +// helpers.testDirectory() +helpers.testDirectory(path.join(__dirname, './temp'), () => { + fs.writeFileSync('testfile', 'Roses are red.'); +}); + +// helpers.mockPrompt() +helpers.mockPrompt(generator, {foo: 'bar'}); + +// helpers.restorePrompt() +helpers.restorePrompt(generator); + +// helpers.mockLocalConfig() +helpers.mockLocalConfig(generator, {foo: 'bar'}); + +// helpers.createDummyGenerator() +const dummyGenerator = helpers.createDummyGenerator(); + +// helpers.createGenerator() +const angularGenerator = helpers.createGenerator('angular:app', [ + '../../app', + '../../common', + '../../controller', + '../../main', + [helpers.createDummyGenerator(), 'testacular:app'] +]); + +// helpers.registerDependencies() +helpers.registerDependencies(env, ['dependency']); + +// helpers.run() +helpers.run(path.join(__dirname, '../app')) + .withOptions({foo: 'bar'}) + .withArguments(['name-x']) + .withPrompts({coffee: false}); + +helpers.run(path.join(__dirname, '../app')) + .inTmpDir(dir => { /* ... */ }) + .withPrompts({coffee: false}) + .then(() => { /* ... */ }); + +helpers.run(path.join(__dirname, '../app')).withGenerators([ + [helpers.createDummyGenerator(), 'karma:app'], +]); + +before(done => { + helpers.run(path.join(__dirname, '../app')) + .on('error', error => { /* ... */ }) + .on('ready', generator => { /* ... */ }) + .on('end', done); +}); From fb798e5fabb9cd792dc27c95ae3e963d02964d6d Mon Sep 17 00:00:00 2001 From: Stepan Burguchev Date: Sun, 9 Jul 2017 18:07:06 +0300 Subject: [PATCH 0273/1618] final polishing --- types/seamless-immutable/index.d.ts | 46 +++++++++++-------- .../seamless-immutable-tests.ts | 24 +++++----- types/seamless-immutable/tsconfig.json | 2 +- 3 files changed, 40 insertions(+), 32 deletions(-) diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index a121e584f1..761f6e460c 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for Seamless-immutable 6.1.3 // Project: https://github.com/rtfeldman/seamless-immutable // Definitions by: alex3165 +// Stepan Burguchev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // This project is licensed under the MIT license. // Copyrights are respective of each contributor listed at the beginning of each definition file. @@ -32,48 +34,54 @@ declare namespace SeamlessImmutable { deep: boolean; } - export interface ImmutableObject { - set(property: K, value: T[K]): T & ImmutableObject; + interface IImmutableObject { + set(property: K, value: T[K]): ImmutableObject; setIn - (propertyPath: [ K ], value: T[K]): T & ImmutableObject; + (propertyPath: [ K ], value: T[K]): ImmutableObject; setIn - (propertyPath: [ K, L ], value: T[K][L]): T & ImmutableObject; + (propertyPath: [ K, L ], value: T[K][L]): ImmutableObject; setIn - (propertyPath: [ K, L, M ], value: T[K][L][M]): T & ImmutableObject; + (propertyPath: [ K, L, M ], value: T[K][L][M]): ImmutableObject; setIn - (propertyPath: [ K, L, M, N ], value: T[K][L][M][N]): T & ImmutableObject; + (propertyPath: [ K, L, M, N ], value: T[K][L][M][N]): ImmutableObject; + setIn + (propertyPath: [ K, L, M, N, O ], value: T[K][L][M][N][O]): ImmutableObject; asMutable(): T; asMutable(opts: AsMutableOptions): T; - merge(part: DeepPartial, config?: MergeConfig): T & ImmutableObject; + merge(part: DeepPartial, config?: MergeConfig): ImmutableObject; - update(property: K, updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + update(property: K, updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn - (propertyPath: [ K ], updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + (propertyPath: [ K ], updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn - (propertyPath: [ K, L ], updaterFunction: (value: T[K][L], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + (propertyPath: [ K, L ], updaterFunction: (value: T[K][L], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn - (propertyPath: [ K, L, M ], updaterFunction: (value: T[K][L][M], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + (propertyPath: [ K, L, M ], updaterFunction: (value: T[K][L][M], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn - (propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): T & ImmutableObject; + (propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn + (propertyPath: [ K, L, M, N, O ], updaterFunction: (value: T[K][L][M][N][O], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - without(property: keyof T): TTarget & ImmutableObject; - without(...properties: Array): TTarget & ImmutableObject; - without(filter: (value: T[keyof T], key: keyof T) => boolean): TTarget & ImmutableObject; + without(property: keyof T): ImmutableObject; + without(...properties: Array): ImmutableObject; + without(filter: (value: T[keyof T], key: keyof T) => boolean): ImmutableObject; } - export interface ImmutableArray { + interface IImmutableArray { asMutable(): Array; asMutable(opts: AsMutableOptions): Array; asObject(toKeyValue: (item: T) => [string, any]): ImmutableObject; - flatMap(mapFunction: (item: T) => Array): TTarget[] & ImmutableArray; + flatMap(mapFunction: (item: T) => Array): ImmutableArray; } + export type ImmutableObject = T & IImmutableObject; + export type ImmutableArray = Array & IImmutableArray; export type Immutable = ImmutableObject | ImmutableArray; - export function from(obj: Array, options?: Options): Array & ImmutableArray; - export function from(obj: T, options?: Options): T & ImmutableObject; + export function from(obj: Array, options?: Options): ImmutableArray; + export function from(obj: T, options?: Options): ImmutableObject; export function isImmutable(target: any): boolean; export function ImmutableError(message: string): Error; diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index e5f7411d55..1c5beffad6 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -25,8 +25,8 @@ interface ExtendedUser extends User { lastName: string; }; - const arrayOfNumbers: number[] & Immutable.ImmutableArray = Immutable.from([0, 2]); - const user: User & Immutable.ImmutableObject = Immutable.from({ + const arrayOfNumbers: Immutable.ImmutableArray = Immutable.from([0, 2]); + const user: Immutable.ImmutableObject = Immutable.from({ firstName: 'Angry', lastName: 'Monkey' }); @@ -45,14 +45,14 @@ interface ExtendedUser extends User { // Instance syntax: immutable array // --------------------------------------------------------------- { - const array: User[] & Immutable.ImmutableArray = Immutable.from([ { firstName: 'Angry', lastName: 'Monkey' } ]); + const array: Immutable.ImmutableArray = Immutable.from([ { firstName: 'Angry', lastName: 'Monkey' } ]); // asMutable const mutableArray1: User[] = array.asMutable(); const mutableArray2: User[] = array.asMutable({ deep: true }); // flatMap - const flatMappedArray: User[] & Immutable.ImmutableArray = array.flatMap((value: User) => + const flatMappedArray: Immutable.ImmutableArray = array.flatMap((value: User) => [value, value] ); @@ -78,26 +78,26 @@ interface ExtendedUser extends User { }); // set: property name is strongly checked - const updatedUser: User & Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); + const updatedUser: Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); - // setIn: property path is strongly checked for up to 4 arguments - const updatedUser2: ExtendedUser & Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); + // setIn: property path is strongly checked for up to 5 arguments + const updatedUser2: Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); // asMutable const mutableUser1: User = immutableUser.asMutable(); const mutableUser2: User = immutableUser.asMutable({ deep: true }); // merge: merged part is strongly checked as a deeply partial object - const mergedUser: User & Immutable.ImmutableObject = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); + const mergedUser: Immutable.ImmutableObject = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); // update: property name is strongly checked - const updatedUser3: User & Immutable.ImmutableObject = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); + const updatedUser3: Immutable.ImmutableObject = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); - // updateIn: property path is strongly checked for up to 4 arguments - const updatedUser4: User & Immutable.ImmutableObject = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); + // updateIn: property path is strongly checked for up to 5 arguments + const updatedUser4: Immutable.ImmutableObject = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); // without: the return type must be specified explicitly or it will be `any` const simpleUser1: Immutable.ImmutableObject = immutableUserEx.without('address'); - const simpleUser2: User & Immutable.ImmutableObject = immutableUserEx.without('address'); + const simpleUser2: Immutable.ImmutableObject = immutableUserEx.without('address'); const simpleUser3: Immutable.ImmutableObject = immutableUserEx.without('firstName', 'lastName'); } diff --git a/types/seamless-immutable/tsconfig.json b/types/seamless-immutable/tsconfig.json index 6ca679e6d8..8e2483cd41 100644 --- a/types/seamless-immutable/tsconfig.json +++ b/types/seamless-immutable/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "seamless-immutable-tests.ts" ] -} \ No newline at end of file +} From 96d54ca44dbbc43ec04afdb01bf81143cc027f86 Mon Sep 17 00:00:00 2001 From: Flur Date: Sun, 9 Jul 2017 20:23:17 +0300 Subject: [PATCH 0274/1618] - add AnyLoader --- types/three/three-core.d.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index a666411d24..820faa1fab 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -2084,11 +2084,19 @@ export class Loader { static Handlers: LoaderHandler; } -export interface LoaderHandler { - handlers: (RegExp | Loader)[]; +/** +* Interface for all loaders +* CompressedTextureLoader don't extends Loader class, but have load method +*/ +export interface AnyLoader { + load(url: string, onLoad?: (result: any) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): any; +} - add(regex: RegExp, loader: Loader | CompressedTextureLoader): void; - get(file: string): Loader; +export interface LoaderHandler { + handlers: (RegExp | AnyLoader)[]; + + add(regex: RegExp, loader: AnyLoader): void; + get(file: string): AnyLoader; } export class FileLoader { From e898669a909088024373068ed6fd749231a58000 Mon Sep 17 00:00:00 2001 From: Renaud Date: Sun, 9 Jul 2017 19:41:32 +0200 Subject: [PATCH 0275/1618] Added declarations for 'passport-steam'. --- types/passport-steam/index.d.ts | 73 ++++++++++++++++++++ types/passport-steam/passport-steam-tests.ts | 26 +++++++ types/passport-steam/tsconfig.json | 22 ++++++ types/passport-steam/tslint.json | 7 ++ 4 files changed, 128 insertions(+) create mode 100644 types/passport-steam/index.d.ts create mode 100644 types/passport-steam/passport-steam-tests.ts create mode 100644 types/passport-steam/tsconfig.json create mode 100644 types/passport-steam/tslint.json diff --git a/types/passport-steam/index.d.ts b/types/passport-steam/index.d.ts new file mode 100644 index 0000000000..e24f641c8a --- /dev/null +++ b/types/passport-steam/index.d.ts @@ -0,0 +1,73 @@ +/** Declaration file generated by dts-gen */ + +export = passport_steam; + +declare function passport_steam(options: any, validate: any): any; + +declare namespace passport_steam { + // Circular reference from passport_steam + const Strategy: any; + + const version: string; + + namespace prototype { + function authenticate(req: any): any; + + function loadAssociation(fn: any): any; + + function loadDiscoveredInfo(fn: any): any; + + function loadDiscoveredInformation(fn: any): any; + + function saveAssociation(fn: any): any; + + function saveDiscoveredInfo(fn: any): any; + + function saveDiscoveredInformation(fn: any): any; + + namespace authenticate { + const prototype: { + }; + + } + + namespace loadAssociation { + const prototype: { + }; + + } + + namespace loadDiscoveredInfo { + const prototype: { + }; + + } + + namespace loadDiscoveredInformation { + const prototype: { + }; + + } + + namespace saveAssociation { + const prototype: { + }; + + } + + namespace saveDiscoveredInfo { + const prototype: { + }; + + } + + namespace saveDiscoveredInformation { + const prototype: { + }; + + } + + } + +} + diff --git a/types/passport-steam/passport-steam-tests.ts b/types/passport-steam/passport-steam-tests.ts new file mode 100644 index 0000000000..8a9965efcc --- /dev/null +++ b/types/passport-steam/passport-steam-tests.ts @@ -0,0 +1,26 @@ +/** + * Created by kzaY on 07/09/2017. + */ +import express = require("express"); +import passport = require('passport'); +import steam = require('passport-steam'); + +// just some test model +let User = { + findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void { + callback(null, { username: 'james' }); + } +}; + +passport.use(new steam.Strategy({ + returnURL: process.env.PASSPORT_RETURN_URL, + realm: process.env.PASSPORT_REALM, + apiKey: process.env.PASSPORT_API_KEY, +}, + (identifier: any, profile: any, done: (error: any, user?: any) => void) => { + User.findOrCreate(profile.id, profile.provider, (err, user) => { + if (err) { return done(err); } + done(null, user); + }); + }) +); diff --git a/types/passport-steam/tsconfig.json b/types/passport-steam/tsconfig.json new file mode 100644 index 0000000000..ab34d06c60 --- /dev/null +++ b/types/passport-steam/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "passport-steam-tests.ts" + ] +} diff --git a/types/passport-steam/tslint.json b/types/passport-steam/tslint.json new file mode 100644 index 0000000000..c9a409bbed --- /dev/null +++ b/types/passport-steam/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // This package uses the Function type, and it will take effort to fix. + "ban-types": false + } +} From 6e277bdfbf6b7fc504574ef93325e392e82efb05 Mon Sep 17 00:00:00 2001 From: Kamil Ejsymont Date: Sun, 9 Jul 2017 21:23:20 +0200 Subject: [PATCH 0276/1618] Add Record type --- types/jsforce/record.d.ts | 6 ++++++ types/jsforce/salesforce-object.d.ts | 5 +++-- 2 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 types/jsforce/record.d.ts diff --git a/types/jsforce/record.d.ts b/types/jsforce/record.d.ts new file mode 100644 index 0000000000..3bfec4c65b --- /dev/null +++ b/types/jsforce/record.d.ts @@ -0,0 +1,6 @@ +import { SalesforceId } from './salesforce-id'; + +export interface Record { + Id: SalesforceId; + attributes: Object[]; +} diff --git a/types/jsforce/salesforce-object.d.ts b/types/jsforce/salesforce-object.d.ts index 12c9b97cf7..31da3a2c92 100644 --- a/types/jsforce/salesforce-object.d.ts +++ b/types/jsforce/salesforce-object.d.ts @@ -3,6 +3,7 @@ import * as stream from 'stream'; import { SObjectCreateOptions } from './create-options'; import { DescribeSObjectResult } from './describe-result'; import { Query } from './query'; +import { Record } from './record'; import { RecordResult } from './record-result'; import { Connection } from './connection'; import { SalesforceId } from './salesforce-id'; @@ -10,8 +11,8 @@ import { SalesforceId } from './salesforce-id'; export class SObject { record(options: any, callback?: (err: Error, ret: any) => void): void; update(options: SObjectCreateOptions, callback?: (err: Error, ret: any) => void): void; - retrieve(ids: string | string[], callback?: (err: Error, ret: any) => void): void; - retrieve(ids: string | string[], options?: Object, callback?: (err: Error, ret: any) => void): void; + retrieve(ids: string | string[], callback?: (err: Error, ret: Record | Record[]) => void): Promise; + retrieve(ids: string | string[], options?: Object, callback?: (err: Error, ret: Record | Record[]) => void): Promise; upsert(records: Record | Record[], extIdField: SalesforceId, options?: Object, callback?: (err: Error, ret: RecordResult) => void): Promise; upsertBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; describeGlobal(callback: (err: Error, res: any) => void): void; From b5531790e3c63fe65336a9dd1642c85ec5a4ab3b Mon Sep 17 00:00:00 2001 From: Kamil Ejsymont Date: Sun, 9 Jul 2017 21:30:58 +0200 Subject: [PATCH 0277/1618] Fix tests --- types/jsforce/index.d.ts | 1 + types/jsforce/jsforce-tests.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/jsforce/index.d.ts b/types/jsforce/index.d.ts index 9210b5eae4..fc7bd017b2 100644 --- a/types/jsforce/index.d.ts +++ b/types/jsforce/index.d.ts @@ -10,6 +10,7 @@ import * as express from 'express'; import * as glob from 'glob'; export { Date } from './date-enum'; +export { Record } from './record'; export { RecordResult } from './record-result'; export { Connection } from './connection'; export { SObject } from './salesforce-object'; diff --git a/types/jsforce/jsforce-tests.ts b/types/jsforce/jsforce-tests.ts index 70a41ec934..3c1657711d 100644 --- a/types/jsforce/jsforce-tests.ts +++ b/types/jsforce/jsforce-tests.ts @@ -32,8 +32,8 @@ salesforceConnection.sobject("ContentVersion").create({ salesforceConnection.sobject("ContentVersion").retrieve("world", { test: "test" -}, (err: Error, ret: sf.RecordResult) => { - if (err || !ret.success) { +}, (err: Error, ret: sf.Record) => { + if (err) { return; } }); From ccd26750c8e01d4caa7ef8520666e07458226539 Mon Sep 17 00:00:00 2001 From: Stepan Burguchev Date: Mon, 10 Jul 2017 01:10:45 +0300 Subject: [PATCH 0278/1618] add fallback definition to solve dynamic scenarios and when the number of arguments is more than 5 --- types/seamless-immutable/index.d.ts | 2 ++ .../seamless-immutable-tests.ts | 18 ++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index 761f6e460c..c027c83429 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -46,6 +46,7 @@ declare namespace SeamlessImmutable { (propertyPath: [ K, L, M, N ], value: T[K][L][M][N]): ImmutableObject; setIn (propertyPath: [ K, L, M, N, O ], value: T[K][L][M][N][O]): ImmutableObject; + setIn(propertyPath: any[], value: TValue): ImmutableObject; asMutable(): T; asMutable(opts: AsMutableOptions): T; @@ -63,6 +64,7 @@ declare namespace SeamlessImmutable { (propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn (propertyPath: [ K, L, M, N, O ], updaterFunction: (value: T[K][L][M][N][O], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn(propertyPath: any[], updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; without(property: keyof T): ImmutableObject; without(...properties: Array): ImmutableObject; diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index 1c5beffad6..8374056fcc 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -76,12 +76,19 @@ interface ExtendedUser extends User { line1: 'Big house' } }); + const data: { + propertyId: string + } = { + propertyId: 'user.1' + }; // set: property name is strongly checked const updatedUser: Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); - // setIn: property path is strongly checked for up to 5 arguments + // setIn: property path is strongly checked for up to 5 arguments (helps with refactoring and intellisense) + // but will fall back to any[] if there are dynamic arguments on the way const updatedUser2: Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); + const updatedUser3: Immutable.ImmutableObject = immutableUserEx.setIn([ data.propertyId, 'line1' ], 'Small house'); // asMutable const mutableUser1: User = immutableUser.asMutable(); @@ -91,10 +98,13 @@ interface ExtendedUser extends User { const mergedUser: Immutable.ImmutableObject = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); // update: property name is strongly checked - const updatedUser3: Immutable.ImmutableObject = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); + const updatedUser4: Immutable.ImmutableObject = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); - // updateIn: property path is strongly checked for up to 5 arguments - const updatedUser4: Immutable.ImmutableObject = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); + // updateIn: property path is strongly checked for up to 5 arguments (helps with refactoring and intellisense) + // but will fall back to any[] if there are dynamic arguments on the way + const updatedUser5: Immutable.ImmutableObject = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); + // the type of the updated value must be explicity specified in case of fallback + const updatedUser6: Immutable.ImmutableObject = immutableUserEx.updateIn([ data.propertyId, 'line1' ], x => x.toLowerCase() + ' 43'); // without: the return type must be specified explicitly or it will be `any` const simpleUser1: Immutable.ImmutableObject = immutableUserEx.without('address'); From 49691fcab875767d293b32803b1b3bd0f15e00e0 Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 01:10:38 +0200 Subject: [PATCH 0279/1618] maj comment informations --- types/passport-steam/index.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/passport-steam/index.d.ts b/types/passport-steam/index.d.ts index e24f641c8a..3b8f5fa883 100644 --- a/types/passport-steam/index.d.ts +++ b/types/passport-steam/index.d.ts @@ -1,4 +1,8 @@ -/** Declaration file generated by dts-gen */ +// Type definitions for passport-steal +// Project: https://github.com/liamcurry/passport-steam +// Definitions by: kzaY +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3.4 export = passport_steam; From 110d7b237b8a1c031c7b736f0018d683bd2b7a48 Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 01:11:00 +0200 Subject: [PATCH 0280/1618] name error --- types/passport-steam/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/passport-steam/index.d.ts b/types/passport-steam/index.d.ts index 3b8f5fa883..6a59c4dcf7 100644 --- a/types/passport-steam/index.d.ts +++ b/types/passport-steam/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for passport-steal +// Type definitions for passport-steam // Project: https://github.com/liamcurry/passport-steam // Definitions by: kzaY // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 60deab812525b3c562172a00f091a83080bf4598 Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 01:20:02 +0200 Subject: [PATCH 0281/1618] update typescript version --- types/passport-steam/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/passport-steam/index.d.ts b/types/passport-steam/index.d.ts index 6a59c4dcf7..4fbb39e48d 100644 --- a/types/passport-steam/index.d.ts +++ b/types/passport-steam/index.d.ts @@ -1,8 +1,8 @@ // Type definitions for passport-steam // Project: https://github.com/liamcurry/passport-steam -// Definitions by: kzaY +// Definitions by: Gonthier Renaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3.4 +// TypeScript Version: 2.2 export = passport_steam; From 5fdac339f939da202a2cd60a6aba42551cebabff Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 01:28:17 +0200 Subject: [PATCH 0282/1618] maj version and remove blank lines --- types/passport-steam/index.d.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/types/passport-steam/index.d.ts b/types/passport-steam/index.d.ts index 4fbb39e48d..6e6551201a 100644 --- a/types/passport-steam/index.d.ts +++ b/types/passport-steam/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for passport-steam +// Type definitions for passport-steam 1.0 // Project: https://github.com/liamcurry/passport-steam // Definitions by: Gonthier Renaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -32,46 +32,36 @@ declare namespace passport_steam { namespace authenticate { const prototype: { }; - } namespace loadAssociation { const prototype: { }; - } namespace loadDiscoveredInfo { const prototype: { }; - } namespace loadDiscoveredInformation { const prototype: { }; - } namespace saveAssociation { const prototype: { }; - } namespace saveDiscoveredInfo { const prototype: { }; - } namespace saveDiscoveredInformation { const prototype: { }; - } - } - -} - +} \ No newline at end of file From 84ad9e9600874278f9f7775ae5ce4059f829aebe Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 01:43:32 +0200 Subject: [PATCH 0283/1618] new line at end --- types/passport-steam/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/passport-steam/index.d.ts b/types/passport-steam/index.d.ts index 6e6551201a..5658623ab3 100644 --- a/types/passport-steam/index.d.ts +++ b/types/passport-steam/index.d.ts @@ -64,4 +64,4 @@ declare namespace passport_steam { }; } } -} \ No newline at end of file +} From 99a1d0b73d763e99aa960c4ca358cfd3b4a6f8b9 Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 04:33:01 +0200 Subject: [PATCH 0284/1618] Added declarations for 'passport-discord'. --- types/passport-discord/index.d.ts | 75 +++++++++++++++++++ .../passport-discord-tests.ts | 25 +++++++ types/passport-discord/tsconfig.json | 22 ++++++ types/passport-discord/tslint.json | 7 ++ 4 files changed, 129 insertions(+) create mode 100644 types/passport-discord/index.d.ts create mode 100644 types/passport-discord/passport-discord-tests.ts create mode 100644 types/passport-discord/tsconfig.json create mode 100644 types/passport-discord/tslint.json diff --git a/types/passport-discord/index.d.ts b/types/passport-discord/index.d.ts new file mode 100644 index 0000000000..13a00148b5 --- /dev/null +++ b/types/passport-discord/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for passport-discord 0.1 +// Project: https://github.com/nicholastay/passport-discord#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Declaration file generated by dts-gen */ + +export = passport_discord; + +declare class passport_discord { + constructor(options: any, verify: any); + + authorizationParams(options: any): any; + + checkScope(scope: any, accessToken: any, cb: any): any; + + userProfile(accessToken: any, done: any): any; + + static Strategy: any; + +} + +declare namespace passport_discord { + namespace prototype { + function authenticate(req: any, options: any): any; + + function authorizationParams(options: any): any; + + function checkScope(scope: any, accessToken: any, cb: any): any; + + function parseErrorResponse(body: any, status: any): any; + + function tokenParams(options: any): any; + + function userProfile(accessToken: any, done: any): any; + + namespace authenticate { + const prototype: { + }; + + } + + namespace authorizationParams { + const prototype: { + }; + + } + + namespace checkScope { + const prototype: { + }; + + } + + namespace parseErrorResponse { + const prototype: { + }; + + } + + namespace tokenParams { + const prototype: { + }; + + } + + namespace userProfile { + const prototype: { + }; + + } + + } + +} diff --git a/types/passport-discord/passport-discord-tests.ts b/types/passport-discord/passport-discord-tests.ts new file mode 100644 index 0000000000..6fb4b8016a --- /dev/null +++ b/types/passport-discord/passport-discord-tests.ts @@ -0,0 +1,25 @@ +/** + * Created by kzaY on 07/09/2017. + */ +import passport = require('passport'); +import discord = require('passport-discord'); + +// just some test model +let User = { + findOrCreate(discordId: any, callback: (err: any, user: any) => void): void { + callback(null, { username: 'james' }); + } +}; + +passport.use(new discord.Strategy( + { + clientID: 'id', + clientSecret: 'secret', + callbackURL: 'callbackURL' + }, + (accessToken: string, refreshToken: string, profile: any, cb: any) => { + User.findOrCreate({ discordId: profile.id }, (err, user) => { + return cb(err, user); + }); + } +)); diff --git a/types/passport-discord/tsconfig.json b/types/passport-discord/tsconfig.json new file mode 100644 index 0000000000..da28db2fea --- /dev/null +++ b/types/passport-discord/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "passport-discord-tests.ts" + ] +} diff --git a/types/passport-discord/tslint.json b/types/passport-discord/tslint.json new file mode 100644 index 0000000000..c9a409bbed --- /dev/null +++ b/types/passport-discord/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // This package uses the Function type, and it will take effort to fix. + "ban-types": false + } +} From 35ab0a2a098131251c5c63218fedb31f5ae00697 Mon Sep 17 00:00:00 2001 From: newraina Date: Mon, 10 Jul 2017 10:35:27 +0800 Subject: [PATCH 0285/1618] add patch method definition for fetch.io package --- types/fetch.io/fetch.io-tests.ts | 4 ++++ types/fetch.io/index.d.ts | 10 ++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/types/fetch.io/fetch.io-tests.ts b/types/fetch.io/fetch.io-tests.ts index 67c2612fdc..8ca6757ada 100644 --- a/types/fetch.io/fetch.io-tests.ts +++ b/types/fetch.io/fetch.io-tests.ts @@ -23,6 +23,10 @@ request .put('') .json(); +request + .patch('') + .json(); + request .config('key', 'value') .json(); diff --git a/types/fetch.io/index.d.ts b/types/fetch.io/index.d.ts index fabbbc4b52..4489156cfe 100644 --- a/types/fetch.io/index.d.ts +++ b/types/fetch.io/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fetch.io 4.0 +// Type definitions for fetch.io 4.1 // Project: https://github.com/haoxins/fetch.io // Definitions by: newraina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -63,6 +63,12 @@ export class Request { */ put: (url: TUrl) => this; + + /** + * HTTP patch method + */ + patch: (url: TUrl) => this; + /** * Set Options */ @@ -93,7 +99,7 @@ export class Request { send(data: {[key: string]: any}): this; /** - * ppend formData + * append formData */ append(key: string, value: any): this; From 0ddc7720f11f6ce407e780ad6d365e44e8faf36d Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 05:06:57 +0200 Subject: [PATCH 0286/1618] update profile --- types/passport-discord/index.d.ts | 87 +++++++++++-------------------- 1 file changed, 29 insertions(+), 58 deletions(-) diff --git a/types/passport-discord/index.d.ts b/types/passport-discord/index.d.ts index 13a00148b5..ccc181b137 100644 --- a/types/passport-discord/index.d.ts +++ b/types/passport-discord/index.d.ts @@ -1,75 +1,46 @@ // Type definitions for passport-discord 0.1 // Project: https://github.com/nicholastay/passport-discord#readme -// Definitions by: My Self +// Definitions by: Gonthier Renaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.2 /** Declaration file generated by dts-gen */ -export = passport_discord; +import * as passport from 'passport'; +import * as express from 'express'; -declare class passport_discord { - constructor(options: any, verify: any); +export class Strategy implements passport.Strategy { + constructor(options: Strategy.StrategyOption, verify: (accessToken: string, refreshToken: string, profile: Strategy.Profile, done: (error: any, user?: any) => void) => void); + name: string; + authenticate: (req: express.Request, options?: Object) => void; authorizationParams(options: any): any; checkScope(scope: any, accessToken: any, cb: any): any; + parseErrorResponse(body: any, status: any): any; + + tokenParams(options: any): any; + userProfile(accessToken: any, done: any): any; - - static Strategy: any; - } -declare namespace passport_discord { - namespace prototype { - function authenticate(req: any, options: any): any; - - function authorizationParams(options: any): any; - - function checkScope(scope: any, accessToken: any, cb: any): any; - - function parseErrorResponse(body: any, status: any): any; - - function tokenParams(options: any): any; - - function userProfile(accessToken: any, done: any): any; - - namespace authenticate { - const prototype: { - }; - - } - - namespace authorizationParams { - const prototype: { - }; - - } - - namespace checkScope { - const prototype: { - }; - - } - - namespace parseErrorResponse { - const prototype: { - }; - - } - - namespace tokenParams { - const prototype: { - }; - - } - - namespace userProfile { - const prototype: { - }; - - } - +export namespace Strategy { + interface StrategyOption { + clientID: string; + clientSecret: string; + callbackURL: string; + scope: string[]; } + interface Profile extends passport.Profile { + profileUrl: string; + id: any; + username: string; + discriminator: string; + avatar: string; + verified: boolean; + email: string; + _raw: any; + _json: any; + } } From 7bd9fe438a0827db8cb2c8cad8a9fa1aef5c19cb Mon Sep 17 00:00:00 2001 From: Renaud Date: Mon, 10 Jul 2017 05:13:10 +0200 Subject: [PATCH 0287/1618] scope optional --- types/passport-discord/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/passport-discord/index.d.ts b/types/passport-discord/index.d.ts index ccc181b137..6c96a153df 100644 --- a/types/passport-discord/index.d.ts +++ b/types/passport-discord/index.d.ts @@ -29,7 +29,7 @@ export namespace Strategy { clientID: string; clientSecret: string; callbackURL: string; - scope: string[]; + scope?: string[]; } interface Profile extends passport.Profile { From 814578c0609996efb1675915dfe079c541f4a956 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wang=20D=C3=A0p=C3=A9ng?= Date: Mon, 10 Jul 2017 12:16:20 +0800 Subject: [PATCH 0288/1618] [request] Add time option to CoreOptions --- types/request/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 2cf7b08cf9..63c86290f4 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -150,6 +150,7 @@ declare namespace request { ca?: string | Buffer | string[] | Buffer[]; har?: HttpArchiveRequest; useQuerystring?: boolean; + time?: boolean; } interface UriOptions { From e4ce18f059ba1bbe940ff5468b5baa5e97b36f7d Mon Sep 17 00:00:00 2001 From: Abruzzi Date: Mon, 10 Jul 2017 15:18:34 +1000 Subject: [PATCH 0289/1618] add: add the declaration of 'ignoreInputTextSelection' --- types/dragula/dragula-tests.ts | 3 ++- types/dragula/index.d.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/types/dragula/dragula-tests.ts b/types/dragula/dragula-tests.ts index d5b28e37dd..5f143406c3 100644 --- a/types/dragula/dragula-tests.ts +++ b/types/dragula/dragula-tests.ts @@ -20,7 +20,8 @@ var d2 = dragula({ revertOnSpill: false, removeOnSpill: false, delay: false, - mirrorContainer: document.body + mirrorContainer: document.body, + ignoreInputTextSelection: true }); var d3 = dragula(); diff --git a/types/dragula/index.d.ts b/types/dragula/index.d.ts index fe09c409e2..01420e9a29 100644 --- a/types/dragula/index.d.ts +++ b/types/dragula/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for dragula v2.1.2 // Project: http://bevacqua.github.io/dragula/ // Definitions by: Paul Welter +// Yang He // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var dragula: dragula.Dragula; @@ -21,6 +22,7 @@ declare namespace dragula { removeOnSpill?: boolean; delay?: boolean | number; mirrorContainer?: Element; + ignoreInputTextSelection?: boolean; } interface Drake { From bd54249da7ce63587d342ca046ea819a58349bc1 Mon Sep 17 00:00:00 2001 From: Stepan Burguchev Date: Mon, 10 Jul 2017 09:25:33 +0300 Subject: [PATCH 0290/1618] set/update fallbacks, tests, tslint coverage --- types/seamless-immutable/index.d.ts | 2 ++ .../seamless-immutable-tests.ts | 23 +++++++++++-------- types/seamless-immutable/tslint.json | 1 + 3 files changed, 16 insertions(+), 10 deletions(-) create mode 100644 types/seamless-immutable/tslint.json diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index c027c83429..d40c609dd4 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -36,6 +36,7 @@ declare namespace SeamlessImmutable { interface IImmutableObject { set(property: K, value: T[K]): ImmutableObject; + set(property: string, value: TValue): ImmutableObject; setIn (propertyPath: [ K ], value: T[K]): ImmutableObject; setIn @@ -54,6 +55,7 @@ declare namespace SeamlessImmutable { merge(part: DeepPartial, config?: MergeConfig): ImmutableObject; update(property: K, updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + update(property: string, updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn (propertyPath: [ K ], updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index 8374056fcc..64cbfdd6cb 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -5,7 +5,7 @@ import * as Immutable from 'seamless-immutable'; interface User { firstName: string; lastName: string; -}; +} interface Address { line1: string; @@ -23,7 +23,7 @@ interface ExtendedUser extends User { interface User { firstName: string; lastName: string; - }; + } const arrayOfNumbers: Immutable.ImmutableArray = Immutable.from([0, 2]); const user: Immutable.ImmutableObject = Immutable.from({ @@ -83,28 +83,31 @@ interface ExtendedUser extends User { }; // set: property name is strongly checked - const updatedUser: Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); + const updatedUser01: Immutable.ImmutableObject = immutableUser.set('firstName', 'Whirlwind'); + const updatedUser02: Immutable.ImmutableObject = immutableUser.set(data.propertyId, 'Whirlwind'); // setIn: property path is strongly checked for up to 5 arguments (helps with refactoring and intellisense) // but will fall back to any[] if there are dynamic arguments on the way - const updatedUser2: Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); - const updatedUser3: Immutable.ImmutableObject = immutableUserEx.setIn([ data.propertyId, 'line1' ], 'Small house'); + const updatedUser11: Immutable.ImmutableObject = immutableUserEx.setIn(['address', 'line1'], 'Small house'); + const updatedUser12: Immutable.ImmutableObject = immutableUserEx.setIn([ data.propertyId, 'line1' ], 'Small house'); // asMutable - const mutableUser1: User = immutableUser.asMutable(); - const mutableUser2: User = immutableUser.asMutable({ deep: true }); + const mutableUser21: User = immutableUser.asMutable(); + const mutableUser22: User = immutableUser.asMutable({ deep: true }); // merge: merged part is strongly checked as a deeply partial object const mergedUser: Immutable.ImmutableObject = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); // update: property name is strongly checked - const updatedUser4: Immutable.ImmutableObject = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); + const updatedUser41: Immutable.ImmutableObject = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); + // the type of the updated value must be explicity specified in case of fallback + const updatedUser42: Immutable.ImmutableObject = immutableUser.update(data.propertyId, x => x.toLowerCase() + ' Whirlwind'); // updateIn: property path is strongly checked for up to 5 arguments (helps with refactoring and intellisense) // but will fall back to any[] if there are dynamic arguments on the way - const updatedUser5: Immutable.ImmutableObject = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); + const updatedUser51: Immutable.ImmutableObject = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); // the type of the updated value must be explicity specified in case of fallback - const updatedUser6: Immutable.ImmutableObject = immutableUserEx.updateIn([ data.propertyId, 'line1' ], x => x.toLowerCase() + ' 43'); + const updatedUser52: Immutable.ImmutableObject = immutableUserEx.updateIn([ data.propertyId, 'line1' ], x => x.toLowerCase() + ' 43'); // without: the return type must be specified explicitly or it will be `any` const simpleUser1: Immutable.ImmutableObject = immutableUserEx.without('address'); diff --git a/types/seamless-immutable/tslint.json b/types/seamless-immutable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/seamless-immutable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 0a0270a40b41414e8e1d4002f424d6632831a16a Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 10 Jul 2017 09:37:07 +0300 Subject: [PATCH 0291/1618] fix error TS2314 Generic type 'Component' requires 2 type argument(s). --- types/react-redux/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index c21ea1c33b..c67c2f7cb3 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -176,4 +176,4 @@ export interface ProviderProps { /** * Makes the Redux store available to the connect() calls in the component hierarchy below. */ -export class Provider extends React.Component { } +export class Provider extends React.Component { } From 7730d7619e34ae5b3362d1ba8b3501797c24ea13 Mon Sep 17 00:00:00 2001 From: Stepan Burguchev Date: Mon, 10 Jul 2017 09:49:33 +0300 Subject: [PATCH 0292/1618] fix common mistakes --- types/seamless-immutable/index.d.ts | 12 +++++++----- types/seamless-immutable/seamless-immutable-tests.ts | 6 ++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index d40c609dd4..70aa6b552d 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -37,6 +37,7 @@ declare namespace SeamlessImmutable { interface IImmutableObject { set(property: K, value: T[K]): ImmutableObject; set(property: string, value: TValue): ImmutableObject; + setIn (propertyPath: [ K ], value: T[K]): ImmutableObject; setIn @@ -47,7 +48,7 @@ declare namespace SeamlessImmutable { (propertyPath: [ K, L, M, N ], value: T[K][L][M][N]): ImmutableObject; setIn (propertyPath: [ K, L, M, N, O ], value: T[K][L][M][N][O]): ImmutableObject; - setIn(propertyPath: any[], value: TValue): ImmutableObject; + setIn(propertyPath: string[], value: TValue): ImmutableObject; asMutable(): T; asMutable(opts: AsMutableOptions): T; @@ -56,6 +57,7 @@ declare namespace SeamlessImmutable { update(property: K, updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; update(property: string, updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn (propertyPath: [ K ], updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn @@ -66,11 +68,11 @@ declare namespace SeamlessImmutable { (propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn (propertyPath: [ K, L, M, N, O ], updaterFunction: (value: T[K][L][M][N][O], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn(propertyPath: any[], updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn(propertyPath: string[], updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - without(property: keyof T): ImmutableObject; - without(...properties: Array): ImmutableObject; - without(filter: (value: T[keyof T], key: keyof T) => boolean): ImmutableObject; + without(property: keyof T): ImmutableObject; + without(...properties: Array): ImmutableObject; + without(filter: (value: T[keyof T], key: keyof T) => boolean): ImmutableObject; } interface IImmutableArray { diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index 64cbfdd6cb..4478ef80cd 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -109,8 +109,6 @@ interface ExtendedUser extends User { // the type of the updated value must be explicity specified in case of fallback const updatedUser52: Immutable.ImmutableObject = immutableUserEx.updateIn([ data.propertyId, 'line1' ], x => x.toLowerCase() + ' 43'); - // without: the return type must be specified explicitly or it will be `any` - const simpleUser1: Immutable.ImmutableObject = immutableUserEx.without('address'); - const simpleUser2: Immutable.ImmutableObject = immutableUserEx.without('address'); - const simpleUser3: Immutable.ImmutableObject = immutableUserEx.without('firstName', 'lastName'); + // without + const simpleUser1: Immutable.ImmutableObject = immutableUserEx.without('address'); } From 4450b36336f984e89f79a97faab6e789cd21cbb0 Mon Sep 17 00:00:00 2001 From: Stepan Burguchev Date: Mon, 10 Jul 2017 10:30:45 +0300 Subject: [PATCH 0293/1618] add function-like constructor; fix lint errors --- types/seamless-immutable/index.d.ts | 85 ++++++++----------- .../seamless-immutable-tests.ts | 9 +- 2 files changed, 44 insertions(+), 50 deletions(-) diff --git a/types/seamless-immutable/index.d.ts b/types/seamless-immutable/index.d.ts index 70aa6b552d..16256d8e83 100644 --- a/types/seamless-immutable/index.d.ts +++ b/types/seamless-immutable/index.d.ts @@ -1,19 +1,10 @@ -// Type definitions for Seamless-immutable 6.1.3 +// Type definitions for Seamless-immutable 7.1 // Project: https://github.com/rtfeldman/seamless-immutable // Definitions by: alex3165 // Stepan Burguchev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// This project is licensed under the MIT license. -// Copyrights are respective of each contributor listed at the beginning of each definition file. - -// 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. - export = SeamlessImmutable; declare namespace SeamlessImmutable { @@ -23,7 +14,7 @@ declare namespace SeamlessImmutable { interface MergeConfig { deep?: boolean; - merger?: Function; + merger?(a: any, b: any, config: any): any; } interface Options { @@ -34,61 +25,59 @@ declare namespace SeamlessImmutable { deep: boolean; } - interface IImmutableObject { + interface ImmutableObjectMixin { set(property: K, value: T[K]): ImmutableObject; set(property: string, value: TValue): ImmutableObject; - setIn - (propertyPath: [ K ], value: T[K]): ImmutableObject; - setIn - (propertyPath: [ K, L ], value: T[K][L]): ImmutableObject; - setIn - (propertyPath: [ K, L, M ], value: T[K][L][M]): ImmutableObject; - setIn - (propertyPath: [ K, L, M, N ], value: T[K][L][M][N]): ImmutableObject; - setIn - (propertyPath: [ K, L, M, N, O ], value: T[K][L][M][N][O]): ImmutableObject; + setIn(propertyPath: [ K ], value: T[K]): ImmutableObject; + setIn(propertyPath: [ K, L ], value: T[K][L]): ImmutableObject; + setIn(propertyPath: [ K, L, M ], value: T[K][L][M]): ImmutableObject; + setIn( + propertyPath: [ K, L, M, N ], value: T[K][L][M][N]): ImmutableObject; + setIn( + propertyPath: [ K, L, M, N, O ], value: T[K][L][M][N][O]): ImmutableObject; setIn(propertyPath: string[], value: TValue): ImmutableObject; - asMutable(): T; - asMutable(opts: AsMutableOptions): T; + asMutable(opts?: AsMutableOptions): T; merge(part: DeepPartial, config?: MergeConfig): ImmutableObject; update(property: K, updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; update(property: string, updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn - (propertyPath: [ K ], updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn - (propertyPath: [ K, L ], updaterFunction: (value: T[K][L], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn - (propertyPath: [ K, L, M ], updaterFunction: (value: T[K][L][M], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn - (propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - updateIn - (propertyPath: [ K, L, M, N, O ], updaterFunction: (value: T[K][L][M][N][O], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn( + propertyPath: [ K ], updaterFunction: (value: T[K], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn( + propertyPath: [ K, L ], updaterFunction: (value: T[K][L], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn( + propertyPath: [ K, L, M ], updaterFunction: (value: T[K][L][M], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn( + propertyPath: [ K, L, M, N ], updaterFunction: (value: T[K][L][M][N], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; + updateIn( + propertyPath: [ K, L, M, N, O ], updaterFunction: (value: T[K][L][M][N][O], ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; updateIn(propertyPath: string[], updaterFunction: (value: TValue, ...additionalParameters: any[]) => any, ...additionalArguments: any[]): ImmutableObject; - without(property: keyof T): ImmutableObject; - without(...properties: Array): ImmutableObject; - without(filter: (value: T[keyof T], key: keyof T) => boolean): ImmutableObject; + without(property: K): ImmutableObject; + without(...properties: K[]): ImmutableObject; + without(filter: (value: T[K], key: K) => boolean): ImmutableObject; } - interface IImmutableArray { - asMutable(): Array; - asMutable(opts: AsMutableOptions): Array; + interface ImmutableArrayMixin { + asMutable(opts?: AsMutableOptions): T[]; asObject(toKeyValue: (item: T) => [string, any]): ImmutableObject; - flatMap(mapFunction: (item: T) => Array): ImmutableArray; + flatMap(mapFunction: (item: T) => TTarget[]): ImmutableArray; } - export type ImmutableObject = T & IImmutableObject; - export type ImmutableArray = Array & IImmutableArray; - export type Immutable = ImmutableObject | ImmutableArray; + type ImmutableObject = T & ImmutableObjectMixin; + type ImmutableArray = T[] & ImmutableArrayMixin; + type Immutable = ImmutableObject | ImmutableArray; - export function from(obj: Array, options?: Options): ImmutableArray; - export function from(obj: T, options?: Options): ImmutableObject; + function from(obj: T[], options?: Options): ImmutableArray; + function from(obj: T, options?: Options): ImmutableObject; - export function isImmutable(target: any): boolean; - export function ImmutableError(message: string): Error; + function isImmutable(target: any): boolean; + function ImmutableError(message: string): Error; } + +declare function SeamlessImmutable(obj: T[], options?: SeamlessImmutable.Options): SeamlessImmutable.ImmutableArray; +declare function SeamlessImmutable(obj: T, options?: SeamlessImmutable.Options): SeamlessImmutable.ImmutableObject; diff --git a/types/seamless-immutable/seamless-immutable-tests.ts b/types/seamless-immutable/seamless-immutable-tests.ts index 4478ef80cd..606d991aea 100644 --- a/types/seamless-immutable/seamless-immutable-tests.ts +++ b/types/seamless-immutable/seamless-immutable-tests.ts @@ -25,8 +25,13 @@ interface ExtendedUser extends User { lastName: string; } - const arrayOfNumbers: Immutable.ImmutableArray = Immutable.from([0, 2]); - const user: Immutable.ImmutableObject = Immutable.from({ + const arrayOfNumbers1: Immutable.ImmutableArray = Immutable.from([0, 2]); + const arrayOfNumbers2: Immutable.ImmutableArray = Immutable([0, 2]); + const user1: Immutable.ImmutableObject = Immutable.from({ + firstName: 'Angry', + lastName: 'Monkey' + }); + const user2: Immutable.ImmutableObject = Immutable({ firstName: 'Angry', lastName: 'Monkey' }); From 674775afd69cf0046309eddafe805a20d649d83d Mon Sep 17 00:00:00 2001 From: Swiod Date: Mon, 10 Jul 2017 10:28:14 +0200 Subject: [PATCH 0294/1618] IconOptions.src is optional --- types/openlayers/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 42587298f0..356ba72429 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -13572,7 +13572,7 @@ declare module olx { rotation?: number; size?: ol.Size; imgSize?: ol.Size; - src: string; + src?: string; } From a6f6d0660eb2b48a33f14a84a69f2cd89c9ed543 Mon Sep 17 00:00:00 2001 From: Anjun Wang Date: Mon, 10 Jul 2017 16:47:10 +0800 Subject: [PATCH 0295/1618] add arrify 1.0.1 --- types/arrify/arrify-tests.ts | 14 ++++++++++++++ types/arrify/index.d.ts | 18 ++++++++++++++++++ types/arrify/tsconfig.json | 22 ++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 types/arrify/arrify-tests.ts create mode 100644 types/arrify/index.d.ts create mode 100644 types/arrify/tsconfig.json diff --git a/types/arrify/arrify-tests.ts b/types/arrify/arrify-tests.ts new file mode 100644 index 0000000000..319e86897a --- /dev/null +++ b/types/arrify/arrify-tests.ts @@ -0,0 +1,14 @@ +import arrify = require("arrify"); + +arrify(null); +arrify(null); + +arrify(undefined); +arrify(undefined); + +arrify(1); +arrify([2, 3]); + +function test(val?: string | string[]) { + arrify(val); +} diff --git a/types/arrify/index.d.ts b/types/arrify/index.d.ts new file mode 100644 index 0000000000..fb552e161e --- /dev/null +++ b/types/arrify/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for arrify 1.0.1 +// Project: https://github.com/sindresorhus/arrify +// Definitions by: AnJun Wang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @example + * arrify(undefined) // returns [] + * @example + * arrify(null) // returns [] + * @example + * arrify(1) // returns [1] + * @example + * arrify([2, 3]) // returns [2, 3] + * @param val + */ +declare function arrify(val: undefined | null | T | T[]): T[]; +export = arrify; diff --git a/types/arrify/tsconfig.json b/types/arrify/tsconfig.json new file mode 100644 index 0000000000..b2579c233e --- /dev/null +++ b/types/arrify/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "arrify-tests.ts" + ] +} \ No newline at end of file From f7da06e430e99327556f8114399aa46f766ea5df Mon Sep 17 00:00:00 2001 From: stonio Date: Mon, 10 Jul 2017 11:26:01 +0200 Subject: [PATCH 0296/1618] Restore readonly keyword for "fn" property --- types/jquery/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 254a2676ed..b71bfbbed3 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -2422,7 +2422,7 @@ interface JQueryStatic { * @since 1.4.3 */ cssNumber: JQuery.PlainObject; - fn: JQuery; + readonly fn: JQuery; fx: { /** * The rate (in milliseconds) at which animations fire. From a76b80a359b125757399ba3871ae6e588dfe7869 Mon Sep 17 00:00:00 2001 From: stonio Date: Mon, 10 Jul 2017 11:27:25 +0200 Subject: [PATCH 0297/1618] Add test/learn-tests.ts --- types/jquery/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/jquery/tsconfig.json b/types/jquery/tsconfig.json index 21d35a63da..901642e583 100644 --- a/types/jquery/tsconfig.json +++ b/types/jquery/tsconfig.json @@ -22,6 +22,7 @@ "jquery-tests.ts", "test/example-tests.ts", "test/longdesc-tests.ts", + "test/learn-tests.ts", "test/jquery-no-window-module-tests.ts", "test/jquery-window-module-tests.ts", "test/jquery-slim-no-window-module-tests.ts", From 8edb3e3b510576cdddc7575992be052592aac038 Mon Sep 17 00:00:00 2001 From: stonio Date: Mon, 10 Jul 2017 11:29:24 +0200 Subject: [PATCH 0298/1618] Remove import instructions --- types/jquery/test/learn-tests.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index 2ad633eddc..5a1e69675e 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -1,6 +1,3 @@ -import jQueryFactory = require('jquery'); -const jQuery = jQueryFactory(window, true); - # From https://learn.jquery.com/plugins/basic-plugin-creation/ ## Basic Plugin Authoring From 7db29def15f4bb4bd06acb475b03b54a89c4a96b Mon Sep 17 00:00:00 2001 From: stonio Date: Mon, 10 Jul 2017 11:30:16 +0200 Subject: [PATCH 0299/1618] Fix comment syntax --- types/jquery/test/learn-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index 5a1e69675e..17fc7cd285 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -1,6 +1,6 @@ -# From https://learn.jquery.com/plugins/basic-plugin-creation/ +// From https://learn.jquery.com/plugins/basic-plugin-creation/ -## Basic Plugin Authoring +// Basic Plugin Authoring interface JQuery { greenify: GreenifyPlugin; From 1df177763e9affa458413190cefd219838285f61 Mon Sep 17 00:00:00 2001 From: stonio Date: Mon, 10 Jul 2017 11:58:45 +0200 Subject: [PATCH 0300/1618] Update README.md --- types/jquery/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/jquery/README.md b/types/jquery/README.md index 8fab451ce0..c6420f2bbc 100644 --- a/types/jquery/README.md +++ b/types/jquery/README.md @@ -31,6 +31,8 @@ Note that while the factory function ignores the second parameter, it is require - Tests generated from examples in jQuery documentation. - [test/longdesc-tests.ts](test/longdesc-tests.ts) - Tests generated from non-example snippets in jQuery documentation. +- [test/learn-tests.ts](test/learn-tests.ts) + - Tests imported from in [jQuery Learning Center](https://learn.jquery.com/). - [test/jquery-window-module-tests.ts](test/jquery-window-module-tests.ts)
    [test/jquery-slim-window-module-tests.ts](test/jquery-slim-window-module-tests.ts) - Tests importing jQuery with a DOM available From dc178ad6fe32416622ec37de703bb72279ab4bb4 Mon Sep 17 00:00:00 2001 From: stonio Date: Mon, 10 Jul 2017 12:01:04 +0200 Subject: [PATCH 0301/1618] Update README.md --- types/jquery/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jquery/README.md b/types/jquery/README.md index c6420f2bbc..3d5fbc2ce1 100644 --- a/types/jquery/README.md +++ b/types/jquery/README.md @@ -32,7 +32,7 @@ Note that while the factory function ignores the second parameter, it is require - [test/longdesc-tests.ts](test/longdesc-tests.ts) - Tests generated from non-example snippets in jQuery documentation. - [test/learn-tests.ts](test/learn-tests.ts) - - Tests imported from in [jQuery Learning Center](https://learn.jquery.com/). + - Tests imported from examples in [jQuery Learning Center](https://learn.jquery.com). - [test/jquery-window-module-tests.ts](test/jquery-window-module-tests.ts)
    [test/jquery-slim-window-module-tests.ts](test/jquery-slim-window-module-tests.ts) - Tests importing jQuery with a DOM available From 111de6049efdfc4ad096e01ec9cebba2a4ee828a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Mon, 10 Jul 2017 13:49:18 +0300 Subject: [PATCH 0302/1618] Updated types. --- types/json2md/index.d.ts | 84 ++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 46 deletions(-) diff --git a/types/json2md/index.d.ts b/types/json2md/index.d.ts index c07e065629..712edf15b0 100644 --- a/types/json2md/index.d.ts +++ b/types/json2md/index.d.ts @@ -12,55 +12,47 @@ type json2md = typeof json2md; declare namespace json2md { const converters: ConvertersMethods; - interface DataObject { - [converter: string]: any; - blockquote?: string | string[]; - code?: CodeInput; - h1?: string | string[]; - h2?: string | string[]; - h3?: string | string[]; - h4?: string | string[]; - h5?: string | string[]; - h6?: string | string[]; - img?: ImgInput | ImgInput[]; - ol?: string[]; - p?: string | string[]; - table?: TableInput; - ul?: string[]; + namespace DefaultConverters { + interface Converters { + [converter: string]: any; + blockquote: string | string[]; + code: CodeInput; + h1: string | string[]; + h2: string | string[]; + h3: string | string[]; + h4: string | string[]; + h5: string | string[]; + h6: string | string[]; + img: ImgInput | ImgInput[]; + ol: string[]; + p: string | string[]; + table: TableInput; + ul: string[]; + } + + interface ImgInput { + title: string; + source: string; + } + + interface CodeInput { + language?: string; + content: string | string[]; + } + + interface TableInput { + headers: string[]; + rows: Array<{ [column: string]: string }> | string[][]; + } + } + + type DataObject = { + [TConverter in keyof DefaultConverters.Converters]?: DefaultConverters.Converters[TConverter] } type ConverterCallback = (input: TInput, json2md: json2md) => string; - interface ConvertersMethods { - [converter: string]: ConverterCallback; - - blockquote(input: string | string[], json2md: json2md): string; - code(input: CodeInput, json2md: json2md): string; - h1(input: string, json2md: json2md): string; - h2(input: string, json2md: json2md): string; - h3(input: string, json2md: json2md): string; - h4(input: string, json2md: json2md): string; - h5(input: string, json2md: json2md): string; - h6(input: string, json2md: json2md): string; - img(input: ImgInput | ImgInput[] | string, json2md: json2md): string; - ol(input: string, json2md: json2md): string; - p(input: string, json2md: json2md): string; - table(input: TableInput, json2md: json2md): string; - ul(input: string, json2md: json2md): string; - } - - interface ImgInput { - title: string; - source: string; - } - - interface CodeInput { - language?: string; - content: string | string[]; - } - - interface TableInput { - headers: string[]; - rows: Array<{ [column: string]: string }> | string[][]; + type ConvertersMethods = { + [TConverter in keyof DefaultConverters.Converters]: ConverterCallback } } From 87055a635e938726e436d61fba3ae1692c6c1a55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Mon, 10 Jul 2017 13:52:03 +0300 Subject: [PATCH 0303/1618] Updated tests. --- types/json2md/json2md-tests.ts | 58 +++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/types/json2md/json2md-tests.ts b/types/json2md/json2md-tests.ts index bdb071517b..1b10c2d6f1 100644 --- a/types/json2md/json2md-tests.ts +++ b/types/json2md/json2md-tests.ts @@ -3,66 +3,66 @@ import * as json2md from 'json2md'; declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; -const exampleString: string = "example string"; -const exampleStringArray: string[] = ["A", "B"]; +const EXAMPLE_STRING: string = "example string"; +const EXAMPLE_STRING_ARRAY: string[] = ["A", "B"]; describe("Default elements", () => { it("Headings", () => { json2md([ { - h1: exampleString + h1: EXAMPLE_STRING }, { - h2: exampleString + h2: EXAMPLE_STRING }, { - h3: exampleString + h3: EXAMPLE_STRING }, { - h4: exampleString + h4: EXAMPLE_STRING }, { - h5: exampleString + h5: EXAMPLE_STRING }, { - h6: exampleString + h6: EXAMPLE_STRING } ]); }); it("Paragraphs", () => { json2md([{ - p: exampleString + p: EXAMPLE_STRING }]); json2md([{ - p: exampleStringArray + p: EXAMPLE_STRING_ARRAY }]); }); it("Blockquote", () => { json2md([{ - blockquote: exampleString + blockquote: EXAMPLE_STRING }]); json2md([{ - blockquote: exampleStringArray + blockquote: EXAMPLE_STRING_ARRAY }]); }); it("Image", () => { json2md([{ img: { - title: exampleString, - source: exampleString + title: EXAMPLE_STRING, + source: EXAMPLE_STRING } }]); json2md([{ img: [ { - title: exampleString, - source: exampleString + title: EXAMPLE_STRING, + source: EXAMPLE_STRING } ] }]); @@ -71,7 +71,7 @@ describe("Default elements", () => { it("Unordered list", () => { json2md([ { - ul: exampleStringArray + ul: EXAMPLE_STRING_ARRAY } ]); }); @@ -79,7 +79,7 @@ describe("Default elements", () => { it("Ordered list", () => { json2md([ { - ol: exampleStringArray + ol: EXAMPLE_STRING_ARRAY } ]); }); @@ -89,7 +89,7 @@ describe("Default elements", () => { { code: { language: "js", - content: exampleString + content: EXAMPLE_STRING } } ]); @@ -99,11 +99,11 @@ describe("Default elements", () => { json2md([ { table: { - headers: exampleStringArray, + headers: EXAMPLE_STRING_ARRAY, rows: [ { - A: exampleString, - B: exampleString + A: EXAMPLE_STRING, + B: EXAMPLE_STRING } ] } @@ -113,9 +113,9 @@ describe("Default elements", () => { json2md([ { table: { - headers: exampleStringArray, + headers: EXAMPLE_STRING_ARRAY, rows: [ - exampleStringArray + EXAMPLE_STRING_ARRAY ] } } @@ -132,7 +132,7 @@ it("Custom types", () => { json2md([ { - customConverter: exampleString + customConverter: EXAMPLE_STRING } ]); }); @@ -200,3 +200,11 @@ it("Big example", () => { } ]); }); + +it("Use converter", () => { + const blockquote: string = json2md.converters.blockquote(EXAMPLE_STRING, json2md); + const img: string = json2md.converters.img({ + title: EXAMPLE_STRING, + source: EXAMPLE_STRING + }, json2md); +}); From e041ed6c42930b848a840d01b5a6b1c4f4d0c3ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Mon, 10 Jul 2017 13:52:58 +0300 Subject: [PATCH 0304/1618] Fixed dtslint errors. --- types/json2md/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/json2md/index.d.ts b/types/json2md/index.d.ts index 712edf15b0..37bdd0d2c8 100644 --- a/types/json2md/index.d.ts +++ b/types/json2md/index.d.ts @@ -48,11 +48,11 @@ declare namespace json2md { type DataObject = { [TConverter in keyof DefaultConverters.Converters]?: DefaultConverters.Converters[TConverter] - } + }; type ConverterCallback = (input: TInput, json2md: json2md) => string; type ConvertersMethods = { [TConverter in keyof DefaultConverters.Converters]: ConverterCallback - } + }; } From 4e606f4948a0b65fc9099a583720547da9cefac4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martynas=20=C5=BDilinskas?= Date: Mon, 10 Jul 2017 13:54:04 +0300 Subject: [PATCH 0305/1618] Added JSDoc. --- types/json2md/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/json2md/index.d.ts b/types/json2md/index.d.ts index 37bdd0d2c8..ce15a5909e 100644 --- a/types/json2md/index.d.ts +++ b/types/json2md/index.d.ts @@ -6,6 +6,13 @@ export = json2md; +/** + * Converts a JSON input to markdown. + * + * @param data The input JSON data. + * @param prefix A snippet to add before each line. + * @return The generated markdown result. + */ declare function json2md(data: json2md.DataObject | json2md.DataObject[] | string | string[], prefix?: string): string; type json2md = typeof json2md; From bb558a2d7999a78d7abcea0f52e1d3adbd3a86d5 Mon Sep 17 00:00:00 2001 From: Simon Korz Date: Mon, 10 Jul 2017 14:05:10 +0200 Subject: [PATCH 0306/1618] three: Specify DirectionalLightShadow types - DirectionalLight.shadow from LightShadow to DirectionalLightShadow - DirectionalLightShadow.camera from Camera to OrthographicCamera Reason: DirectionalLight always uses DirectionalLightShadow with OrthographicCamera and properties of OrthographicCamera that are not in Camera need to be available. Also see: https://threejs.org/docs/index.html#api/lights/shadows/DirectionalLightShadow --- types/three/three-core.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 7a6a6ec9ac..c01f6fddfd 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -1937,10 +1937,12 @@ export class DirectionalLight extends Light { */ intensity: number; - shadow: LightShadow; + shadow: DirectionalLightShadow; } -export class DirectionalLightShadow extends LightShadow {} +export class DirectionalLightShadow extends LightShadow { + camera: OrthographicCamera; +} export class HemisphereLight extends Light { constructor(skyColorHex?: number|string, groundColorHex?: number|string, intensity?: number); From 9ef6dc6a7b40bc8fd86ec6e580deda94652668c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 13:04:34 +0100 Subject: [PATCH 0307/1618] Flesh out Subscriable type to better match ES Observable spec --- types/recompose/index.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 3e3d6b85ae..ee99adca68 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -16,8 +16,18 @@ declare module 'recompose' { type mapper = (input: TInner) => TOutter; type predicate = mapper; type predicateDiff = (current: T, next: T) => boolean + interface Observer { + next(value: T): void; + error(err: any): void; + complete(): void; + } + + interface Subscription { + unsubscribe(): void; + closed: boolean; + } interface Subscribable { - subscribe: Function; + subscribe(observer: Observer):Subscription; } interface ComponentEnhancer { From 97396df6e129c6e0b083d80450b45bb50230b18e Mon Sep 17 00:00:00 2001 From: FreshRob Date: Mon, 10 Jul 2017 13:33:47 +0100 Subject: [PATCH 0308/1618] Step to number + Added cookie path Step changed from boolean to number (ref: https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce) Added cookiePath (ref: https://www.optimizesmart.com/google-analytics-cookies-ultimate-guide/) --- types/google.analytics/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/google.analytics/index.d.ts b/types/google.analytics/index.d.ts index ad292f7fe1..4e4487a9d4 100644 --- a/types/google.analytics/index.d.ts +++ b/types/google.analytics/index.d.ts @@ -77,6 +77,7 @@ declare namespace UniversalAnalytics { cookieName?: string; cookieDomain?: string; cookieExpires?: number; + cookiePath?: string coupon?: string; creative?: string; currencyCode?: string; @@ -524,7 +525,7 @@ declare namespace UniversalAnalytics { socialNetwork?: string; socialTarget?: string; some?: string; - step?: boolean; + step?: number; tax?: string; timingCategory?: string; timingLabel?: string; From c7adfa4392eb201433ca297b69d5c4c7409c7cfb Mon Sep 17 00:00:00 2001 From: FreshRob Date: Mon, 10 Jul 2017 14:31:24 +0100 Subject: [PATCH 0309/1618] Added missing semicolon Added missing semicolon --- types/google.analytics/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/google.analytics/index.d.ts b/types/google.analytics/index.d.ts index 4e4487a9d4..715e4b529b 100644 --- a/types/google.analytics/index.d.ts +++ b/types/google.analytics/index.d.ts @@ -77,7 +77,7 @@ declare namespace UniversalAnalytics { cookieName?: string; cookieDomain?: string; cookieExpires?: number; - cookiePath?: string + cookiePath?: string; coupon?: string; creative?: string; currencyCode?: string; From d14bffff32baf84c971fd5676e0732b16756dee4 Mon Sep 17 00:00:00 2001 From: Grzegorz Kielak Date: Mon, 10 Jul 2017 15:19:01 +0200 Subject: [PATCH 0310/1618] Add types for react-touch https://github.com/leonaves/react-touch --- types/react-touch/index.d.ts | 102 ++++++++++++++++++++++++ types/react-touch/react-touch-tests.tsx | 62 ++++++++++++++ types/react-touch/tsconfig.json | 24 ++++++ types/react-touch/tslint.json | 3 + 4 files changed, 191 insertions(+) create mode 100644 types/react-touch/index.d.ts create mode 100644 types/react-touch/react-touch-tests.tsx create mode 100644 types/react-touch/tsconfig.json create mode 100644 types/react-touch/tslint.json diff --git a/types/react-touch/index.d.ts b/types/react-touch/index.d.ts new file mode 100644 index 0000000000..7359abd1f4 --- /dev/null +++ b/types/react-touch/index.d.ts @@ -0,0 +1,102 @@ +// Type definitions for react-touch 1.8 +// Project: https://github.com/leonaves/react-touch +// Definitions by: Grzegorz Kielak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import * as React from "react"; + +export function defineHold(config?: HoldConfig): HoldableConfig; + +export interface HoldConfig { + /** @default 250 */ + updateEvery?: number; + /** @default 1000 */ + holdFor?: number; +} + +/** @see defineHold */ +export interface HoldableConfig { + holdProgress(callback: () => void): (updateState: (holdLength: number) => void) => () => void; + holdComplete(callback: () => void): () => () => void; +} + +export interface HoldableProps { + /** @see defineHold */ + config?: HoldableConfig; + onHoldProgress?(): void; + onHoldComplete?(): void; + onMouseDown?(): void; + onTouchStart?(): void; +} + +export class Holdable extends React.Component { +} + +export interface DraggableStyle { + translateX?: number; + translateY?: number; + top?: number; + left?: number; + right?: number; + bottom?: number; +} + +export interface DraggableCallbackArgument extends DraggableStyle { + dx: number; + dy: number; +} + +export type DraggableCallback = (argument: DraggableCallbackArgument) => JSX.Element; + +export interface DraggableProps { + /** + * An object that defines the initial position of the draggable component. + * You can pass any of the following styles to it + * and they'll be updated and passed back out in the callback with every animation tick. + */ + style: DraggableStyle; + children: DraggableCallback; +} + +export class Draggable extends React.Component { +} + +export function defineSwipe(config?: SwipConfig): SwipeableConfig; + +export interface SwipConfig { + /** @default 100 */ + swipeDistance?: number; +} + +/** @see defineSwipe */ +export interface SwipeableConfig { + onSwipeLeft(current: number, initial: number, callback: () => void): void; + onSwipeRight(current: number, initial: number, callback: () => void): void; + onSwipeUp(current: number, initial: number, callback: () => void): void; + onSwipeDown(current: number, initial: number, callback: () => void): void; +} + +export interface SwipeableProps { + /** @see defineSwipe */ + config?: SwipeableConfig; + onSwipeLeft?(): void; + onSwipeRight?(): void; + onSwipeUp?(): void; + onSwipeDown?(): void; + onMouseDown?(): void; + onTouchStart?(): void; +} + +export class Swipeable extends React.Component { +} + +export enum moves {UPLEFT, UP, UPRIGHT, LEFT, RIGHT, DOWNRIGHT, DOWN, DOWNLEFT} + +export interface CustomGestureProps { + config: moves[]; + onGesture(): void; +} + +export class CustomGesture extends React.Component { +} diff --git a/types/react-touch/react-touch-tests.tsx b/types/react-touch/react-touch-tests.tsx new file mode 100644 index 0000000000..4efaaa33b1 --- /dev/null +++ b/types/react-touch/react-touch-tests.tsx @@ -0,0 +1,62 @@ +import * as React from "react"; +import { + CustomGesture, + defineHold, defineSwipe, Draggable, DraggableCallbackArgument, DraggableStyle, Holdable, HoldableConfig, + HoldableProps, HoldConfig, moves, SwipConfig, Swipeable, SwipeableConfig, SwipeableProps +} from "react-touch"; + +export class HoldableTest extends React.PureComponent<{}> { + render() { + const holdConfig: HoldConfig = {}; + const config: HoldableConfig = defineHold(holdConfig); + const props: HoldableProps = { + config, + onHoldComplete() { + return; + } + }; + return ; + } +} + +export class DraggableTest extends React.PureComponent<{}> { + render() { + const style: DraggableStyle = {}; + return ; + } + + private callback = (argument: DraggableCallbackArgument): JSX.Element => { + return
    ; + } +} + +export class SwipeableTest extends React.PureComponent<{}> { + render() { + const swipConfig: SwipConfig = {}; + const config: SwipeableConfig = defineSwipe(swipConfig); + const props: SwipeableProps = { + config, + onSwipeLeft: this.swipeHandler, + onSwipeUp: this.swipeHandler + }; + return +
    + ; + } + + private swipeHandler = () => { + return; + } +} + +export class CustomGestureTest extends React.PureComponent<{}> { + private move: moves[] = [moves.UPLEFT, moves.RIGHT, moves.DOWNRIGHT]; + + render() { + return ; + } + + private handler = () => { + return; + } +} diff --git a/types/react-touch/tsconfig.json b/types/react-touch/tsconfig.json new file mode 100644 index 0000000000..931b273805 --- /dev/null +++ b/types/react-touch/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-touch-tests.tsx" + ] +} diff --git a/types/react-touch/tslint.json b/types/react-touch/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/react-touch/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From eb26c6134140d9977a7f06f24a09fb8b1472a42a Mon Sep 17 00:00:00 2001 From: Kyle Roach Date: Mon, 10 Jul 2017 10:58:40 -0400 Subject: [PATCH 0311/1618] Adding typings for react-native-collapsible --- types/react-native-collapsible/Accordion.d.ts | 64 +++++++++++++++ types/react-native-collapsible/index.d.ts | 79 +++++++++++++++++++ .../react-native-collapsible-tests.tsx | 38 +++++++++ types/react-native-collapsible/tsconfig.json | 24 ++++++ types/react-native-collapsible/tslint.json | 1 + 5 files changed, 206 insertions(+) create mode 100644 types/react-native-collapsible/Accordion.d.ts create mode 100644 types/react-native-collapsible/index.d.ts create mode 100644 types/react-native-collapsible/react-native-collapsible-tests.tsx create mode 100644 types/react-native-collapsible/tsconfig.json create mode 100644 types/react-native-collapsible/tslint.json diff --git a/types/react-native-collapsible/Accordion.d.ts b/types/react-native-collapsible/Accordion.d.ts new file mode 100644 index 0000000000..2a2fc04a9f --- /dev/null +++ b/types/react-native-collapsible/Accordion.d.ts @@ -0,0 +1,64 @@ +import * as React from 'react'; +import { EasingMode } from './index'; + +export interface AccordionProps { + /** + * An array of sections passed to the render methods + */ + sections: string[]; + + /** + * A function that should return a renderable representing the header + */ + renderHeader(content: any, index: number, isActive: boolean): JSX.Element; + + /** + * A function that should return a renderable representing the content + */ + renderContent(content: any, index: number, isActive: boolean): JSX.Element; + + /** + * An optional function that is called when currently active section is changed, index === false when collapsed + */ + onChange?(index: number): void; + + /** + * Set which index in the sections array is initially open. Defaults to none. + */ + initiallyActiveSection?: number; + + /** + * Control which index in the sections array is currently open. Defaults to none. If false, closes all sections. + */ + activeSection?: boolean | number; + + /** + * The color of the underlay that will show through when tapping on headers. + * + * @default black + */ + underlayColor?: string; + + /** + * Alignment of the content when transitioning, can be top, center or bottom + * + * @default top + */ + align?: 'top' | 'center' | 'bottom'; + + /** + * Duration of transition in milliseconds + * + * @default 300 + */ + duration?: number; + + /** + * Function or function name from Easing (or tween-functions if < RN 0.8). Collapsible will try to combine Easing functions for you if you name them like tween-functions. + * + * @default easeOutCubic + */ + easing?: EasingMode | any; +} + +export default class Accordion extends React.Component {} diff --git a/types/react-native-collapsible/index.d.ts b/types/react-native-collapsible/index.d.ts new file mode 100644 index 0000000000..bdd8dd9ea5 --- /dev/null +++ b/types/react-native-collapsible/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for react-native-collapsible 0.8 +// Project: https://github.com/oblador/react-native-collapsible +// Definitions by: Kyle Roach +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from 'react'; + +export type EasingMode = +'linear' | +'easeInQuad' | +'easeOutQuad' | +'easeInOutQuad' | +'easeInCubic' | +'easeOutCubic' | +'easeInOutCubic' | +'easeInQuart' | +'easeOutQuart' | +'easeInOutQuart' | +'easeInQuint' | +'easeOutQuint' | +'easeInOutQuint' | +'easeInSine' | +'easeOutSine' | +'easeInOutSine' | +'easeInExpo' | +'easeOutExpo' | +'easeInOutExpo' | +'easeInCirc' | +'easeOutCirc' | +'easeInOutCirc' | +'easeInElastic' | +'easeOutElastic' | +'easeInOutElastic' | +'easeInBack' | +'easeOutBack' | +'easeInOutBack' | +'easeInBounce' | +'easeOutBounce' | +'easeInOutBounce'; + +export interface CollapsibleProps { + /** + * Alignment of the content when transitioning, can be top, center or bottom + * + * @default top + */ + align?: 'top' | 'center' | 'bottom'; + + /** + * Whether to show the child components or not + * + * @default true + */ + collapsed?: boolean; + + /** + * Which height should the component collapse to + * + * @default 0 + */ + collapsedHeight?: number; + + /** + * Duration of transition in milliseconds + * + * @default 300 + */ + duration?: number; + + /** + * Function or function name from Easing (or tween-functions if < RN 0.8). Collapsible will try to combine Easing functions for you if you name them like tween-functions + * + * @default easeOutCubic + */ + easing?: EasingMode | any; +} + +export default class Collapsible extends React.Component {} diff --git a/types/react-native-collapsible/react-native-collapsible-tests.tsx b/types/react-native-collapsible/react-native-collapsible-tests.tsx new file mode 100644 index 0000000000..1107084f3d --- /dev/null +++ b/types/react-native-collapsible/react-native-collapsible-tests.tsx @@ -0,0 +1,38 @@ +import * as React from 'react'; +import { View } from 'react-native'; +import Collapsible from 'react-native-collapsible'; +import Accordion from 'react-native-collapsible/Accordion'; + +class CollapsibleTest extends React.Component { + render() { + return ( + + + + ); + } +} + +class AccordianTest extends React.Component { + _renderHeader() { + return ( + + ); + } + + _renderContent() { + return ( + + ); + } + + render() { + return ( + + ); + } +} diff --git a/types/react-native-collapsible/tsconfig.json b/types/react-native-collapsible/tsconfig.json new file mode 100644 index 0000000000..1e5b287fb1 --- /dev/null +++ b/types/react-native-collapsible/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "Accordion.d.ts", + "react-native-collapsible-tests.tsx" + ] +} diff --git a/types/react-native-collapsible/tslint.json b/types/react-native-collapsible/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-collapsible/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From eadb478a2e42a6befda6dcaee1da5f7bee6ae118 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B3natan=20N=C3=BA=C3=B1ez?= Date: Mon, 10 Jul 2017 17:17:13 +0200 Subject: [PATCH 0312/1618] [@types/bootstrap] allow call affix command Allow call affix command like 'checkPosition' http://getbootstrap.com/javascript/#affix-checkposition --- types/bootstrap/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/bootstrap/index.d.ts b/types/bootstrap/index.d.ts index 53d9b45b37..cd15ad62ee 100644 --- a/types/bootstrap/index.d.ts +++ b/types/bootstrap/index.d.ts @@ -119,6 +119,7 @@ interface JQuery { typeahead(options?: TypeaheadOptions): JQuery; affix(options?: AffixOptions): JQuery; + affix(command: string): JQuery; emulateTransitionEnd(duration: number): JQuery; } From 7db3bd0d08ef03c278ac6311fb5a3d062e9d5473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 16:29:21 +0100 Subject: [PATCH 0313/1618] Was able to simplfy things --- types/recompose/index.d.ts | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index ee99adca68..6b84b33034 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -15,19 +15,10 @@ declare module 'recompose' { type Component

    = ComponentClass

    | StatelessComponent

    ; type mapper = (input: TInner) => TOutter; type predicate = mapper; - type predicateDiff = (current: T, next: T) => boolean - interface Observer { - next(value: T): void; - error(err: any): void; - complete(): void; - } + type predicateDiff = (current: T, next: T) => boolean} - interface Subscription { - unsubscribe(): void; - closed: boolean; - } interface Subscribable { - subscribe(observer: Observer):Subscription; + subscribe(observer: any):any; } interface ComponentEnhancer { From d58e9e015a85b38180c0c15a15dc2d15076d6175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 16:45:11 +0100 Subject: [PATCH 0314/1618] Fix CI Fail; forgot Ctrl-S on my end --- types/recompose/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 6b84b33034..dedc360f4d 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -15,7 +15,7 @@ declare module 'recompose' { type Component

    = ComponentClass

    | StatelessComponent

    ; type mapper = (input: TInner) => TOutter; type predicate = mapper; - type predicateDiff = (current: T, next: T) => boolean} + type predicateDiff = (current: T, next: T) => boolean interface Subscribable { subscribe(observer: any):any; From 57879fda5a28312d2177145665b16cab78a56282 Mon Sep 17 00:00:00 2001 From: Manusan Date: Mon, 10 Jul 2017 17:47:28 +0200 Subject: [PATCH 0315/1618] binary flag is gone on ping and pong which reduces the options object to the mask boolean --- types/ws/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/ws/index.d.ts b/types/ws/index.d.ts index fc072727e8..8dc6cfa746 100644 --- a/types/ws/index.d.ts +++ b/types/ws/index.d.ts @@ -43,8 +43,8 @@ declare class WebSocket extends events.EventEmitter { close(code?: number, data?: any): void; pause(): void; resume(): void; - ping(data?: any, options?: { mask?: boolean; binary?: boolean }, dontFail?: boolean): void; - pong(data?: any, options?: { mask?: boolean; binary?: boolean }, dontFail?: boolean): void; + ping(data?: any, mask?: boolean, dontFail?: boolean): void; + pong(data?: any, mask?: boolean, dontFail?: boolean): void; send(data: any, cb?: (err: Error) => void): void; send(data: any, options: { mask?: boolean; binary?: boolean }, cb?: (err: Error) => void): void; stream(options: { mask?: boolean; binary?: boolean }, cb?: (err: Error, final: boolean) => void): void; @@ -76,8 +76,8 @@ declare class WebSocket extends events.EventEmitter { addListener(event: 'close', cb: (code: number, message: string) => void): this; addListener(event: 'headers', cb: (headers: {}, request: http.IncomingMessage) => void): this; addListener(event: 'message', cb: (data: WebSocket.Data, flags: { binary: boolean }) => void): this; - addListener(event: 'ping', cb: (data: Buffer, flags: { binary: boolean }) => void): this; - addListener(event: 'pong', cb: (data: Buffer, flags: { binary: boolean }) => void): this; + addListener(event: 'ping', cb: (data: Buffer) => void): this; + addListener(event: 'pong', cb: (data: Buffer) => void): this; addListener(event: 'open', cb: () => void): this; addListener(event: 'unexpected-response', cb: (request: http.ClientRequest, response: http.IncomingMessage) => void): this; addListener(event: string, listener: () => void): this; From bc2c62ee87ca04098a63f2c4606aa6e970f4be7c Mon Sep 17 00:00:00 2001 From: Nick McGuire Date: Mon, 10 Jul 2017 11:52:52 -0400 Subject: [PATCH 0316/1618] [react-native] Added two TextInput Android properties Added two properties to the TextInputAndroidProperties interface: - disableFullscreenUI - textBreakStrategy --- types/react-native/index.d.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 13d32d8321..dfdfde82c6 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1020,6 +1020,14 @@ export interface TextInputIOSProperties { */ export interface TextInputAndroidProperties { + /** + * When false, if there is a small amount of space available around a text input (e.g. landscape orientation on a phone), + * the OS may choose to have the user edit the text inside of a full screen text input mode. + * When true, this feature is disabled and users will always edit the text directly inside of the text input. + * Defaults to false. + */ + disableFullscreenUI?: boolean + /** * If defined, the provided image resource will be rendered on the left. */ @@ -1042,6 +1050,12 @@ export interface TextInputAndroidProperties { */ returnKeyLabel?: string + /** + * Set text break strategy on Android API Level 23+, possible values are simple, highQuality, balanced + * The default value is simple. + */ + textBreakStrategy?: "simple" | "highQuality" | "balanced" + /** * The color of the textInput underline. */ From a3f1955c46c8693cd7ca78cf4e716698aaf417a1 Mon Sep 17 00:00:00 2001 From: Kyle Roach Date: Mon, 10 Jul 2017 12:17:35 -0400 Subject: [PATCH 0317/1618] Added definitions for react-native-material-design-searchbar --- .../index.d.ts | 41 +++++++++++++++++++ ...native-material-design-searchbar-tests.tsx | 19 +++++++++ .../tsconfig.json | 24 +++++++++++ .../tslint.json | 1 + 4 files changed, 85 insertions(+) create mode 100644 types/react-native-material-design-searchbar/index.d.ts create mode 100644 types/react-native-material-design-searchbar/react-native-material-design-searchbar-tests.tsx create mode 100644 types/react-native-material-design-searchbar/tsconfig.json create mode 100644 types/react-native-material-design-searchbar/tslint.json diff --git a/types/react-native-material-design-searchbar/index.d.ts b/types/react-native-material-design-searchbar/index.d.ts new file mode 100644 index 0000000000..d2269fae4b --- /dev/null +++ b/types/react-native-material-design-searchbar/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for react-native-material-design-searchbar 1.1 +// Project: https://github.com/ananddayalan/react-native-material-design-searchbar +// Definitions by: Kyle Roach +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from 'react'; +import { + TextInputProperties, + ReturnKeyType, + ReturnKeyTypeAndroid, + TextStyle, + ReturnKeyTypeIOS, +} from 'react-native'; + +export interface SearchBarProps { + height: number; + autoCorrect?: boolean; + returnKeyType?: ReturnKeyType | ReturnKeyTypeAndroid | ReturnKeyTypeIOS; + placeholder?: string; + padding?: number; + inputStyle?: TextStyle; + iconCloseName?: string; + iconSearchName?: string; + iconBackName?: string; + iconSize?: number; + iconPadding?: number; + placeholderColor?: string; + iconColor?: string; + textStyle?: TextStyle; + inputProps?: TextInputProperties; + onSearchChange?(text: string): void; + onClose?(): void; + onBlur?(): void; + onEndEditing?(): void; + onSubmitEditing?(): void; + onFocus?(): void; + onBackPress?(): void; +} + +export default class SearchBar extends React.Component {} diff --git a/types/react-native-material-design-searchbar/react-native-material-design-searchbar-tests.tsx b/types/react-native-material-design-searchbar/react-native-material-design-searchbar-tests.tsx new file mode 100644 index 0000000000..fec9daf4a3 --- /dev/null +++ b/types/react-native-material-design-searchbar/react-native-material-design-searchbar-tests.tsx @@ -0,0 +1,19 @@ +import * as React from 'react'; +import SearchBar from 'react-native-material-design-searchbar'; + +class SearchbarTest extends React.Component { + render() { + return ( + console.log('On Search Change')} + height={50} + onFocus={() => console.log('On Focus')} + onBlur={() => console.log('On Blur')} + placeholder={'Search...'} + autoCorrect={false} + padding={5} + returnKeyType={'search'} + /> + ); + } +} diff --git a/types/react-native-material-design-searchbar/tsconfig.json b/types/react-native-material-design-searchbar/tsconfig.json new file mode 100644 index 0000000000..d45789898e --- /dev/null +++ b/types/react-native-material-design-searchbar/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-native-material-design-searchbar-tests.tsx" + ] +} diff --git a/types/react-native-material-design-searchbar/tslint.json b/types/react-native-material-design-searchbar/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-material-design-searchbar/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e525932a5b6916f01c784763c0e4ee346d5213a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 17:35:23 +0100 Subject: [PATCH 0318/1618] Rewrote again to match observable found in componentFromStream --- types/recompose/index.d.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index dedc360f4d..09c8d6a59d 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -17,8 +17,17 @@ declare module 'recompose' { type predicate = mapper; type predicateDiff = (current: T, next: T) => boolean + interface Observer{ + next(props: T): void; + complete(): void; + } + + interface Subscription{ + unsubscribe(): void + } + interface Subscribable { - subscribe(observer: any):any; + subscribe(observer: Observer): Subscription; } interface ComponentEnhancer { From 668fb871aeeb385ba5ce2be31540309d527e32b5 Mon Sep 17 00:00:00 2001 From: Mohsen Azimi Date: Mon, 10 Jul 2017 10:45:41 -0700 Subject: [PATCH 0319/1618] Make render optional in react-loadable Reference: https://github.com/thejameskyle/react-loadable#example --- types/react-loadable/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-loadable/index.d.ts b/types/react-loadable/index.d.ts index 424372a068..b9ea35c5b0 100644 --- a/types/react-loadable/index.d.ts +++ b/types/react-loadable/index.d.ts @@ -67,7 +67,7 @@ export interface OptionsWithRender extends Common * }); * ``` */ - render(loaded: Exports, props: Props): React.ReactNode; + render?(loaded: Exports, props: Props): React.ReactNode; } export interface OptionsWithMap extends CommonOptions { From 25e6685bd45837b607891051b2184c2f6ab9f0b7 Mon Sep 17 00:00:00 2001 From: Flur Date: Mon, 10 Jul 2017 22:50:13 +0300 Subject: [PATCH 0320/1618] - add null return --- types/three/three-core.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 820faa1fab..629c9c6ba7 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -2096,7 +2096,7 @@ export interface LoaderHandler { handlers: (RegExp | AnyLoader)[]; add(regex: RegExp, loader: AnyLoader): void; - get(file: string): AnyLoader; + get(file: string): AnyLoader | null; } export class FileLoader { From bdc0554a965474a4e5a4e70b7d73ea00b7199a61 Mon Sep 17 00:00:00 2001 From: Flur Date: Mon, 10 Jul 2017 23:20:25 +0300 Subject: [PATCH 0321/1618] - add events --- types/three/three-mtlloader.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/three/three-mtlloader.d.ts b/types/three/three-mtlloader.d.ts index a795a293de..dce5b12a17 100644 --- a/types/three/three-mtlloader.d.ts +++ b/types/three/three-mtlloader.d.ts @@ -17,7 +17,7 @@ export class MTLLoader extends EventDispatcher { texturePath: string; crossOrigin: boolean; - load(url: string, onLoad: (materialCreator: MaterialCreator) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + load(url: string, onLoad: (materialCreator: MaterialCreator) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; parse(text: string) : MaterialCreator; setPath(path: string) : void; setTexturePath(path: string) : void; From a24aee6125213ba20a5bda15a5d4fce8b60b2f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Goetz?= Date: Mon, 10 Jul 2017 22:43:07 +0200 Subject: [PATCH 0322/1618] Improve react typings for HTML attributes, fix tests in other libraries --- types/material-ui/index.d.ts | 9 +- types/react-dropzone/index.d.ts | 2 +- types/react-input-mask/index.d.ts | 2 +- types/react-router-dom/index.d.ts | 2 +- .../CustomLink.tsx | 1 + .../react-user-tour/react-user-tour-tests.tsx | 2 +- types/react/index.d.ts | 1078 +++++++++++------ types/reactstrap/lib/Input.d.ts | 2 +- types/reactstrap/lib/Label.d.ts | 2 +- 9 files changed, 744 insertions(+), 356 deletions(-) diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index d44911add5..ec7ad246b4 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1128,6 +1128,7 @@ declare namespace __MaterialUI { secondaryText?: React.ReactNode; secondaryTextLines?: number; // 1 or 2 style?: React.CSSProperties; + value?: any; } export class ListItem extends React.Component { } @@ -1174,6 +1175,7 @@ declare namespace __MaterialUI { focusState?: string; // 'none', 'focused', or 'keyboard-focused' innerDivStyle?: React.CSSProperties; insetChildren?: boolean; + label?: string | React.ReactNode; leftIcon?: React.ReactElement; menuItems?: React.ReactNode; onTouchTap?: TouchTapEventHandler; @@ -1181,7 +1183,6 @@ declare namespace __MaterialUI { rightIcon?: React.ReactElement; secondaryText?: React.ReactNode; style?: React.CSSProperties; - value?: any; containerElement?: React.ReactNode | string; } export class MenuItem extends React.Component { @@ -1264,6 +1265,8 @@ declare namespace __MaterialUI { style?: React.CSSProperties; transitionEnabled?: boolean; zDepth?: number; + width?: number | string; + height?: number | string; } export class Paper extends React.Component { } @@ -1413,7 +1416,8 @@ declare namespace __MaterialUI { namespace Switches { // what's not commonly overridden by Checkbox, RadioButton, or Toggle - interface CommonEnhancedSwitchProps extends React.HTMLAttributes<{}>, React.Props { + interface CommonEnhancedSwitchProps extends React.InputHTMLAttributes<{}>, React.Props { + label?: React.ReactNode; } interface EnhancedSwitchProps extends CommonEnhancedSwitchProps { @@ -1427,7 +1431,6 @@ declare namespace __MaterialUI { id?: string; inputStyle: React.CSSProperties; inputType: string; - label?: string; labelPosition?: string; // oneOf(['left', 'right']) labelStyle?: React.CSSProperties; name?: string; diff --git a/types/react-dropzone/index.d.ts b/types/react-dropzone/index.d.ts index c47b64d9bc..cd07fd3341 100644 --- a/types/react-dropzone/index.d.ts +++ b/types/react-dropzone/index.d.ts @@ -28,7 +28,7 @@ declare module "react-dropzone" { disablePreview?: boolean; // Enable/disable preview generation disableClick?: boolean; // Disallow clicking on the dropzone container to open file dialog - inputProps?: React.ChangeTargetHTMLProps; // Pass additional attributes to the tag + inputProps?: React.InputHTMLAttributes; // Pass additional attributes to the tag multiple?: boolean; // Allow dropping multiple files accept?: string; // Allow specific types of files. See https://github.com/okonet/attr-accept for more information name?: string; // name attribute for the input tag diff --git a/types/react-input-mask/index.d.ts b/types/react-input-mask/index.d.ts index 4396198fde..a830650812 100644 --- a/types/react-input-mask/index.d.ts +++ b/types/react-input-mask/index.d.ts @@ -7,7 +7,7 @@ import * as React from "react"; declare namespace reactInputMask { - interface ReactInputMaskProps extends React.HTMLAttributes { + interface ReactInputMaskProps extends React.InputHTMLAttributes { /** * Mask string. Format characters are: * * `9`: `0-9` diff --git a/types/react-router-dom/index.d.ts b/types/react-router-dom/index.d.ts index 52ec2352f2..a70613fa81 100644 --- a/types/react-router-dom/index.d.ts +++ b/types/react-router-dom/index.d.ts @@ -39,7 +39,7 @@ declare module 'react-router-dom' { } class HashRouter extends React.Component {} - interface LinkProps extends React.HTMLAttributes { + interface LinkProps extends React.AnchorHTMLAttributes { to: H.LocationDescriptor; replace?: boolean; } diff --git a/types/react-router/test/examples-from-react-router-website/CustomLink.tsx b/types/react-router/test/examples-from-react-router-website/CustomLink.tsx index 4ec8be4c87..f3b1fb180e 100644 --- a/types/react-router/test/examples-from-react-router-website/CustomLink.tsx +++ b/types/react-router/test/examples-from-react-router-website/CustomLink.tsx @@ -20,6 +20,7 @@ const CustomLinkExample = () => ( interface OldSchoolMenuLinkProps extends LinkProps { activeOnlyWhenExact?: boolean; + label: string; } const OldSchoolMenuLink: React.SFC = ({ label, to, activeOnlyWhenExact }) => ( diff --git a/types/react-user-tour/react-user-tour-tests.tsx b/types/react-user-tour/react-user-tour-tests.tsx index c961ee5bbd..56e4e2c2ce 100644 --- a/types/react-user-tour/react-user-tour-tests.tsx +++ b/types/react-user-tour/react-user-tour-tests.tsx @@ -44,7 +44,7 @@ class TestApp extends React.Component<{}, State> { ]} />; - return

    + return
    {Tour}
    ; } diff --git a/types/react/index.d.ts b/types/react/index.d.ts index df4a9f5374..537b6eefde 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -11,6 +11,7 @@ // Albert Kurniawan // Tanguy Krotoff // Dovydas Navickas +// Stéphane Goetz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -76,7 +77,10 @@ declare namespace React { } // ReactHTML for ReactHTMLElement - interface ReactHTMLElement extends DOMElement, T> { + // tslint:disable-next-line:no-empty-interface + interface ReactHTMLElement extends DetailedReactHTMLElement, T> { } + + interface DetailedReactHTMLElement

    , T extends HTMLElement> extends DOMElement { type: keyof ReactHTML; } @@ -102,12 +106,11 @@ declare namespace React { type DOMFactory

    , T extends Element> = (props?: ClassAttributes & P | null, ...children: ReactNode[]) => DOMElement; - interface HTMLFactory extends DOMFactory, T> { - (props?: ClassAttributes & HTMLAttributes | null, ...children: ReactNode[]): ReactHTMLElement; - } + // tslint:disable-next-line:no-empty-interface + interface HTMLFactory extends DetailedHTMLFactory, T> {} - interface ChangeTargetHTMLFactory extends DOMFactory, T> { - (props?: ClassAttributes & ChangeTargetHTMLAttributes | null, ...children: ReactNode[]): ReactHTMLElement; + interface DetailedHTMLFactory

    , T extends HTMLElement> extends DOMFactory { + (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; } interface SVGFactory extends DOMFactory, SVGElement> { @@ -152,7 +155,7 @@ declare namespace React { function createElement

    , T extends HTMLElement>( type: keyof ReactHTML, props?: ClassAttributes & P, - ...children: ReactNode[]): ReactHTMLElement; + ...children: ReactNode[]): DetailedReactHTMLElement; function createElement

    , T extends SVGElement>( type: keyof ReactSVG, props?: ClassAttributes & P, @@ -182,6 +185,11 @@ declare namespace React { // DOM Elements // ReactHTMLElement + function cloneElement

    , T extends HTMLElement>( + element: DetailedReactHTMLElement, + props?: P, + ...children: ReactNode[]): DetailedReactHTMLElement; + // ReactHTMLElement, less specific function cloneElement

    , T extends HTMLElement>( element: ReactHTMLElement, props?: P, @@ -511,11 +519,10 @@ declare namespace React { ref?: Ref; } - interface HTMLProps extends HTMLAttributes, ClassAttributes { + interface HTMLProps extends AllHTMLAttributes, ClassAttributes { } - interface ChangeTargetHTMLProps extends ChangeTargetHTMLAttributes, ClassAttributes { - } + type DetailedHTMLProps, T> = ClassAttributes & E; interface SVGProps extends SVGAttributes, ClassAttributes { } @@ -2327,129 +2334,28 @@ declare namespace React { suppressContentEditableWarning?: boolean; // Standard HTML Attributes - accept?: string; - acceptCharset?: string; accessKey?: string; - action?: string; - allowFullScreen?: boolean; - allowTransparency?: boolean; - alt?: string; - async?: boolean; - autoComplete?: string; - autoFocus?: boolean; - autoPlay?: boolean; - capture?: boolean; - cellPadding?: number | string; - cellSpacing?: number | string; - charSet?: string; - challenge?: string; - checked?: boolean; - cite?: string; - classID?: string; className?: string; - cols?: number; - colSpan?: number; - content?: string; contentEditable?: boolean; contextMenu?: string; - controls?: boolean; - coords?: string; - crossOrigin?: string; - data?: string; - dateTime?: string; - default?: boolean; - defer?: boolean; dir?: string; - disabled?: boolean; - download?: any; draggable?: boolean; - encType?: string; - form?: string; - formAction?: string; - formEncType?: string; - formMethod?: string; - formNoValidate?: boolean; - formTarget?: string; - frameBorder?: number | string; - headers?: string; - height?: number | string; hidden?: boolean; - high?: number; - href?: string; - hrefLang?: string; - htmlFor?: string; - httpEquiv?: string; id?: string; - inputMode?: string; - integrity?: string; - is?: string; - keyParams?: string; - keyType?: string; - kind?: string; - label?: string; lang?: string; - list?: string; - loop?: boolean; - low?: number; - manifest?: string; - marginHeight?: number; - marginWidth?: number; - max?: number | string; - maxLength?: number; - media?: string; - mediaGroup?: string; - method?: string; - min?: number | string; - minLength?: number; - multiple?: boolean; - muted?: boolean; - name?: string; - nonce?: string; - noValidate?: boolean; - open?: boolean; - optimum?: number; - pattern?: string; - placeholder?: string; - playsInline?: boolean; - poster?: string; - preload?: string; - radioGroup?: string; - readOnly?: boolean; - rel?: string; - required?: boolean; - reversed?: boolean; - role?: string; - rows?: number; - rowSpan?: number; - sandbox?: string; - scope?: string; - scoped?: boolean; - scrolling?: string; - seamless?: boolean; - selected?: boolean; - shape?: string; - size?: number; - sizes?: string; slot?: string; - span?: number; spellCheck?: boolean; - src?: string; - srcDoc?: string; - srcLang?: string; - srcSet?: string; - start?: number; - step?: number | string; style?: CSSProperties; - summary?: string; tabIndex?: number; - target?: string; title?: string; - type?: string; - useMap?: string; - value?: string | string[] | number; - width?: number | string; - wmode?: string; - wrap?: string; + + // Unknown + inputMode?: string; + is?: string; + radioGroup?: string; // , + + // WAI-ARIA + role?: string; // RDFa Attributes about?: string; @@ -2476,10 +2382,488 @@ declare namespace React { unselectable?: boolean; } - interface ChangeTargetHTMLAttributes extends HTMLAttributes { + interface AllHTMLAttributes extends HTMLAttributes { + // Standard HTML Attributes + accept?: string; + acceptCharset?: string; + action?: string; + allowFullScreen?: boolean; + allowTransparency?: boolean; + alt?: string; + async?: boolean; + autoComplete?: string; + autoFocus?: boolean; + autoPlay?: boolean; + capture?: boolean; + cellPadding?: number | string; + cellSpacing?: number | string; + charSet?: string; + challenge?: string; + checked?: boolean; + cite?: string; + classID?: string; + cols?: number; + colSpan?: number; + content?: string; + controls?: boolean; + coords?: string; + crossOrigin?: string; + data?: string; + dateTime?: string; + default?: boolean; + defer?: boolean; + disabled?: boolean; + download?: any; + encType?: string; + form?: string; + formAction?: string; + formEncType?: string; + formMethod?: string; + formNoValidate?: boolean; + formTarget?: string; + frameBorder?: number | string; + headers?: string; + height?: number | string; + high?: number; + href?: string; + hrefLang?: string; + htmlFor?: string; + httpEquiv?: string; + integrity?: string; + keyParams?: string; + keyType?: string; + kind?: string; + label?: string; + list?: string; + loop?: boolean; + low?: number; + manifest?: string; + marginHeight?: number; + marginWidth?: number; + max?: number | string; + maxLength?: number; + media?: string; + mediaGroup?: string; + method?: string; + min?: number | string; + minLength?: number; + multiple?: boolean; + muted?: boolean; + name?: string; + nonce?: string; + noValidate?: boolean; + open?: boolean; + optimum?: number; + pattern?: string; + placeholder?: string; + playsInline?: boolean; + poster?: string; + preload?: string; + readOnly?: boolean; + rel?: string; + required?: boolean; + reversed?: boolean; + rows?: number; + rowSpan?: number; + sandbox?: string; + scope?: string; + scoped?: boolean; + scrolling?: string; + seamless?: boolean; + selected?: boolean; + shape?: string; + size?: number; + sizes?: string; + span?: number; + src?: string; + srcDoc?: string; + srcLang?: string; + srcSet?: string; + start?: number; + step?: number | string; + summary?: string; + target?: string; + type?: string; + useMap?: string; + value?: string | string[] | number; + width?: number | string; + wmode?: string; + wrap?: string; + } + + interface AnchorHTMLAttributes extends HTMLAttributes { + download?: any; + href?: string; + hrefLang?: string; + media?: string; + rel?: string; + target?: string; + } + + // tslint:disable-next-line:no-empty-interface + interface AudioHTMLAttributes extends MediaHTMLAttributes {} + + interface AreaHTMLAttributes extends HTMLAttributes { + alt?: string; + coords?: string; + download?: any; + href?: string; + hrefLang?: string; + media?: string; + rel?: string; + shape?: string; + target?: string; + } + + interface BaseHTMLAttributes extends HTMLAttributes { + href?: string; + target?: string; + } + + interface BlockquoteHTMLAttributes extends HTMLAttributes { + cite?: string; + } + + interface ButtonHTMLAttributes extends HTMLAttributes { + autoFocus?: boolean; + disabled?: boolean; + form?: string; + formAction?: string; + formEncType?: string; + formMethod?: string; + formNoValidate?: boolean; + formTarget?: string; + name?: string; + type?: string; + value?: string | string[] | number; + } + + interface CanvasHTMLAttributes extends HTMLAttributes { + height?: number | string; + width?: number | string; + } + + interface ColHTMLAttributes extends HTMLAttributes { + span?: number; + } + + interface ColgroupHTMLAttributes extends HTMLAttributes { + span?: number; + } + + interface DetailsHTMLAttributes extends HTMLAttributes { + open?: boolean; + } + + interface DelHTMLAttributes extends HTMLAttributes { + cite?: string; + dateTime?: string; + } + + interface EmbedHTMLAttributes extends HTMLAttributes { + height?: number | string; + src?: string; + type?: string; + width?: number | string; + } + + interface FieldsetHTMLAttributes extends HTMLAttributes { + disabled?: boolean; + form?: string; + name?: string; + } + + interface FormHTMLAttributes extends HTMLAttributes { + acceptCharset?: string; + action?: string; + autoComplete?: string; + encType?: string; + method?: string; + name?: string; + noValidate?: boolean; + target?: string; + } + + interface HtmlHTMLAttributes extends HTMLAttributes { + manifest?: string; + } + + interface IframeHTMLAttributes extends HTMLAttributes { + allowFullScreen?: boolean; + allowTransparency?: boolean; + frameBorder?: number | string; + height?: number | string; + marginHeight?: number; + marginWidth?: number; + name?: string; + sandbox?: string; + scrolling?: string; + seamless?: boolean; + src?: string; + srcDoc?: string; + width?: number | string; + } + + interface ImgHTMLAttributes extends HTMLAttributes { + alt?: string; + height?: number | string; + sizes?: string; + src?: string; + srcSet?: string; + useMap?: string; + width?: number | string; + } + + interface InsHTMLAttributes extends HTMLAttributes { + cite?: string; + dateTime?: string; + } + + interface InputHTMLAttributes extends HTMLAttributes { + accept?: string; + alt?: string; + autoComplete?: string; + autoFocus?: boolean; + capture?: boolean; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute + checked?: boolean; + crossOrigin?: string; + disabled?: boolean; + form?: string; + formAction?: string; + formEncType?: string; + formMethod?: string; + formNoValidate?: boolean; + formTarget?: string; + height?: number | string; + list?: string; + max?: number | string; + maxLength?: number; + min?: number | string; + minLength?: number; + multiple?: boolean; + name?: string; + pattern?: string; + placeholder?: string; + readOnly?: boolean; + required?: boolean; + size?: number; + src?: string; + step?: number | string; + type?: string; + value?: string | string[] | number; + width?: number | string; + onChange?: ChangeEventHandler; } + interface KeygenHTMLAttributes extends HTMLAttributes { + autoFocus?: boolean; + challenge?: string; + disabled?: boolean; + form?: string; + keyType?: string; + keyParams?: string; + name?: string; + } + + interface LabelHTMLAttributes extends HTMLAttributes { + form?: string; + htmlFor?: string; + } + + interface LiHTMLAttributes extends HTMLAttributes { + value?: string | string[] | number; + } + + interface LinkHTMLAttributes extends HTMLAttributes { + href?: string; + hrefLang?: string; + integrity?: string; + media?: string; + rel?: string; + sizes?: string; + type?: string; + } + + interface MapHTMLAttributes extends HTMLAttributes { + name?: string; + } + + interface MenuHTMLAttributes extends HTMLAttributes { + type?: string; + } + + interface MediaHTMLAttributes extends HTMLAttributes { + autoPlay?: boolean; + controls?: boolean; + crossOrigin?: string; + loop?: boolean; + mediaGroup?: string; + muted?: boolean; + preload?: string; + src?: string; + } + + interface MetaHTMLAttributes extends HTMLAttributes { + charSet?: string; + content?: string; + httpEquiv?: string; + name?: string; + } + + interface MeterHTMLAttributes extends HTMLAttributes { + form?: string; + high?: number; + low?: number; + max?: number | string; + min?: number | string; + optimum?: number; + value?: string | string[] | number; + } + + interface QuoteHTMLAttributes extends HTMLAttributes { + cite?: string; + } + + interface ObjectHTMLAttributes extends HTMLAttributes { + classID?: string; + data?: string; + form?: string; + height?: number | string; + name?: string; + type?: string; + useMap?: string; + width?: number | string; + wmode?: string; + } + + interface OlHTMLAttributes extends HTMLAttributes { + reversed?: boolean; + start?: number; + } + + interface OptgroupHTMLAttributes extends HTMLAttributes { + disabled?: boolean; + label?: string; + } + + interface OptionHTMLAttributes extends HTMLAttributes { + disabled?: boolean; + label?: string; + selected?: boolean; + value?: string | string[] | number; + } + + interface OutputHTMLAttributes extends HTMLAttributes { + form?: string; + htmlFor?: string; + name?: string; + } + + interface ParamHTMLAttributes extends HTMLAttributes { + name?: string; + value?: string | string[] | number; + } + + interface ProgressHTMLAttributes extends HTMLAttributes { + max?: number | string; + value?: string | string[] | number; + } + + interface ScriptHTMLAttributes extends HTMLAttributes { + async?: boolean; + charSet?: string; + crossOrigin?: string; + defer?: boolean; + integrity?: string; + nonce?: string; + src?: string; + type?: string; + } + + interface SelectHTMLAttributes extends HTMLAttributes { + autoFocus?: boolean; + disabled?: boolean; + form?: string; + multiple?: boolean; + name?: string; + required?: boolean; + size?: number; + + onChange?: ChangeEventHandler; + } + + interface SourceHTMLAttributes extends HTMLAttributes { + media?: string; + sizes?: string; + src?: string; + srcSet?: string; + type?: string; + } + + interface StyleHTMLAttributes extends HTMLAttributes { + media?: string; + nonce?: string; + scoped?: boolean; + type?: string; + } + + interface TableHTMLAttributes extends HTMLAttributes { + cellPadding?: number | string; + cellSpacing?: number | string; + summary?: string; + } + + interface TextareaHTMLAttributes extends HTMLAttributes { + autoFocus?: boolean; + cols?: number; + disabled?: boolean; + form?: string; + maxLength?: number; + minLength?: number; + name?: string; + placeholder?: string; + readOnly?: boolean; + required?: boolean; + rows?: number; + value?: string | string[] | number; + wrap?: string; + + onChange?: ChangeEventHandler; + } + + interface TdHTMLAttributes extends HTMLAttributes { + colSpan?: number; + headers?: string; + rowSpan?: number; + } + + interface ThHTMLAttributes extends HTMLAttributes { + colSpan?: number; + headers?: string; + rowSpan?: number; + scope?: string; + } + + interface TimeHTMLAttributes extends HTMLAttributes { + dateTime?: string; + } + + interface TrackHTMLAttributes extends HTMLAttributes { + default?: boolean; + kind?: string; + label?: string; + src?: string; + srcLang?: string; + } + + interface VideoHTMLAttributes extends MediaHTMLAttributes { + height?: number | string; + playsInline?: boolean; + poster?: string; + width?: number | string; + } + // this list is "complete" in that it contains every SVG attribute // that React supports, but the types can be improved. // Full list here: https://facebook.github.io/react/docs/dom-elements.html @@ -2758,119 +3142,119 @@ declare namespace React { // ---------------------------------------------------------------------- interface ReactHTML { - a: HTMLFactory; - abbr: HTMLFactory; - address: HTMLFactory; - area: HTMLFactory; - article: HTMLFactory; - aside: HTMLFactory; - audio: HTMLFactory; - b: HTMLFactory; - base: HTMLFactory; - bdi: HTMLFactory; - bdo: HTMLFactory; - big: HTMLFactory; - blockquote: HTMLFactory; - body: HTMLFactory; - br: HTMLFactory; - button: HTMLFactory; - canvas: HTMLFactory; - caption: HTMLFactory; - cite: HTMLFactory; - code: HTMLFactory; - col: HTMLFactory; - colgroup: HTMLFactory; - data: HTMLFactory; - datalist: HTMLFactory; - dd: HTMLFactory; - del: HTMLFactory; - details: HTMLFactory; - dfn: HTMLFactory; - dialog: HTMLFactory; - div: HTMLFactory; - dl: HTMLFactory; - dt: HTMLFactory; - em: HTMLFactory; - embed: HTMLFactory; - fieldset: HTMLFactory; - figcaption: HTMLFactory; - figure: HTMLFactory; - footer: HTMLFactory; - form: HTMLFactory; - h1: HTMLFactory; - h2: HTMLFactory; - h3: HTMLFactory; - h4: HTMLFactory; - h5: HTMLFactory; - h6: HTMLFactory; - head: HTMLFactory; - header: HTMLFactory; - hgroup: HTMLFactory; - hr: HTMLFactory; - html: HTMLFactory; - i: HTMLFactory; - iframe: HTMLFactory; - img: HTMLFactory; - input: ChangeTargetHTMLFactory; - ins: HTMLFactory; - kbd: HTMLFactory; - keygen: HTMLFactory; - label: HTMLFactory; - legend: HTMLFactory; - li: HTMLFactory; - link: HTMLFactory; - main: HTMLFactory; - map: HTMLFactory; - mark: HTMLFactory; - menu: HTMLFactory; - menuitem: HTMLFactory; - meta: HTMLFactory; - meter: HTMLFactory; - nav: HTMLFactory; - noscript: HTMLFactory; - object: HTMLFactory; - ol: HTMLFactory; - optgroup: HTMLFactory; - option: HTMLFactory; - output: HTMLFactory; - p: HTMLFactory; - param: HTMLFactory; - picture: HTMLFactory; - pre: HTMLFactory; - progress: HTMLFactory; - q: HTMLFactory; - rp: HTMLFactory; - rt: HTMLFactory; - ruby: HTMLFactory; - s: HTMLFactory; - samp: HTMLFactory; - script: HTMLFactory; - section: HTMLFactory; - select: ChangeTargetHTMLFactory; - small: HTMLFactory; - source: HTMLFactory; - span: HTMLFactory; - strong: HTMLFactory; - style: HTMLFactory; - sub: HTMLFactory; - summary: HTMLFactory; - sup: HTMLFactory; - table: HTMLFactory; - tbody: HTMLFactory; - td: HTMLFactory; - textarea: ChangeTargetHTMLFactory; - tfoot: HTMLFactory; - th: HTMLFactory; - thead: HTMLFactory; - time: HTMLFactory; - title: HTMLFactory; - tr: HTMLFactory; - track: HTMLFactory; - u: HTMLFactory; - ul: HTMLFactory; - "var": HTMLFactory; - video: HTMLFactory; - wbr: HTMLFactory; + a: DetailedHTMLFactory, HTMLAnchorElement>; + abbr: DetailedHTMLFactory, HTMLElement>; + address: DetailedHTMLFactory, HTMLElement>; + area: DetailedHTMLFactory, HTMLAreaElement>; + article: DetailedHTMLFactory, HTMLElement>; + aside: DetailedHTMLFactory, HTMLElement>; + audio: DetailedHTMLFactory, HTMLAudioElement>; + b: DetailedHTMLFactory, HTMLElement>; + base: DetailedHTMLFactory, HTMLBaseElement>; + bdi: DetailedHTMLFactory, HTMLElement>; + bdo: DetailedHTMLFactory, HTMLElement>; + big: DetailedHTMLFactory, HTMLElement>; + blockquote: DetailedHTMLFactory, HTMLElement>; + body: DetailedHTMLFactory, HTMLBodyElement>; + br: DetailedHTMLFactory, HTMLBRElement>; + button: DetailedHTMLFactory, HTMLButtonElement>; + canvas: DetailedHTMLFactory, HTMLCanvasElement>; + caption: DetailedHTMLFactory, HTMLElement>; + cite: DetailedHTMLFactory, HTMLElement>; + code: DetailedHTMLFactory, HTMLElement>; + col: DetailedHTMLFactory, HTMLTableColElement>; + colgroup: DetailedHTMLFactory, HTMLTableColElement>; + data: DetailedHTMLFactory, HTMLElement>; + datalist: DetailedHTMLFactory, HTMLDataListElement>; + dd: DetailedHTMLFactory, HTMLElement>; + del: DetailedHTMLFactory, HTMLElement>; + details: DetailedHTMLFactory, HTMLElement>; + dfn: DetailedHTMLFactory, HTMLElement>; + dialog: DetailedHTMLFactory, HTMLElement>; + div: DetailedHTMLFactory, HTMLDivElement>; + dl: DetailedHTMLFactory, HTMLDListElement>; + dt: DetailedHTMLFactory, HTMLElement>; + em: DetailedHTMLFactory, HTMLElement>; + embed: DetailedHTMLFactory, HTMLEmbedElement>; + fieldset: DetailedHTMLFactory, HTMLFieldSetElement>; + figcaption: DetailedHTMLFactory, HTMLElement>; + figure: DetailedHTMLFactory, HTMLElement>; + footer: DetailedHTMLFactory, HTMLElement>; + form: DetailedHTMLFactory, HTMLFormElement>; + h1: DetailedHTMLFactory, HTMLHeadingElement>; + h2: DetailedHTMLFactory, HTMLHeadingElement>; + h3: DetailedHTMLFactory, HTMLHeadingElement>; + h4: DetailedHTMLFactory, HTMLHeadingElement>; + h5: DetailedHTMLFactory, HTMLHeadingElement>; + h6: DetailedHTMLFactory, HTMLHeadingElement>; + head: DetailedHTMLFactory, HTMLHeadElement>; + header: DetailedHTMLFactory, HTMLElement>; + hgroup: DetailedHTMLFactory, HTMLElement>; + hr: DetailedHTMLFactory, HTMLHRElement>; + html: DetailedHTMLFactory, HTMLHtmlElement>; + i: DetailedHTMLFactory, HTMLElement>; + iframe: DetailedHTMLFactory, HTMLIFrameElement>; + img: DetailedHTMLFactory, HTMLImageElement>; + input: DetailedHTMLFactory, HTMLInputElement>; + ins: DetailedHTMLFactory, HTMLModElement>; + kbd: DetailedHTMLFactory, HTMLElement>; + keygen: DetailedHTMLFactory, HTMLElement>; + label: DetailedHTMLFactory, HTMLLabelElement>; + legend: DetailedHTMLFactory, HTMLLegendElement>; + li: DetailedHTMLFactory, HTMLLIElement>; + link: DetailedHTMLFactory, HTMLLinkElement>; + main: DetailedHTMLFactory, HTMLElement>; + map: DetailedHTMLFactory, HTMLMapElement>; + mark: DetailedHTMLFactory, HTMLElement>; + menu: DetailedHTMLFactory, HTMLElement>; + menuitem: DetailedHTMLFactory, HTMLElement>; + meta: DetailedHTMLFactory, HTMLMetaElement>; + meter: DetailedHTMLFactory, HTMLElement>; + nav: DetailedHTMLFactory, HTMLElement>; + noscript: DetailedHTMLFactory, HTMLElement>; + object: DetailedHTMLFactory, HTMLObjectElement>; + ol: DetailedHTMLFactory, HTMLOListElement>; + optgroup: DetailedHTMLFactory, HTMLOptGroupElement>; + option: DetailedHTMLFactory, HTMLOptionElement>; + output: DetailedHTMLFactory, HTMLElement>; + p: DetailedHTMLFactory, HTMLParagraphElement>; + param: DetailedHTMLFactory, HTMLParamElement>; + picture: DetailedHTMLFactory, HTMLElement>; + pre: DetailedHTMLFactory, HTMLPreElement>; + progress: DetailedHTMLFactory, HTMLProgressElement>; + q: DetailedHTMLFactory, HTMLQuoteElement>; + rp: DetailedHTMLFactory, HTMLElement>; + rt: DetailedHTMLFactory, HTMLElement>; + ruby: DetailedHTMLFactory, HTMLElement>; + s: DetailedHTMLFactory, HTMLElement>; + samp: DetailedHTMLFactory, HTMLElement>; + script: DetailedHTMLFactory, HTMLScriptElement>; + section: DetailedHTMLFactory, HTMLElement>; + select: DetailedHTMLFactory, HTMLSelectElement>; + small: DetailedHTMLFactory, HTMLElement>; + source: DetailedHTMLFactory, HTMLSourceElement>; + span: DetailedHTMLFactory, HTMLSpanElement>; + strong: DetailedHTMLFactory, HTMLElement>; + style: DetailedHTMLFactory, HTMLStyleElement>; + sub: DetailedHTMLFactory, HTMLElement>; + summary: DetailedHTMLFactory, HTMLElement>; + sup: DetailedHTMLFactory, HTMLElement>; + table: DetailedHTMLFactory, HTMLTableElement>; + tbody: DetailedHTMLFactory, HTMLTableSectionElement>; + td: DetailedHTMLFactory, HTMLTableDataCellElement>; + textarea: DetailedHTMLFactory, HTMLTextAreaElement>; + tfoot: DetailedHTMLFactory, HTMLTableSectionElement>; + th: DetailedHTMLFactory, HTMLTableHeaderCellElement>; + thead: DetailedHTMLFactory, HTMLTableSectionElement>; + time: DetailedHTMLFactory, HTMLElement>; + title: DetailedHTMLFactory, HTMLTitleElement>; + tr: DetailedHTMLFactory, HTMLTableRowElement>; + track: DetailedHTMLFactory, HTMLTrackElement>; + u: DetailedHTMLFactory, HTMLElement>; + ul: DetailedHTMLFactory, HTMLUListElement>; + "var": DetailedHTMLFactory, HTMLElement>; + video: DetailedHTMLFactory, HTMLVideoElement>; + wbr: DetailedHTMLFactory, HTMLElement>; } interface ReactSVG { @@ -2986,120 +3370,120 @@ declare global { interface IntrinsicElements { // HTML - a: React.HTMLProps; - abbr: React.HTMLProps; - address: React.HTMLProps; - area: React.HTMLProps; - article: React.HTMLProps; - aside: React.HTMLProps; - audio: React.HTMLProps; - b: React.HTMLProps; - base: React.HTMLProps; - bdi: React.HTMLProps; - bdo: React.HTMLProps; - big: React.HTMLProps; - blockquote: React.HTMLProps; - body: React.HTMLProps; - br: React.HTMLProps; - button: React.HTMLProps; - canvas: React.HTMLProps; - caption: React.HTMLProps; - cite: React.HTMLProps; - code: React.HTMLProps; - col: React.HTMLProps; - colgroup: React.HTMLProps; - data: React.HTMLProps; - datalist: React.HTMLProps; - dd: React.HTMLProps; - del: React.HTMLProps; - details: React.HTMLProps; - dfn: React.HTMLProps; - dialog: React.HTMLProps; - div: React.HTMLProps; - dl: React.HTMLProps; - dt: React.HTMLProps; - em: React.HTMLProps; - embed: React.HTMLProps; - fieldset: React.HTMLProps; - figcaption: React.HTMLProps; - figure: React.HTMLProps; - footer: React.HTMLProps; - form: React.HTMLProps; - h1: React.HTMLProps; - h2: React.HTMLProps; - h3: React.HTMLProps; - h4: React.HTMLProps; - h5: React.HTMLProps; - h6: React.HTMLProps; - head: React.HTMLProps; - header: React.HTMLProps; - hgroup: React.HTMLProps; - hr: React.HTMLProps; - html: React.HTMLProps; - i: React.HTMLProps; - iframe: React.HTMLProps; - img: React.HTMLProps; - input: React.ChangeTargetHTMLProps; - ins: React.HTMLProps; - kbd: React.HTMLProps; - keygen: React.HTMLProps; - label: React.HTMLProps; - legend: React.HTMLProps; - li: React.HTMLProps; - link: React.HTMLProps; - main: React.HTMLProps; - map: React.HTMLProps; - mark: React.HTMLProps; - menu: React.HTMLProps; - menuitem: React.HTMLProps; - meta: React.HTMLProps; - meter: React.HTMLProps; - nav: React.HTMLProps; - noindex: React.HTMLProps; - noscript: React.HTMLProps; - object: React.HTMLProps; - ol: React.HTMLProps; - optgroup: React.HTMLProps; - option: React.HTMLProps; - output: React.HTMLProps; - p: React.HTMLProps; - param: React.HTMLProps; - picture: React.HTMLProps; - pre: React.HTMLProps; - progress: React.HTMLProps; - q: React.HTMLProps; - rp: React.HTMLProps; - rt: React.HTMLProps; - ruby: React.HTMLProps; - s: React.HTMLProps; - samp: React.HTMLProps; - script: React.HTMLProps; - section: React.HTMLProps; - select: React.ChangeTargetHTMLProps; - small: React.HTMLProps; - source: React.HTMLProps; - span: React.HTMLProps; - strong: React.HTMLProps; - style: React.HTMLProps; - sub: React.HTMLProps; - summary: React.HTMLProps; - sup: React.HTMLProps; - table: React.HTMLProps; - tbody: React.HTMLProps; - td: React.HTMLProps; - textarea: React.ChangeTargetHTMLProps; - tfoot: React.HTMLProps; - th: React.HTMLProps; - thead: React.HTMLProps; - time: React.HTMLProps; - title: React.HTMLProps; - tr: React.HTMLProps; - track: React.HTMLProps; - u: React.HTMLProps; - ul: React.HTMLProps; - "var": React.HTMLProps; - video: React.HTMLProps; - wbr: React.HTMLProps; + a: React.DetailedHTMLProps, HTMLAnchorElement>; + abbr: React.DetailedHTMLProps, HTMLElement>; + address: React.DetailedHTMLProps, HTMLElement>; + area: React.DetailedHTMLProps, HTMLAreaElement>; + article: React.DetailedHTMLProps, HTMLElement>; + aside: React.DetailedHTMLProps, HTMLElement>; + audio: React.DetailedHTMLProps, HTMLAudioElement>; + b: React.DetailedHTMLProps, HTMLElement>; + base: React.DetailedHTMLProps, HTMLBaseElement>; + bdi: React.DetailedHTMLProps, HTMLElement>; + bdo: React.DetailedHTMLProps, HTMLElement>; + big: React.DetailedHTMLProps, HTMLElement>; + blockquote: React.DetailedHTMLProps, HTMLElement>; + body: React.DetailedHTMLProps, HTMLBodyElement>; + br: React.DetailedHTMLProps, HTMLBRElement>; + button: React.DetailedHTMLProps, HTMLButtonElement>; + canvas: React.DetailedHTMLProps, HTMLCanvasElement>; + caption: React.DetailedHTMLProps, HTMLElement>; + cite: React.DetailedHTMLProps, HTMLElement>; + code: React.DetailedHTMLProps, HTMLElement>; + col: React.DetailedHTMLProps, HTMLTableColElement>; + colgroup: React.DetailedHTMLProps, HTMLTableColElement>; + data: React.DetailedHTMLProps, HTMLElement>; + datalist: React.DetailedHTMLProps, HTMLDataListElement>; + dd: React.DetailedHTMLProps, HTMLElement>; + del: React.DetailedHTMLProps, HTMLElement>; + details: React.DetailedHTMLProps, HTMLElement>; + dfn: React.DetailedHTMLProps, HTMLElement>; + dialog: React.DetailedHTMLProps, HTMLElement>; + div: React.DetailedHTMLProps, HTMLDivElement>; + dl: React.DetailedHTMLProps, HTMLDListElement>; + dt: React.DetailedHTMLProps, HTMLElement>; + em: React.DetailedHTMLProps, HTMLElement>; + embed: React.DetailedHTMLProps, HTMLEmbedElement>; + fieldset: React.DetailedHTMLProps, HTMLFieldSetElement>; + figcaption: React.DetailedHTMLProps, HTMLElement>; + figure: React.DetailedHTMLProps, HTMLElement>; + footer: React.DetailedHTMLProps, HTMLElement>; + form: React.DetailedHTMLProps, HTMLFormElement>; + h1: React.DetailedHTMLProps, HTMLHeadingElement>; + h2: React.DetailedHTMLProps, HTMLHeadingElement>; + h3: React.DetailedHTMLProps, HTMLHeadingElement>; + h4: React.DetailedHTMLProps, HTMLHeadingElement>; + h5: React.DetailedHTMLProps, HTMLHeadingElement>; + h6: React.DetailedHTMLProps, HTMLHeadingElement>; + head: React.DetailedHTMLProps, HTMLHeadElement>; + header: React.DetailedHTMLProps, HTMLElement>; + hgroup: React.DetailedHTMLProps, HTMLElement>; + hr: React.DetailedHTMLProps, HTMLHRElement>; + html: React.DetailedHTMLProps, HTMLHtmlElement>; + i: React.DetailedHTMLProps, HTMLElement>; + iframe: React.DetailedHTMLProps, HTMLIFrameElement>; + img: React.DetailedHTMLProps, HTMLImageElement>; + input: React.DetailedHTMLProps, HTMLInputElement>; + ins: React.DetailedHTMLProps, HTMLModElement>; + kbd: React.DetailedHTMLProps, HTMLElement>; + keygen: React.DetailedHTMLProps, HTMLElement>; + label: React.DetailedHTMLProps, HTMLLabelElement>; + legend: React.DetailedHTMLProps, HTMLLegendElement>; + li: React.DetailedHTMLProps, HTMLLIElement>; + link: React.DetailedHTMLProps, HTMLLinkElement>; + main: React.DetailedHTMLProps, HTMLElement>; + map: React.DetailedHTMLProps, HTMLMapElement>; + mark: React.DetailedHTMLProps, HTMLElement>; + menu: React.DetailedHTMLProps, HTMLElement>; + menuitem: React.DetailedHTMLProps, HTMLElement>; + meta: React.DetailedHTMLProps, HTMLMetaElement>; + meter: React.DetailedHTMLProps, HTMLElement>; + nav: React.DetailedHTMLProps, HTMLElement>; + noindex: React.DetailedHTMLProps, HTMLElement>; + noscript: React.DetailedHTMLProps, HTMLElement>; + object: React.DetailedHTMLProps, HTMLObjectElement>; + ol: React.DetailedHTMLProps, HTMLOListElement>; + optgroup: React.DetailedHTMLProps, HTMLOptGroupElement>; + option: React.DetailedHTMLProps, HTMLOptionElement>; + output: React.DetailedHTMLProps, HTMLElement>; + p: React.DetailedHTMLProps, HTMLParagraphElement>; + param: React.DetailedHTMLProps, HTMLParamElement>; + picture: React.DetailedHTMLProps, HTMLElement>; + pre: React.DetailedHTMLProps, HTMLPreElement>; + progress: React.DetailedHTMLProps, HTMLProgressElement>; + q: React.DetailedHTMLProps, HTMLQuoteElement>; + rp: React.DetailedHTMLProps, HTMLElement>; + rt: React.DetailedHTMLProps, HTMLElement>; + ruby: React.DetailedHTMLProps, HTMLElement>; + s: React.DetailedHTMLProps, HTMLElement>; + samp: React.DetailedHTMLProps, HTMLElement>; + script: React.DetailedHTMLProps, HTMLScriptElement>; + section: React.DetailedHTMLProps, HTMLElement>; + select: React.DetailedHTMLProps, HTMLSelectElement>; + small: React.DetailedHTMLProps, HTMLElement>; + source: React.DetailedHTMLProps, HTMLSourceElement>; + span: React.DetailedHTMLProps, HTMLSpanElement>; + strong: React.DetailedHTMLProps, HTMLElement>; + style: React.DetailedHTMLProps, HTMLStyleElement>; + sub: React.DetailedHTMLProps, HTMLElement>; + summary: React.DetailedHTMLProps, HTMLElement>; + sup: React.DetailedHTMLProps, HTMLElement>; + table: React.DetailedHTMLProps, HTMLTableElement>; + tbody: React.DetailedHTMLProps, HTMLTableSectionElement>; + td: React.DetailedHTMLProps, HTMLTableDataCellElement>; + textarea: React.DetailedHTMLProps, HTMLTextAreaElement>; + tfoot: React.DetailedHTMLProps, HTMLTableSectionElement>; + th: React.DetailedHTMLProps, HTMLTableHeaderCellElement>; + thead: React.DetailedHTMLProps, HTMLTableSectionElement>; + time: React.DetailedHTMLProps, HTMLElement>; + title: React.DetailedHTMLProps, HTMLTitleElement>; + tr: React.DetailedHTMLProps, HTMLTableRowElement>; + track: React.DetailedHTMLProps, HTMLTrackElement>; + u: React.DetailedHTMLProps, HTMLElement>; + ul: React.DetailedHTMLProps, HTMLUListElement>; + "var": React.DetailedHTMLProps, HTMLElement>; + video: React.DetailedHTMLProps, HTMLVideoElement>; + wbr: React.DetailedHTMLProps, HTMLElement>; // SVG svg: React.SVGProps; diff --git a/types/reactstrap/lib/Input.d.ts b/types/reactstrap/lib/Input.d.ts index 816add1137..c9d7a1329d 100644 --- a/types/reactstrap/lib/Input.d.ts +++ b/types/reactstrap/lib/Input.d.ts @@ -27,7 +27,7 @@ type InputType = // Intermediate interface to "redefine" the type of size to string // size:number => size:any => size:string -interface Intermediate extends React.ChangeTargetHTMLProps { +interface Intermediate extends React.InputHTMLAttributes { size?: any; } diff --git a/types/reactstrap/lib/Label.d.ts b/types/reactstrap/lib/Label.d.ts index 04cf76e3a0..383378dc4e 100644 --- a/types/reactstrap/lib/Label.d.ts +++ b/types/reactstrap/lib/Label.d.ts @@ -1,6 +1,6 @@ import { ColumnProps } from './Col'; -interface Intermediate extends React.ChangeTargetHTMLProps { +interface Intermediate extends React.LabelHTMLAttributes { size?: any; } From de518ab03003212500979f73833fb3ddaa128445 Mon Sep 17 00:00:00 2001 From: Kohki Makimoto Date: Tue, 11 Jul 2017 13:55:01 +0900 Subject: [PATCH 0323/1618] [react-native] Add type `renderSectionFooter` for SectionList --- types/react-native/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index dfdfde82c6..5dedae5911 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3715,6 +3715,11 @@ export interface SectionListProperties extends ScrollViewProperties { */ renderSectionHeader?: (info: {section: SectionListData}) => React.ReactElement | null + /** + * Rendered at the bottom of each section. + */ + renderSectionFooter?: (info: {section: SectionListData}) => React.ReactElement | null + /** * An array of objects with data for each section. */ From ec4f2fa49808d46ee780ab366ad0e5539ff90420 Mon Sep 17 00:00:00 2001 From: Swiod Date: Tue, 11 Jul 2017 10:10:57 +0200 Subject: [PATCH 0324/1618] Missing function ol.style.Style#clone --- types/openlayers/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 356ba72429..bfd673a2e1 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -10582,6 +10582,13 @@ declare module ol { */ constructor(opt_options?: olx.style.StyleOptions); + /** + * Clones the style. + * @return {ol.style.Style} The cloned style. + * @api + */ + clone(): ol.style.Style; + /** * Get the geometry to be rendered. * @return {string|ol.geom.Geometry|ol.StyleGeometryFunction} From 58255fbdac01a89af959547093e6db90423e2742 Mon Sep 17 00:00:00 2001 From: newraina Date: Tue, 11 Jul 2017 16:42:26 +0800 Subject: [PATCH 0325/1618] remove consecutive blank lines --- types/fetch.io/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/fetch.io/index.d.ts b/types/fetch.io/index.d.ts index 4489156cfe..29d5d2dfab 100644 --- a/types/fetch.io/index.d.ts +++ b/types/fetch.io/index.d.ts @@ -63,7 +63,6 @@ export class Request { */ put: (url: TUrl) => this; - /** * HTTP patch method */ From d0c01b30a6beea2f253f0cac2f974bf95ed89f33 Mon Sep 17 00:00:00 2001 From: Jarrad Whitaker Date: Thu, 6 Jul 2017 13:05:12 +1000 Subject: [PATCH 0326/1618] loosen assert.fail --- types/node/index.d.ts | 3 ++- types/node/node-tests.ts | 4 ++++ types/node/v4/index.d.ts | 2 +- types/node/v6/index.d.ts | 2 +- types/node/v6/node-tests.ts | 2 ++ types/node/v7/index.d.ts | 2 +- types/node/v7/node-tests.ts | 2 ++ 7 files changed, 13 insertions(+), 4 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 7551a5190b..db864d60c2 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -4013,7 +4013,8 @@ declare module "assert" { }); } - export function fail(actual: any, expected: any, message: string, operator: string): void; + export function fail(message: string): void; + export function fail(actual: any, expected: any, message?: string, operator?: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index fef0cd9862..6530ccd381 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -63,6 +63,10 @@ namespace assert_tests { assert.equal(3, "3", "uses == comparator"); + assert.fail('stuff broke'); + + assert.fail('actual', 'expected', 'message'); + assert.fail(1, 2, undefined, '>'); assert.ifError(0); diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index a79f49e35d..84e531f004 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -2281,7 +2281,7 @@ declare module "assert" { operator?: string; stackStartFunction?: Function}); } - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function fail(actual: any, expected: any, message?: string, operator?: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 0b87d6f2f6..9732f6bf2b 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -3693,7 +3693,7 @@ declare module "assert" { }); } - export function fail(actual: any, expected: any, message: string, operator: string): void; + export function fail(actual: any, expected: any, message?: string, operator?: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 191f1128c2..b1aee63753 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -61,6 +61,8 @@ namespace assert_tests { assert.equal(3, "3", "uses == comparator"); + assert.fail("actual", "expected", "message"); + assert.fail(1, 2, undefined, '>'); assert.ifError(0); diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 59b3d680c7..0e9c7288f0 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -3844,7 +3844,7 @@ declare module "assert" { }); } - export function fail(actual: any, expected: any, message: string, operator: string): void; + export function fail(actual: any, expected: any, message?: string, operator?: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 4a2f53ab67..0fad40256a 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -62,6 +62,8 @@ namespace assert_tests { assert.equal(3, "3", "uses == comparator"); + assert.fail("actual", "expected", "message"); + assert.fail(1, 2, undefined, '>'); assert.ifError(0); From c238232c3e0057da97e5136f03db88b0bd132c39 Mon Sep 17 00:00:00 2001 From: Jarrad Whitaker Date: Tue, 11 Jul 2017 18:45:37 +1000 Subject: [PATCH 0327/1618] change throws and doesNotThrow to use overload syntax --- types/node/index.d.ts | 21 +++++++++------------ types/node/v4/index.d.ts | 21 +++++++++------------ types/node/v6/index.d.ts | 21 +++++++++------------ types/node/v7/index.d.ts | 21 +++++++++------------ 4 files changed, 36 insertions(+), 48 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index db864d60c2..b4e3fbbfbd 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -4024,19 +4024,16 @@ declare module "assert" { export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; + export function throws(block: Function, message?: string): void; + export function throws(block: Function, error: Function, message?: string): void; + export function throws(block: Function, error: RegExp, message?: string): void; + export function throws(block: Function, error: (err: any) => boolean, message?: string): void; + + export function doesNotThrow(block: Function, message?: string): void; + export function doesNotThrow(block: Function, error: Function, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp, message?: string): void; + export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 84e531f004..53441c22b4 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -2291,19 +2291,16 @@ declare module "assert" { export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; + export function throws(block: Function, message?: string): void; + export function throws(block: Function, error: Function, message?: string): void; + export function throws(block: Function, error: RegExp, message?: string): void; + export function throws(block: Function, error: (err: any) => boolean, message?: string): void; + + export function doesNotThrow(block: Function, message?: string): void; + export function doesNotThrow(block: Function, error: Function, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp, message?: string): void; + export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 9732f6bf2b..ac75d338b9 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -3703,19 +3703,16 @@ declare module "assert" { export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; + export function throws(block: Function, message?: string): void; + export function throws(block: Function, error: Function, message?: string): void; + export function throws(block: Function, error: RegExp, message?: string): void; + export function throws(block: Function, error: (err: any) => boolean, message?: string): void; + + export function doesNotThrow(block: Function, message?: string): void; + export function doesNotThrow(block: Function, error: Function, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp, message?: string): void; + export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 0e9c7288f0..2a5a6f1bbb 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -3854,19 +3854,16 @@ declare module "assert" { export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; + export function throws(block: Function, message?: string): void; + export function throws(block: Function, error: Function, message?: string): void; + export function throws(block: Function, error: RegExp, message?: string): void; + export function throws(block: Function, error: (err: any) => boolean, message?: string): void; + + export function doesNotThrow(block: Function, message?: string): void; + export function doesNotThrow(block: Function, error: Function, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp, message?: string): void; + export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; export function ifError(value: any): void; } From 99dee20f49bab5878ef91a69b34aa5a23d0cea97 Mon Sep 17 00:00:00 2001 From: Bastien Date: Tue, 11 Jul 2017 12:19:20 +0200 Subject: [PATCH 0328/1618] [spark-md5] Add types --- types/spark-md5/index.d.ts | 42 ++++++++++++++++++++++++++++++ types/spark-md5/spark-md5-tests.ts | 20 ++++++++++++++ types/spark-md5/tsconfig.json | 22 ++++++++++++++++ types/spark-md5/tslint.json | 1 + 4 files changed, 85 insertions(+) create mode 100644 types/spark-md5/index.d.ts create mode 100644 types/spark-md5/spark-md5-tests.ts create mode 100644 types/spark-md5/tsconfig.json create mode 100644 types/spark-md5/tslint.json diff --git a/types/spark-md5/index.d.ts b/types/spark-md5/index.d.ts new file mode 100644 index 0000000000..6f93e6a821 --- /dev/null +++ b/types/spark-md5/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for spark-md5 3.0 +// Project: https://github.com/satazor/js-spark-md5#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface State { + buff: Uint8Array; + length: number; + hash: number[]; +} + +interface IArrayBuffer extends ArrayBuffer {} + +declare class SparkMD5 { + constructor(); + append(str: string): SparkMD5; + appendBinary(contents: string): SparkMD5; + end (raw?: boolean): string; + reset (): SparkMD5; + getState(): State; + setState(state: State): State; + destroy(): void; + static hash(str: string, raw?: boolean): string + static hashBinary(content: string, raw?: boolean): string +} + +declare namespace SparkMD5 { + class ArrayBuffer { + constructor(); + append(str: string): ArrayBuffer; + end (raw?: boolean): string; + reset (): ArrayBuffer; + getState(): State; + setState(state: State): State; + destroy(): void; + static hash(arr: IArrayBuffer, raw?: boolean): string + } +} + +declare module "spark-md5" { + export = SparkMD5; +} diff --git a/types/spark-md5/spark-md5-tests.ts b/types/spark-md5/spark-md5-tests.ts new file mode 100644 index 0000000000..4b960eaa56 --- /dev/null +++ b/types/spark-md5/spark-md5-tests.ts @@ -0,0 +1,20 @@ +import * as SparkMD5 from "spark-md5"; + +SparkMD5.hash('Hi there'); +SparkMD5.hash('Hi there', true); +SparkMD5.hashBinary(""); + +var spark = new SparkMD5(); +spark.append('Hi'); +spark.append(' there'); +var hexHash = spark.end(); +var rawHash = spark.end(true); + +var sparkArr = new SparkMD5.ArrayBuffer(); +sparkArr.append('Hi'); +sparkArr.append(' there'); +var hexHash = sparkArr.end(); +var rawHash = sparkArr.end(true); + +const arr = new ArrayBuffer(8); +SparkMD5.ArrayBuffer.hash(arr); diff --git a/types/spark-md5/tsconfig.json b/types/spark-md5/tsconfig.json new file mode 100644 index 0000000000..7dabd9b1a8 --- /dev/null +++ b/types/spark-md5/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "spark-md5-tests.ts" + ] +} diff --git a/types/spark-md5/tslint.json b/types/spark-md5/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/spark-md5/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 0c8e9b5f96dc35a90d33e2737f3ff82be385f6c9 Mon Sep 17 00:00:00 2001 From: ikatyang Date: Tue, 11 Jul 2017 18:38:32 +0800 Subject: [PATCH 0329/1618] feat(make-dir): initial commit --- types/make-dir/index.d.ts | 38 ++++++++++++++++++++++++++++++++ types/make-dir/make-dir-tests.ts | 7 ++++++ types/make-dir/tsconfig.json | 22 ++++++++++++++++++ types/make-dir/tslint.json | 3 +++ 4 files changed, 70 insertions(+) create mode 100644 types/make-dir/index.d.ts create mode 100644 types/make-dir/make-dir-tests.ts create mode 100644 types/make-dir/tsconfig.json create mode 100644 types/make-dir/tslint.json diff --git a/types/make-dir/index.d.ts b/types/make-dir/index.d.ts new file mode 100644 index 0000000000..e23dfba939 --- /dev/null +++ b/types/make-dir/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for make-dir 1.0 +// Project: https://github.com/sindresorhus/make-dir +// Definitions by: Ika +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = makeDir; + +/** + * Returns a `Promise` for the path to the created directory. + * @param path Directory to create. + * @param options + */ +declare function makeDir(path: string, options?: makeDir.Options): Promise; + +declare namespace makeDir { + /** + * Returns the path to the created directory. + * @param path Directory to create. + * @param options + */ + function sync(path: string, options?: Options): string; + + interface Options { + /** + * Default: `0o777 & (~process.umask())` + * + * Directory [permissions](https://x-team.com/blog/file-system-permissions-umask-node-js/). + */ + mode?: number; + + /** + * Default: `require('fs')` + * + * Use a custom `fs` implementation. For example [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). + */ + fs?: any; + } +} diff --git a/types/make-dir/make-dir-tests.ts b/types/make-dir/make-dir-tests.ts new file mode 100644 index 0000000000..817d793b70 --- /dev/null +++ b/types/make-dir/make-dir-tests.ts @@ -0,0 +1,7 @@ +import makeDir = require('make-dir'); + +makeDir('path/to/somewhere').then(dirname => { + // do something +}); + +const dirname = makeDir.sync('path/to/somewhere'); diff --git a/types/make-dir/tsconfig.json b/types/make-dir/tsconfig.json new file mode 100644 index 0000000000..90686a9f48 --- /dev/null +++ b/types/make-dir/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "make-dir-tests.ts" + ] +} diff --git a/types/make-dir/tslint.json b/types/make-dir/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/make-dir/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 5a8b5047e3dcbd49e2dc2c44231c734737701f25 Mon Sep 17 00:00:00 2001 From: york yao Date: Tue, 11 Jul 2017 18:40:47 +0800 Subject: [PATCH 0330/1618] add types of gzip-size --- types/gzip-size/gzip-size-tests.ts | 7 +++++++ types/gzip-size/index.d.ts | 13 +++++++++++++ types/gzip-size/tsconfig.json | 22 ++++++++++++++++++++++ types/gzip-size/tslint.json | 3 +++ 4 files changed, 45 insertions(+) create mode 100644 types/gzip-size/gzip-size-tests.ts create mode 100644 types/gzip-size/index.d.ts create mode 100644 types/gzip-size/tsconfig.json create mode 100644 types/gzip-size/tslint.json diff --git a/types/gzip-size/gzip-size-tests.ts b/types/gzip-size/gzip-size-tests.ts new file mode 100644 index 0000000000..f07d99bd50 --- /dev/null +++ b/types/gzip-size/gzip-size-tests.ts @@ -0,0 +1,7 @@ +import gzipSize = require('gzip-size'); + +const string = 'Lorem ipsum dolor sit amet.'; + +console.log(string.length); + +console.log(gzipSize.sync(string)); diff --git a/types/gzip-size/index.d.ts b/types/gzip-size/index.d.ts new file mode 100644 index 0000000000..12b1899b54 --- /dev/null +++ b/types/gzip-size/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for gzip-size 3.0 +// Project: https://github.com/sindresorhus/gzip-size +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function gzipSize(input: string | Buffer, callback: (error: Error, size: number) => void): string; +export = gzipSize; +declare namespace gzipSize { + function sync(input: string | Buffer): number; + function stream(): NodeJS.ReadWriteStream; +} diff --git a/types/gzip-size/tsconfig.json b/types/gzip-size/tsconfig.json new file mode 100644 index 0000000000..dd3dbc82c7 --- /dev/null +++ b/types/gzip-size/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gzip-size-tests.ts" + ] +} \ No newline at end of file diff --git a/types/gzip-size/tslint.json b/types/gzip-size/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gzip-size/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From 8b6a36dbcf263965eff4828a5ed9cf10029e8268 Mon Sep 17 00:00:00 2001 From: Kyle Roach Date: Mon, 10 Jul 2017 09:47:19 -0400 Subject: [PATCH 0331/1618] [rn] Adds ImageBackground --- types/react-native/index.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 13d32d8321..fdc1bcc183 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native 0.44 +// Type definitions for react-native 0.46 // Project: https://github.com/facebook/react-native // Definitions by: Eloy Durán // Fedor Nezhivoi @@ -8588,6 +8588,9 @@ export type DrawerLayoutAndroid = DrawerLayoutAndroidStatic export var Image: ImageStatic export type Image = ImageStatic +export var ImageBackground: ImageStatic +export type ImageBackground = ImageStatic + export var ImagePickerIOS: ImagePickerIOSStatic export type ImagePickerIOS = ImagePickerIOSStatic From 4745f0a8508d1a4a4d19186d69535404ccc90d1d Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Tue, 11 Jul 2017 18:25:31 +1000 Subject: [PATCH 0332/1618] Update export --- types/react-infinite-scroller/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-infinite-scroller/index.d.ts b/types/react-infinite-scroller/index.d.ts index b833c48981..61376165b2 100644 --- a/types/react-infinite-scroller/index.d.ts +++ b/types/react-infinite-scroller/index.d.ts @@ -61,5 +61,5 @@ declare module 'react-infinite-scroller' { loader?: React.ReactElement; } - export default class InfiniteScroll extends React.Component { } + export = class InfiniteScroll extends React.Component { } } From 21f4820e6357a983030539eff7bda5a254540a77 Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Tue, 11 Jul 2017 18:27:52 +1000 Subject: [PATCH 0333/1618] Update react-infinite-scroller-tests.tsx --- types/react-infinite-scroller/react-infinite-scroller-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx index e3171fff46..c1b2d30920 100644 --- a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx +++ b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import InfiniteScroll from 'react-infinite-scroller'; +import * as InfiniteScroll from 'react-infinite-scroller'; class Test1 extends React.Component { public render() { From 61885be51ea65702399a4cfbdd1ab96e5553e0a5 Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Tue, 11 Jul 2017 18:28:56 +1000 Subject: [PATCH 0334/1618] Create tslint.json --- types/react-infinite-scroller/tslint.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 types/react-infinite-scroller/tslint.json diff --git a/types/react-infinite-scroller/tslint.json b/types/react-infinite-scroller/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-infinite-scroller/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2d97577f3d4b372ef462e5247832115f39390779 Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Tue, 11 Jul 2017 21:19:30 +1000 Subject: [PATCH 0335/1618] use namespace --- types/react-infinite-scroller/index.d.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/types/react-infinite-scroller/index.d.ts b/types/react-infinite-scroller/index.d.ts index 61376165b2..07c0bbc8b5 100644 --- a/types/react-infinite-scroller/index.d.ts +++ b/types/react-infinite-scroller/index.d.ts @@ -4,8 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -declare module 'react-infinite-scroller' { - import * as React from 'react'; +/// + +import * as React from "react"; + +declare namespace InfiniteScroll { /** * properties. @@ -61,5 +64,8 @@ declare module 'react-infinite-scroller' { loader?: React.ReactElement; } - export = class InfiniteScroll extends React.Component { } + class InfiniteScroll extends React.Component { } + } + +export = InfiniteScroll.InfiniteScroll; From 32cdd18aee89e60574526a78013d4524d3bb3f78 Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Tue, 11 Jul 2017 21:23:39 +1000 Subject: [PATCH 0336/1618] lints --- types/react-infinite-scroller/index.d.ts | 7 +------ .../react-infinite-scroller-tests.tsx | 6 +++--- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/types/react-infinite-scroller/index.d.ts b/types/react-infinite-scroller/index.d.ts index 07c0bbc8b5..7d748c90a0 100644 --- a/types/react-infinite-scroller/index.d.ts +++ b/types/react-infinite-scroller/index.d.ts @@ -1,15 +1,12 @@ -// Type definitions for react-infinite-scroller 1.0.12 +// Type definitions for react-infinite-scroller 1.0 // Project: https://github.com/CassetteRocks/react-infinite-scroller // Definitions by: Lauri Lavanti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - import * as React from "react"; declare namespace InfiniteScroll { - /** * properties. */ @@ -63,9 +60,7 @@ declare namespace InfiniteScroll { */ loader?: React.ReactElement; } - class InfiniteScroll extends React.Component { } - } export = InfiniteScroll.InfiniteScroll; diff --git a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx index c1b2d30920..48b5bc243c 100644 --- a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx +++ b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx @@ -1,8 +1,8 @@ import * as React from 'react'; -import * as InfiniteScroll from 'react-infinite-scroller'; +import InfiniteScroll = require('react-infinite-scroller'); class Test1 extends React.Component { - public render() { + render() { return ( {}} @@ -14,7 +14,7 @@ class Test1 extends React.Component { } class Test2 extends React.Component { - public render() { + render() { return ( {}} From 38717ff972c0e0e730a369761d3af4dc061fa7bd Mon Sep 17 00:00:00 2001 From: Stan Goldmann Date: Tue, 11 Jul 2017 13:44:11 +0200 Subject: [PATCH 0337/1618] Add typings for retry --- types/retry/index.d.ts | 97 ++++++++++++++++++++++++++++++++++++++ types/retry/options.d.ts | 66 ++++++++++++++++++++++++++ types/retry/retry-tests.ts | 74 +++++++++++++++++++++++++++++ types/retry/tsconfig.json | 21 +++++++++ types/retry/tslint.json | 57 ++++++++++++++++++++++ 5 files changed, 315 insertions(+) create mode 100644 types/retry/index.d.ts create mode 100644 types/retry/options.d.ts create mode 100644 types/retry/retry-tests.ts create mode 100644 types/retry/tsconfig.json create mode 100644 types/retry/tslint.json diff --git a/types/retry/index.d.ts b/types/retry/index.d.ts new file mode 100644 index 0000000000..1489c3b476 --- /dev/null +++ b/types/retry/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for retry v0.10.1 +// Project: https://github.com/tim-kos/node-retry +// Definitions by: Stan Goldmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Options } from './options' +export * from './options' + +export interface RetryOperation { + /** + * Defines the function that is to be retried and executes it for the first time right away. + * + * @param {function} callback The function that is to be retried + * @param {current} [callback.current] Number of attempts callback has been executed so far. + * @param {Options.Attempt} [options] + * + * + * @return {void} + */ + attempt(callback: (current?: number) => void, options?: Options.Attempt): void + + /** + * Returns false when no error value is given, or the maximum amount of retries has been reached. + * Otherwise it returns true, and retries the operation after the timeout for the current attempt number. + * + * @param {(Error|any)} [err] + * + * @return {boolean} + */ + retry(err?: Error | any): boolean + + /** + * The number of attempts it took to call the retrying function before it was successful. + * + * @return {number} + */ + attempts(): number + + /** + * A reference to the error object that occured most frequently. + * Errors are compared using the error.message property. + * + * @return {(Error|null)} If no errors occured so far the value will be null. + */ + mainError(): Error | null + + /** + * Returns an array of all errors that have been passed to RetryOperation.retry() so far. + * + * @return {Error[]} + */ + errors(): Error[] + + /** + * Stopts the operation being retried. Useful for aborting the operation on a fatal error etc. + */ + stop(): void +} +/** + * Create a new RetryOperation object. + * + * @param {Options.Operation} [options] + * + * @return {RetryOperation} + */ +export function operation(options?: Options.Operation): RetryOperation + +/** + * Get an array with timeouts and their return values in milliseconds. + * + * @param {Options.Timeouts} [options] + * + * @return {number[]} + */ +export function timeouts(options?: Options.Timeouts): number[] + +/** + * Create a new timeout (in milliseconds) based on the given parameters. + * + * @param {number} attempt Representing for which retry the timeout should be calculated. + * @param {Options.Timeout} [options] + * + * @return {number} timeout + */ +export function createTimeout(attempt: number, options?: Options.Timeout): number + +/** + * Wrap all functions of the object with retry. + * + * @param {object} object The object to be wrapped + * @param {Options.Operation} [options] + * @param {string[]} [methods] Methods which need to be wrapped + * + * @return {void} + */ +export function wrap(object: object, options?: Options.Operation, methods?: string[]): void diff --git a/types/retry/options.d.ts b/types/retry/options.d.ts new file mode 100644 index 0000000000..b7fe689e67 --- /dev/null +++ b/types/retry/options.d.ts @@ -0,0 +1,66 @@ +export namespace Options { + /** + * @type {boolean} [forever=false] Whether to retry forever. + * @type {boolean} [unref=false] Wether to unref the setTimeout's or not. + */ + interface Retry { + forever: boolean + unref: boolean + } + + /** + * @type {number} timeout A timeout in milliseconds. + * @type {function} callback Callback to execute when the operation takes longer than the timeout. + */ + interface Attempt { + timeout: number + callback: () => void + } + + /** + * @type {number} [retries=10] The maximum amount of times to retry the operation. + * @type {number} [factor=2] The exponential factor to use. + * @type {number} [minTimeout=1000] The number of milliseconds before starting the first retry. + * @type {number} [maxTimeout=Infinity] The maximum number of milliseconds between two retries. + * @type {boolean} [randomize=false] Randomizes the timeouts by multiplying a factor between 1-2. + * @type {boolean} [forever=false] Whether to retry forever. + * @type {boolean} [unref=false] Wether to unref the setTimeout's. + */ + interface Operation { + retries: number + factor: number + minTimeout: number + maxTimeout: number + randomize: boolean + forever: boolean + unref: boolean + } + + /** + * @type {number} [retries=10] The maximum amount of times to retry the operation. + * @type {number} [factor=2] The exponential factor to use. + * @type {number} [minTimeout=1000] The number of milliseconds before starting the first retry. + * @type {number} [maxTimeout=Infinity] The maximum number of milliseconds between two retries. + * @type {boolean} [randomize=false] Randomizes the timeouts by multiplying a factor between 1-2. + */ + interface Timeouts { + retries: number + factor: number + minTimeout: number + maxTimeout: number + randomize: boolean + } + + /** + * @type {number} [factor=2] The exponential factor to use. + * @type {number} [minTimeout=1000] The number of milliseconds before starting the first retry. + * @type {number} [maxTimeout=Infinity] The maximum number of milliseconds between two retries. + * @type {boolean} [randomize=false] Randomizes the timeouts by multiplying a factor between 1-2. + */ + interface Timeout { + factor: number + minTimeout: number + maxTimeout: number + randomize: boolean + } +} diff --git a/types/retry/retry-tests.ts b/types/retry/retry-tests.ts new file mode 100644 index 0000000000..ebd260ff62 --- /dev/null +++ b/types/retry/retry-tests.ts @@ -0,0 +1,74 @@ +// import * as retry from './index' +import retry = require('retry') + +// Option values +const att = 4 +const ret = 2 +const fac = 1.5 +const min = 2000 +const max = 4000 +const rnd = false +const evr = false +const unr = false + +// Options themselves +const operationOptions: retry.Options.Operation = { + retries: ret, + factor: fac, + minTimeout: min, + maxTimeout: max, + randomize: rnd, + forever: evr, + unref: unr, +} + +const timeoutOptions: retry.Options.Timeout = { + factor: fac, + minTimeout: min, + maxTimeout: max, + randomize: rnd, +} + +const timeoutsOptions: retry.Options.Timeouts = { + retries: ret, + factor: fac, + minTimeout: min, + maxTimeout: max, + randomize: rnd, +} + +// Class to be wrapped later on +class Foo { + public bar() { + // + } + + public baz() { + // + } +} + +const operation = retry.operation(operationOptions) + +operation.attempt((current) => { + const err = Math.random() >= 0.5 ? new Error('Happens to the best of us') : undefined + + const retry = operation.retry(err) + + if (retry) { + const after = operation.attempts() + } + else { + const errors = operation.errors() + + const main = operation.mainError() + } + + operation.stop() +}) + +const timeout = retry.createTimeout(att, timeoutOptions) + +const timeouts = retry.timeouts(timeoutsOptions) + +const wrap = retry.wrap(new Foo(), operationOptions, ['bar']) diff --git a/types/retry/tsconfig.json b/types/retry/tsconfig.json new file mode 100644 index 0000000000..ac59335113 --- /dev/null +++ b/types/retry/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true, + "noImplicitThis": true, + "noImplicitReturns": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "options.d.ts", + "retry-tests.ts" + ] +} diff --git a/types/retry/tslint.json b/types/retry/tslint.json new file mode 100644 index 0000000000..bab5334f69 --- /dev/null +++ b/types/retry/tslint.json @@ -0,0 +1,57 @@ +{ + "defaultSeverity": "error", + "extends": [ + "tslint:recommended" + ], + "rulesDirectory": [], + "rules": { + "ordered-imports": false, + "object-literal-sort-keys": false, + "semicolon": false, + "max-line-length": [ + true, + 120 + ], + "indent": [ + true, + "spaces", + 4 + ], + "quotemark": [ + true, + "single", + "avoid-escape" + ], + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "trailing-comma": [ + true, + { + "multiline": { + "objects": "always", + "arrays": "always", + "functions": "never", + "typeLiterals": "ignore" + } + } + ], + "interface-name": [ + true, + "never-prefix" + ], + "no-namespace": [ + true, + "allow-declarations" + ], + "align": [ + true, + "arguments", + "statements", + "members", + "elements" + ] + } +} From 5dd4d38774f4551a2634198e7839161eaea446c1 Mon Sep 17 00:00:00 2001 From: Bastien Date: Tue, 11 Jul 2017 14:00:37 +0200 Subject: [PATCH 0338/1618] Fix lint errors --- types/spark-md5/index.d.ts | 24 ++++++++++++++---------- types/spark-md5/spark-md5-tests.ts | 12 ++++++------ types/spark-md5/tslint.json | 7 ++++++- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/types/spark-md5/index.d.ts b/types/spark-md5/index.d.ts index 6f93e6a821..f0bcec7131 100644 --- a/types/spark-md5/index.d.ts +++ b/types/spark-md5/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/satazor/js-spark-md5#readme // Definitions by: My Self // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 interface State { buff: Uint8Array; @@ -9,34 +10,37 @@ interface State { hash: number[]; } -interface IArrayBuffer extends ArrayBuffer {} +// copy of ArrayBuffer because of a conflict with the class SparkMD5.ArrayBuffer +interface ArrayBufferCopy extends ArrayBuffer {} declare class SparkMD5 { constructor(); append(str: string): SparkMD5; appendBinary(contents: string): SparkMD5; - end (raw?: boolean): string; - reset (): SparkMD5; + end(raw?: boolean): string; + reset(): SparkMD5; getState(): State; setState(state: State): State; destroy(): void; - static hash(str: string, raw?: boolean): string - static hashBinary(content: string, raw?: boolean): string + static hash(str: string, raw?: boolean): string; + static hashBinary(content: string, raw?: boolean): string; } declare namespace SparkMD5 { class ArrayBuffer { constructor(); append(str: string): ArrayBuffer; - end (raw?: boolean): string; - reset (): ArrayBuffer; + end(raw?: boolean): string; + reset(): ArrayBuffer; getState(): State; setState(state: State): State; destroy(): void; - static hash(arr: IArrayBuffer, raw?: boolean): string + static hash(arr: ArrayBufferCopy, raw?: boolean): string; } } -declare module "spark-md5" { +export = SparkMD5; + +/*declare module "spark-md5" { export = SparkMD5; -} +}*/ diff --git a/types/spark-md5/spark-md5-tests.ts b/types/spark-md5/spark-md5-tests.ts index 4b960eaa56..7cff5c461a 100644 --- a/types/spark-md5/spark-md5-tests.ts +++ b/types/spark-md5/spark-md5-tests.ts @@ -4,17 +4,17 @@ SparkMD5.hash('Hi there'); SparkMD5.hash('Hi there', true); SparkMD5.hashBinary(""); -var spark = new SparkMD5(); +let spark = new SparkMD5(); spark.append('Hi'); spark.append(' there'); -var hexHash = spark.end(); -var rawHash = spark.end(true); +let hexHash = spark.end(); +let rawHash = spark.end(true); -var sparkArr = new SparkMD5.ArrayBuffer(); +let sparkArr = new SparkMD5.ArrayBuffer(); sparkArr.append('Hi'); sparkArr.append(' there'); -var hexHash = sparkArr.end(); -var rawHash = sparkArr.end(true); +hexHash = sparkArr.end(); +rawHash = sparkArr.end(true); const arr = new ArrayBuffer(8); SparkMD5.ArrayBuffer.hash(arr); diff --git a/types/spark-md5/tslint.json b/types/spark-md5/tslint.json index 3db14f85ea..7caadb5ed8 100644 --- a/types/spark-md5/tslint.json +++ b/types/spark-md5/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false + } +} From c81ee2c38fbef270973fcca219cdbbd830fd2b2f Mon Sep 17 00:00:00 2001 From: Stan Goldmann Date: Tue, 11 Jul 2017 13:57:05 +0200 Subject: [PATCH 0339/1618] Fix CI errors * Lower typescript version since 2.4 is not supported yet, remove minor version and version tag from package * Add lib to tsconfig.json * Adjust tslint.json by extending dstlint and removing duplicate rules --- types/retry/index.d.ts | 4 ++-- types/retry/tsconfig.json | 3 +++ types/retry/tslint.json | 50 +++------------------------------------ 3 files changed, 8 insertions(+), 49 deletions(-) diff --git a/types/retry/index.d.ts b/types/retry/index.d.ts index 1489c3b476..e284f0241e 100644 --- a/types/retry/index.d.ts +++ b/types/retry/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for retry v0.10.1 +// Type definitions for retry 0.10 // Project: https://github.com/tim-kos/node-retry // Definitions by: Stan Goldmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.3 import { Options } from './options' export * from './options' diff --git a/types/retry/tsconfig.json b/types/retry/tsconfig.json index ac59335113..8fe0ee98bb 100644 --- a/types/retry/tsconfig.json +++ b/types/retry/tsconfig.json @@ -1,6 +1,9 @@ { "compilerOptions": { "module": "commonjs", + "lib": [ + "es5" + ], "noImplicitAny": true, "noImplicitThis": true, "noImplicitReturns": true, diff --git a/types/retry/tslint.json b/types/retry/tslint.json index bab5334f69..5a7fb3d744 100644 --- a/types/retry/tslint.json +++ b/types/retry/tslint.json @@ -1,57 +1,13 @@ { - "defaultSeverity": "error", - "extends": [ - "tslint:recommended" - ], - "rulesDirectory": [], + "extends": "dtslint/dt.json", "rules": { - "ordered-imports": false, - "object-literal-sort-keys": false, + "member-access": true, + "prefer-method-signature": false, "semicolon": false, - "max-line-length": [ - true, - 120 - ], - "indent": [ - true, - "spaces", - 4 - ], - "quotemark": [ - true, - "single", - "avoid-escape" - ], "one-line": [ true, "check-open-brace", "check-whitespace" - ], - "trailing-comma": [ - true, - { - "multiline": { - "objects": "always", - "arrays": "always", - "functions": "never", - "typeLiterals": "ignore" - } - } - ], - "interface-name": [ - true, - "never-prefix" - ], - "no-namespace": [ - true, - "allow-declarations" - ], - "align": [ - true, - "arguments", - "statements", - "members", - "elements" ] } } From 5d79b2be918b0bd36367ac0950b6f1f09bc19d85 Mon Sep 17 00:00:00 2001 From: Bastien Date: Tue, 11 Jul 2017 14:55:43 +0200 Subject: [PATCH 0340/1618] [angular-pdfjs-viewer] Add type --- .../angular-pdfjs-viewer-tests.ts | 11 ++++++++++ types/angular-pdfjs-viewer/index.d.ts | 19 ++++++++++++++++ types/angular-pdfjs-viewer/tsconfig.json | 22 +++++++++++++++++++ types/angular-pdfjs-viewer/tslint.json | 1 + 4 files changed, 53 insertions(+) create mode 100644 types/angular-pdfjs-viewer/angular-pdfjs-viewer-tests.ts create mode 100644 types/angular-pdfjs-viewer/index.d.ts create mode 100644 types/angular-pdfjs-viewer/tsconfig.json create mode 100644 types/angular-pdfjs-viewer/tslint.json diff --git a/types/angular-pdfjs-viewer/angular-pdfjs-viewer-tests.ts b/types/angular-pdfjs-viewer/angular-pdfjs-viewer-tests.ts new file mode 100644 index 0000000000..123b497dcb --- /dev/null +++ b/types/angular-pdfjs-viewer/angular-pdfjs-viewer-tests.ts @@ -0,0 +1,11 @@ +import * as angular from "angular"; +import "angular-pdfjs-viewer"; + +angular.module('app').config((pdfjsViewerConfigProvider: angular.pdfjsViewer.ConfigProvider) => { + pdfjsViewerConfigProvider.setWorkerSrc("/assets/pdf.js-viewer/pdf.worker.js"); + pdfjsViewerConfigProvider.setCmapDir("/assets/pdf.js-viewer/cmaps"); + pdfjsViewerConfigProvider.setImageDir("/assets/pdf.js-viewer/images"); + + pdfjsViewerConfigProvider.disableWorker(); + pdfjsViewerConfigProvider.setVerbosity("infos"); // "errors", "warnings" or "infos" +}); diff --git a/types/angular-pdfjs-viewer/index.d.ts b/types/angular-pdfjs-viewer/index.d.ts new file mode 100644 index 0000000000..392164bb00 --- /dev/null +++ b/types/angular-pdfjs-viewer/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for angular-pdfjs-viewer 1.0 +// Project: https://github.com/legalthings/angular-pdfjs-viewer +// Definitions by: Bastien Moulia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as angular from 'angular'; + +declare module 'angular' { + namespace pdfjsViewer { + interface ConfigProvider extends angular.IServiceProvider { + setWorkerSrc(src: string): void; + setCmapDir(dir: string): void; + setImageDir(dir: string): void; + disableWorker(): void; + setVerbosity(verbosity: "errors" | "warnings" | "infos"): void; + } + } +} diff --git a/types/angular-pdfjs-viewer/tsconfig.json b/types/angular-pdfjs-viewer/tsconfig.json new file mode 100644 index 0000000000..a8d322df87 --- /dev/null +++ b/types/angular-pdfjs-viewer/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-pdfjs-viewer-tests.ts" + ] +} diff --git a/types/angular-pdfjs-viewer/tslint.json b/types/angular-pdfjs-viewer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/angular-pdfjs-viewer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d71db6e84d929f5ac2cbda1662eb42deab77b758 Mon Sep 17 00:00:00 2001 From: Lee Henson Date: Tue, 11 Jul 2017 14:00:08 +0100 Subject: [PATCH 0341/1618] [stripe-node] cvc must be a string, as it may have leading zeros --- types/stripe-node/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/stripe-node/index.d.ts b/types/stripe-node/index.d.ts index a6193cb45d..284d53e8c0 100644 --- a/types/stripe-node/index.d.ts +++ b/types/stripe-node/index.d.ts @@ -3959,7 +3959,7 @@ declare namespace StripeNode { * Australia, Canada, or the United States. Highly recommended to always * include this value. */ - cvc?: number; + cvc?: string; /** * Cardholder's full name. From 8455dafd74d4c7dafb0183b29070c7402f6d1681 Mon Sep 17 00:00:00 2001 From: Arjen van der Ende Date: Tue, 11 Jul 2017 14:53:12 +0200 Subject: [PATCH 0342/1618] [csv-stringify] Add formatter options for boolean, date and object types --- types/csv-stringify/csv-stringify-tests.ts | 10 ++++++++++ types/csv-stringify/index.d.ts | 11 +++++++++++ types/csv-stringify/tslint.json | 7 ++++++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/types/csv-stringify/csv-stringify-tests.ts b/types/csv-stringify/csv-stringify-tests.ts index d7a6f0196b..f899896a5d 100644 --- a/types/csv-stringify/csv-stringify-tests.ts +++ b/types/csv-stringify/csv-stringify-tests.ts @@ -12,6 +12,16 @@ stringify([["1", "2", "3"], ["4", "5", "6"]], { // nothing }); +stringify([["1", true, new Date()], ["4", false, new Date()]], { + delimiter: ",", + formatters: { + bool: value => value ? 'yes' : 'no', + date: value => value.toISOString() + } +}, (error: Error, output: string): void => { + // nothing +}); + stream = stringify({ delimiter: "," }); stream.write(["1", "2", "3"]); diff --git a/types/csv-stringify/index.d.ts b/types/csv-stringify/index.d.ts index a636547187..7715109521 100644 --- a/types/csv-stringify/index.d.ts +++ b/types/csv-stringify/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for csv-stringify 1.0 // Project: https://github.com/wdavidw/node-csv-stringify // Definitions by: Rogier Schouten +// Arjen van der Ende // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -55,6 +56,16 @@ declare namespace stringify { * special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). */ rowDelimiter?: string; + /** + * Override serialization of boolean, dates and complex objects. + */ + formatters?: FormatterOpts; + } + + interface FormatterOpts { + bool?: (value: boolean) => string; + date?: (value: Date) => string; + object?: (value: any) => string; } interface Stringifier extends NodeJS.ReadWriteStream { diff --git a/types/csv-stringify/tslint.json b/types/csv-stringify/tslint.json index 3db14f85ea..11584e5acd 100644 --- a/types/csv-stringify/tslint.json +++ b/types/csv-stringify/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "prefer-method-signature": false + } +} From 9045ee35ebe9c56e00f3994de1827c952141badb Mon Sep 17 00:00:00 2001 From: Arjen van der Ende Date: Tue, 11 Jul 2017 15:09:09 +0200 Subject: [PATCH 0343/1618] [csv-stringify] Bump version number in header --- types/csv-stringify/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/csv-stringify/index.d.ts b/types/csv-stringify/index.d.ts index 7715109521..e727a0dcd9 100644 --- a/types/csv-stringify/index.d.ts +++ b/types/csv-stringify/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for csv-stringify 1.0 +// Type definitions for csv-stringify 1.4 // Project: https://github.com/wdavidw/node-csv-stringify // Definitions by: Rogier Schouten // Arjen van der Ende From 646d56fd35a94c141a00f50043286bbb6a3a2b93 Mon Sep 17 00:00:00 2001 From: Arjen van der Ende Date: Tue, 11 Jul 2017 16:15:23 +0200 Subject: [PATCH 0344/1618] [csv-stringify] Allow .write to write array with optional encoding and callback --- types/csv-stringify/csv-stringify-tests.ts | 3 +++ types/csv-stringify/index.d.ts | 7 +++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/types/csv-stringify/csv-stringify-tests.ts b/types/csv-stringify/csv-stringify-tests.ts index f899896a5d..e73e9abde3 100644 --- a/types/csv-stringify/csv-stringify-tests.ts +++ b/types/csv-stringify/csv-stringify-tests.ts @@ -25,6 +25,9 @@ stringify([["1", true, new Date()], ["4", false, new Date()]], { stream = stringify({ delimiter: "," }); stream.write(["1", "2", "3"]); +stream.write(["4", true, new Date()], 'utf8', (err: Error, output: string): void => { + // nothing +}); const transform: NodeJS.ReadWriteStream = stream; diff --git a/types/csv-stringify/index.d.ts b/types/csv-stringify/index.d.ts index e727a0dcd9..78c049ad3a 100644 --- a/types/csv-stringify/index.d.ts +++ b/types/csv-stringify/index.d.ts @@ -69,12 +69,11 @@ declare namespace stringify { } interface Stringifier extends NodeJS.ReadWriteStream { - // Stringifier stream takes array of strings or Object - write(line: string[] | any): boolean; + // Stringifier stream takes array of strings or Object, and optional encoding and callback + write(line: string[] | any, encoding?: string, cb?: (error: Error | undefined, output: string) => void): boolean; // repeat declarations from NodeJS.WritableStream to avoid compile error - write(buffer: string | Buffer, cb?: () => void): boolean; - write(str: string, encoding?: string, cb?: () => void): boolean; + write(buffer: string | Buffer, cb?: (error: Error | undefined, output: string) => void): boolean; } } From 31c0726fcbd9b34e9434d19e6bbd79c3d9da87ea Mon Sep 17 00:00:00 2001 From: Jason Cheatham Date: Tue, 11 Jul 2017 09:54:36 -0400 Subject: [PATCH 0345/1618] Add shell-quote types --- types/shell-quote/index.d.ts | 12 ++++++++++++ types/shell-quote/shell-quote-tests.ts | 8 ++++++++ types/shell-quote/tsconfig.json | 22 ++++++++++++++++++++++ types/shell-quote/tslint.json | 1 + 4 files changed, 43 insertions(+) create mode 100644 types/shell-quote/index.d.ts create mode 100644 types/shell-quote/shell-quote-tests.ts create mode 100644 types/shell-quote/tsconfig.json create mode 100644 types/shell-quote/tslint.json diff --git a/types/shell-quote/index.d.ts b/types/shell-quote/index.d.ts new file mode 100644 index 0000000000..51e197618d --- /dev/null +++ b/types/shell-quote/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for shell-quote 1.6 +// Project: https://github.com/substack/node-shell-quote +// Definitions by: Jason Cheatham +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export function quote(args: string[]): string; +export function parse( + cmd: string, + env?: { [key: string]: string } | ((key: string) => string | object), + opts?: { [key: string]: string } +): string[]; diff --git a/types/shell-quote/shell-quote-tests.ts b/types/shell-quote/shell-quote-tests.ts new file mode 100644 index 0000000000..73b33be7a0 --- /dev/null +++ b/types/shell-quote/shell-quote-tests.ts @@ -0,0 +1,8 @@ +import { parse, quote } from 'shell-quote'; + +quote([ 'a', 'b c d', '$f', '"g"' ]); +parse('a "b c" \\$def \'it\\\'s great\''); +parse('beep --boop="$PWD"', { PWD: '/home/robot' }); +parse('beep --boop="$PWD"', { PWD: '/home/robot' }, { escape: '^' }); +parse('beep --boop="$PWD"', (key: string) => '/home/robot'); +parse('beep --boop="$PWD"', (key: string) => ({ op: '||' })); diff --git a/types/shell-quote/tsconfig.json b/types/shell-quote/tsconfig.json new file mode 100644 index 0000000000..f4db2c63ff --- /dev/null +++ b/types/shell-quote/tsconfig.json @@ -0,0 +1,22 @@ +{ + "files": [ + "index.d.ts", + "shell-quote-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/shell-quote/tslint.json b/types/shell-quote/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/shell-quote/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d6042ebb83be87966676fe39a6b7ac766c4feb3e Mon Sep 17 00:00:00 2001 From: Morten Houston Ludvigsen Date: Tue, 11 Jul 2017 16:23:39 +0200 Subject: [PATCH 0346/1618] Don't require knockout extension functions to be of type KnockoutBindingHandler --- types/knockout/index.d.ts | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 063d1c4ec5..533f2adfc5 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -5,24 +5,21 @@ interface KnockoutExtensionFunctions { - [key: string]: KnockoutBindingHandler | undefined; + [key: string]: any; } -interface KnockoutSubscribableFunctions { +interface KnockoutSubscribableFunctions extends KnockoutExtensionFunctions { notifySubscribers(valueToWrite?: T, event?: string): void; } -type KnockoutSubscribableExtensionFunctions = KnockoutSubscribableFunctions & KnockoutExtensionFunctions; -interface KnockoutComputedFunctions { +interface KnockoutComputedFunctions extends KnockoutExtensionFunctions { } -type KnockoutComputedExtensionFunctions = KnockoutComputedFunctions & KnockoutExtensionFunctions; -interface KnockoutObservableFunctions { +interface KnockoutObservableFunctions extends KnockoutExtensionFunctions { equalityComparer(a: any, b: any): boolean; } -type KnockoutObservableExtensionFunctions = KnockoutObservableFunctions & KnockoutExtensionFunctions; -interface KnockoutObservableArrayFunctions { +interface KnockoutObservableArrayFunctions extends KnockoutExtensionFunctions { // General Array functions indexOf(searchElement: T, fromIndex?: number): number; slice(start: number, end?: number): T[]; @@ -49,10 +46,9 @@ interface KnockoutObservableArrayFunctions { destroyAll(items: T[]): void; destroyAll(): void; } -type KnockoutObservableArrayExtensionFunctions = KnockoutObservableArrayFunctions & KnockoutExtensionFunctions; interface KnockoutSubscribableStatic { - fn: KnockoutSubscribableExtensionFunctions; + fn: KnockoutSubscribableFunctions; new (): KnockoutSubscribable; } @@ -71,7 +67,7 @@ interface KnockoutSubscribable extends KnockoutSubscribableFunctions { } interface KnockoutComputedStatic { - fn: KnockoutComputedExtensionFunctions; + fn: KnockoutComputedFunctions; (): KnockoutComputed; (func: () => T, context?: any, options?: any): KnockoutComputed; @@ -79,7 +75,7 @@ interface KnockoutComputedStatic { } interface KnockoutComputed extends KnockoutObservable, KnockoutComputedFunctions { - fn: KnockoutComputedExtensionFunctions; + fn: KnockoutComputedFunctions; dispose(): void; isActive(): boolean; @@ -88,7 +84,7 @@ interface KnockoutComputed extends KnockoutObservable, KnockoutComputedFun } interface KnockoutObservableArrayStatic { - fn: KnockoutObservableArrayExtensionFunctions; + fn: KnockoutObservableArrayFunctions; (value?: T[] | null): KnockoutObservableArray; } @@ -103,7 +99,7 @@ interface KnockoutObservableArray extends KnockoutObservable, KnockoutOb } interface KnockoutObservableStatic { - fn: KnockoutObservableExtensionFunctions; + fn: KnockoutObservableFunctions; (value?: T | null): KnockoutObservable; } From fa5e2eed6cf1c029555b391efaded6d823bce9f6 Mon Sep 17 00:00:00 2001 From: teppeis Date: Wed, 12 Jul 2017 00:04:22 +0900 Subject: [PATCH 0347/1618] update mkdirp error type --- types/mkdirp/index.d.ts | 10 +++++----- types/mkdirp/mkdirp-tests.ts | 10 +++++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/types/mkdirp/index.d.ts b/types/mkdirp/index.d.ts index 7cd860f69a..fb18a16205 100644 --- a/types/mkdirp/index.d.ts +++ b/types/mkdirp/index.d.ts @@ -1,14 +1,14 @@ -// Type definitions for mkdirp 0.3.0 +// Type definitions for mkdirp 0.5.1 // Project: http://github.com/substack/node-mkdirp // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// - -declare function mkdirp(dir: string, cb: (err: any, made: string) => void): void; -declare function mkdirp(dir: string, flags: any, cb: (err: any, made: string) => void): void; +declare function mkdirp(dir: string, cb: (err: NodeJS.ErrnoException, made: string) => void): void; +declare function mkdirp(dir: string, opts: any, cb: (err: NodeJS.ErrnoException, made: string) => void): void; declare namespace mkdirp { - function sync(dir: string, flags?: any): string; + function sync(dir: string, opts?: any): string; } export = mkdirp; diff --git a/types/mkdirp/mkdirp-tests.ts b/types/mkdirp/mkdirp-tests.ts index 68c51f74b6..d17dff4e22 100644 --- a/types/mkdirp/mkdirp-tests.ts +++ b/types/mkdirp/mkdirp-tests.ts @@ -3,13 +3,21 @@ import mkdirp = require('mkdirp'); var str: string; var num: number; +var opts = { + mode: num, + fs: {} +}; mkdirp(str, num, (err, made) => { str = made; }); +mkdirp(str, opts, (err, made) => { + str = made; +}); mkdirp(str, (err, made) => { str = made; }); str = mkdirp.sync(str, num); -str = mkdirp.sync(str); \ No newline at end of file +str = mkdirp.sync(str, opts); +str = mkdirp.sync(str); From 0367bd2cfcd94496896543e21cdf94d810fd4b46 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 2 Jul 2017 15:51:12 -0400 Subject: [PATCH 0348/1618] [jquery] Formatting. Move EventStatic above Event. --- types/jquery/index.d.ts | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index b71bfbbed3..525461a01e 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -5155,6 +5155,14 @@ declare namespace JQuery { // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. + // Static members + interface EventStatic { + (event: string, properties?: T): JQuery.Event & T; + (properties: T): JQuery.Event & T; + new (event: string, properties?: T): JQuery.Event & T; + new (properties: T): JQuery.Event & T; + } + // Instance members interface Event { /** @@ -5213,7 +5221,6 @@ declare namespace JQuery { * @since 1.1.3 */ which: number; - /** * Returns whether event.preventDefault() was ever called on this event object. * @@ -5221,7 +5228,6 @@ declare namespace JQuery { * @since 1.3 */ isDefaultPrevented(): boolean; - /** * Returns whether event.stopImmediatePropagation() was ever called on this event object. * @@ -5229,7 +5235,6 @@ declare namespace JQuery { * @since 1.3 */ isImmediatePropagationStopped(): boolean; - /** * Returns whether event.stopPropagation() was ever called on this event object. * @@ -5237,7 +5242,6 @@ declare namespace JQuery { * @since 1.3 */ isPropagationStopped(): boolean; - /** * If this method is called, the default action of the event will not be triggered. * @@ -5245,7 +5249,6 @@ declare namespace JQuery { * @since 1.0 */ preventDefault(): void; - /** * Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. * @@ -5253,7 +5256,6 @@ declare namespace JQuery { * @since 1.3 */ stopImmediatePropagation(): void; - /** * Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. * @@ -5307,14 +5309,6 @@ declare namespace JQuery { target: TTarget; } - // Static members - interface EventStatic { - (event: string, properties?: T): JQuery.Event & T; - (properties: T): JQuery.Event & T; - new (event: string, properties?: T): JQuery.Event & T; - new (properties: T): JQuery.Event & T; - } - interface EventLike { type: string; } From f5fd92f7b3b3a2bb0906fe80d474e22b12b8e072 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 2 Jul 2017 15:54:48 -0400 Subject: [PATCH 0349/1618] [jquery] Formatting. Move JQueryStatic above JQuery for consistency. --- types/jquery/index.d.ts | 1874 ++++++++++++------------ types/jquery/jquery-tests.ts | 2634 +++++++++++++++++----------------- 2 files changed, 2254 insertions(+), 2254 deletions(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 525461a01e..9d290ebf43 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -38,6 +38,943 @@ declare const $: JQueryStatic; // Used by JQuery.Event type _Event = Event; +interface JQueryStatic { + /** + * A factory function that returns a chainable utility object with methods to register multiple + * callbacks into callback queues, invoke callback queues, and relay the success or failure state of + * any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + * @see {@link https://api.jquery.com/jQuery.Deferred/} + * @since 1.5 + */ + Deferred: JQuery.DeferredStatic; + Event: JQuery.EventStatic; + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize + * CSS property naming, or create custom properties. + * + * @see {@link https://api.jquery.com/jQuery.cssHooks/} + * @since 1.4.3 + */ + cssHooks: JQuery.PlainObject>; + /** + * An object containing all CSS properties that may be used without a unit. The .css() method uses this + * object to see if it may append px to unitless values. + * + * @see {@link https://api.jquery.com/jQuery.cssNumber/} + * @since 1.4.3 + */ + cssNumber: JQuery.PlainObject; + readonly fn: JQuery; + fx: { + /** + * The rate (in milliseconds) at which animations fire. + * + * @see {@link https://api.jquery.com/jQuery.fx.interval/} + * @since 1.4.3 + * @deprecated 3.0 + */ + interval: number; + /** + * Globally disable all animations. + * + * @see {@link https://api.jquery.com/jQuery.fx.off/} + * @since 1.3 + */ + off: boolean; + step: JQuery.PlainObject>; + }; + /** + * A Promise-like object (or "thenable") that resolves when the document is ready. + * + * @see {@link https://api.jquery.com/jQuery.ready/} + * @since 1.8 + */ + ready: JQuery.Thenable>; + /** + * A collection of properties that represent the presence of different browser features or bugs. + * Intended for jQuery's internal use; specific properties may be removed when they are no longer + * needed internally to improve page startup performance. For your own project's feature-detection + * needs, we strongly recommend the use of an external library such as Modernizr instead of dependency + * on properties in jQuery.support. + * + * @see {@link https://api.jquery.com/jQuery.support/} + * @since 1.3 + * @deprecated 1.9 + */ + support: JQuery.PlainObject; + valHooks: JQuery.PlainObject>; + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. + * A string defining a single, standalone, HTML element (e.g.

    or
    ). + * @param ownerDocument_attributes A document in which the new elements will be created. + * An object of attributes, events, and methods to call on the newly-created element. + * @see {@link https://api.jquery.com/jQuery/} + * @since 1.0 + * @since 1.4 + */ + (html: JQuery.htmlString, ownerDocument_attributes: Document | JQuery.PlainObject): JQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + * @see {@link https://api.jquery.com/jQuery/} + * @since 1.0 + */ + (selector: JQuery.Selector, context: Element | Document | JQuery | undefined): JQuery; + // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. + // HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function. + (window: Window, discriminator: boolean): JQueryStatic; + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * Binds a function to be executed when the DOM has finished loading. + * + * @param selector_object_callback A string containing a selector expression + * A DOM element to wrap in a jQuery object. + * An array containing a set of DOM elements to wrap in a jQuery object. + * A plain object to wrap in a jQuery object. + * An existing jQuery object to clone. + * The function to execute when the DOM is ready. + * @see {@link https://api.jquery.com/jQuery/} + * @since 1.0 + * @since 1.4 + */ + (selector_object_callback?: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery | + JQuery.PlainObject | + ((this: Document, $: JQueryStatic) => void)): JQuery; + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * + * @param flags An optional list of space-separated flags that change how the callback list behaves. + * @see {@link https://api.jquery.com/jQuery.Callbacks/} + * @since 1.7 + */ + Callbacks(flags?: string): JQuery.Callbacks; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can + * be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. + * @see {@link https://api.jquery.com/jQuery.ajax/} + * @since 1.5 + */ + ajax(url: string, settings?: JQuery.AjaxSettings): JQuery.jqXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can + * be set for any option with $.ajaxSetup(). + * @see {@link https://api.jquery.com/jQuery.ajax/} + * @since 1.0 + */ + ajax(settings?: JQuery.AjaxSettings): JQuery.jqXHR; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they + * are processed by $.ajax(). + * + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + * @see {@link https://api.jquery.com/jQuery.ajaxPrefilter/} + * @since 1.5 + */ + ajaxPrefilter(dataTypes: string, + handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they + * are processed by $.ajax(). + * + * @param handler A handler to set default values for future Ajax requests. + * @see {@link https://api.jquery.com/jQuery.ajaxPrefilter/} + * @since 1.5 + */ + ajaxPrefilter(handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; + /** + * Set default values for future Ajax requests. Its use is not recommended. + * + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + * @see {@link https://api.jquery.com/jQuery.ajaxSetup/} + * @since 1.1 + */ + ajaxSetup(options: JQuery.AjaxSettings): JQuery.AjaxSettings; + /** + * Creates an object that handles the actual transmission of Ajax data. + * + * @param dataType A string identifying the data type to use + * @param handler A handler to return the new transport object to use with the data type provided in the first argument. + * @see {@link https://api.jquery.com/jQuery.ajaxTransport/} + * @since 1.5 + */ + ajaxTransport(dataType: string, + handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => JQuery.Transport | void): void; + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + * @see {@link https://api.jquery.com/jQuery.contains/} + * @since 1.4 + */ + contains(container: Element, contained: Element): boolean; + css(elem: Element, unknown: any): any; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or + * the full data store for the element. + * + * @param element The DOM element to query for the data. + * @param key Name of the data stored. + * @param undefined + * @see {@link https://api.jquery.com/jQuery.data/} + * @since 1.2.3 + */ + data(element: Element, key: string, undefined: undefined): any; // tslint:disable-line:unified-signatures + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value; this can be any Javascript type except undefined. + * @see {@link https://api.jquery.com/jQuery.data/} + * @since 1.2.3 + */ + data(element: Element, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or + * the full data store for the element. + * + * @param element The DOM element to query for the data. + * @param key Name of the data stored. + * @see {@link https://api.jquery.com/jQuery.data/} + * @since 1.2.3 + * @since 1.4 + */ + data(element: Element, key?: string): any; + /** + * Execute the next function on the queue for the matched element. + * + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @see {@link https://api.jquery.com/jQuery.dequeue/} + * @since 1.3 + */ + dequeue(element: Element, queueName?: string): void; + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. + * Arrays and array-like objects with a length property (such as a function's arguments object) are + * iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param array The array to iterate over. + * @param callback The function that will be executed on every object. + * @see {@link https://api.jquery.com/jQuery.each/} + * @since 1.0 + */ + each(array: ArrayLike, callback: (this: T, indexInArray: number, value: T) => false | any): ArrayLike; + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. + * Arrays and array-like objects with a length property (such as a function's arguments object) are + * iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param obj The object to iterate over. + * @param callback The function that will be executed on every object. + * @see {@link https://api.jquery.com/jQuery.each/} + * @since 1.0 + */ + each(obj: T, callback: (this: T[K], propertyName: K, valueOfProperty: T[K]) => false | any): T; + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + * @see {@link https://api.jquery.com/jQuery.error/} + * @since 1.4.1 + */ + error(message: string): any; + /** + * Escapes any character that has a special meaning in a CSS selector. + * + * @param selector A string containing a selector expression to escape. + * @see {@link https://api.jquery.com/jQuery.escapeSelector/} + * @since 3.0 + */ + escapeSelector(selector: JQuery.Selector): JQuery.Selector; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.1.4 + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.1.4 + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.1.4 + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.1.4 + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W): T & U & V & W; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.1.4 + */ + extend(deep: true, target: T, object1: U, object2: V): T & U & V; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.1.4 + */ + extend(deep: true, target: T, object1: U): T & U; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.1.4 + */ + extend(deep: true, target: any, object1: any, ...objects: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.0 + */ + extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.0 + */ + extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.0 + */ + extend(target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.0 + */ + extend(target: T, object1: U, object2: V, object3: W): T & U & V & W; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.0 + */ + extend(target: T, object1: U, object2: V): T & U & V; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.0 + */ + extend(target: T, object1: U): T & U; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see {@link https://api.jquery.com/jQuery.extend/} + * @since 1.0 + */ + extend(target: any, object1: any, ...objects: any[]): any; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but + * you can use null or jQuery.noop as a placeholder. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see {@link https://api.jquery.com/jQuery.get/} + * @since 1.0 + */ + get(url: string, + data: JQuery.PlainObject | string, + success: JQuery.jqXHR.DoneCallback | null, + dataType?: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but + * you can use null or jQuery.noop as a placeholder. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see {@link https://api.jquery.com/jQuery.get/} + * @since 1.0 + */ + get(url: string, + success: JQuery.jqXHR.DoneCallback | null, + dataType: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but + * you can use null or jQuery.noop as a placeholder. + * A plain object or string that is sent to the server with the request. + * @see {@link https://api.jquery.com/jQuery.get/} + * @since 1.0 + */ + get(url: string, + success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url_settings A string containing the URL to which the request is sent. + * A set of key/value pairs that configure the Ajax request. All properties except for url are + * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a + * complete list of all settings. The type option will automatically be set to GET. + * @see {@link https://api.jquery.com/jQuery.get/} + * @since 1.0 + * @since 1.12 + * @since 2.2 + */ + get(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @see {@link https://api.jquery.com/jQuery.getJSON/} + * @since 1.0 + */ + getJSON(url: string, + data: JQuery.PlainObject | string, + success: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param success_data A callback function that is executed if the request succeeds. + * A plain object or string that is sent to the server with the request. + * @see {@link https://api.jquery.com/jQuery.getJSON/} + * @since 1.0 + */ + getJSON(url: string, + success_data?: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @see {@link https://api.jquery.com/jQuery.getScript/} + * @since 1.0 + */ + getScript(url: string, + success?: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + * @see {@link https://api.jquery.com/jQuery.globalEval/} + * @since 1.0.4 + */ + globalEval(code: string): void; + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array-like object to search through. + * @param fn The function to process each item against. The first argument to the function is the item, and the + * second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements + * for which "callback" returns true. If "invert" is true, then the function returns an array + * consisting of all elements for which "callback" returns false. + * @see {@link https://api.jquery.com/jQuery.grep/} + * @since 1.0 + */ + grep(array: ArrayLike, + fn: (elementOfArray: T, indexInArray: number) => boolean, + invert?: boolean): T[]; + /** + * Determine whether an element has any jQuery data associated with it. + * + * @param element A DOM element to be checked for data. + * @see {@link https://api.jquery.com/jQuery.hasData/} + * @since 1.5 + */ + hasData(element: Element): boolean; + /** + * Holds or releases the execution of jQuery's ready event. + * + * @param hold Indicates whether the ready hold is being requested or released + * @see {@link https://api.jquery.com/jQuery.holdReady/} + * @since 1.6 + * @deprecated 3.2 + */ + holdReady(hold: boolean): void; + /** + * Modify and filter HTML strings passed through jQuery manipulation methods. + * + * @param html The HTML string on which to operate. + * @see {@link https://api.jquery.com/jQuery.htmlPrefilter/} + * @since 1.12/2.2 + */ + htmlPrefilter(html: JQuery.htmlString): JQuery.htmlString; + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex The index of the array at which to begin the search. The default is 0, which will search the whole array. + * @see {@link https://api.jquery.com/jQuery.inArray/} + * @since 1.2 + */ + inArray(value: T, array: T[], fromIndex?: number): number; + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + * @see {@link https://api.jquery.com/jQuery.isArray/} + * @since 1.3 + * @deprecated 3.2 + */ + isArray(obj: any): obj is any[]; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + * @see {@link https://api.jquery.com/jQuery.isEmptyObject/} + * @since 1.4 + */ + isEmptyObject(obj: any): obj is {}; + /** + * Determine if the argument passed is a JavaScript function object. + * + * @param obj Object to test whether or not it is a function. + * @see {@link https://api.jquery.com/jQuery.isFunction/} + * @since 1.2 + */ + isFunction(obj: any): obj is Function; + /** + * Determines whether its argument represents a JavaScript number. + * + * @param value The value to be tested. + * @see {@link https://api.jquery.com/jQuery.isNumeric/} + * @since 1.7 + */ + isNumeric(value: any): value is number; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + * @see {@link https://api.jquery.com/jQuery.isPlainObject/} + * @since 1.4 + */ + isPlainObject(obj: any): obj is JQuery.PlainObject; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + * @see {@link https://api.jquery.com/jQuery.isWindow/} + * @since 1.4.3 + */ + isWindow(obj: any): obj is Window; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node The DOM node that will be checked to see if it's in an XML document. + * @see {@link https://api.jquery.com/jQuery.isXMLDoc/} + * @since 1.1.4 + */ + isXMLDoc(node: Node): boolean; + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + * @see {@link https://api.jquery.com/jQuery.makeArray/} + * @since 1.2 + */ + makeArray(obj: ArrayLike): T[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the + * second argument is the index in array The function can return any value. A returned array will be + * flattened into the resulting array. Within the function, this refers to the global (window) object. + * @see {@link https://api.jquery.com/jQuery.map/} + * @since 1.0 + */ + map(array: T[], callback: (elementOfArray: T, indexInArray: number) => R): R[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param obj The Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the + * second argument is the key of the object property. The function can return any value to add to the + * array. A returned array will be flattened into the resulting array. Within the function, this refers + * to the global (window) object. + * @see {@link https://api.jquery.com/jQuery.map/} + * @since 1.6 + */ + map(obj: T, callback: (propertyOfObject: T[K], key: K) => R): R[]; + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array-like object to merge, the elements of second added. + * @param second The second array-like object to merge into the first, unaltered. + * @see {@link https://api.jquery.com/jQuery.merge/} + * @since 1.0 + */ + merge(first: ArrayLike, second: ArrayLike): Array; + /** + * Relinquish jQuery's control of the $ variable. + * + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + * @see {@link https://api.jquery.com/jQuery.noConflict/} + * @since 1.0 + */ + noConflict(removeAll?: boolean): this; + /** + * An empty function. + * + * @see {@link https://api.jquery.com/jQuery.noop/} + * @since 1.4 + */ + noop(): undefined; + /** + * Return a number representing the current time. + * + * @see {@link https://api.jquery.com/jQuery.now/} + * @since 1.4.3 + */ + now(): number; + /** + * Create a serialized representation of an array, a plain object, or a jQuery object suitable for use + * in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input + * elements with name/value properties. + * + * @param obj An array, a plain object, or a jQuery object to serialize. + * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. + * @see {@link https://api.jquery.com/jQuery.param/} + * @since 1.2 + * @since 1.4 + */ + param(obj: any[] | JQuery.PlainObject | JQuery, traditional?: boolean): string; + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context Document element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + * @see {@link https://api.jquery.com/jQuery.parseHTML/} + * @since 1.8 + */ + parseHTML(data: string, context: Document | null | undefined, keepScripts: boolean): JQuery.Node[]; + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context_keepScripts Document element to serve as the context in which the HTML fragment will be created + * A Boolean indicating whether to include scripts passed in the HTML string + * @see {@link https://api.jquery.com/jQuery.parseHTML/} + * @since 1.8 + */ + parseHTML(data: string, context_keepScripts?: Document | null | undefined | boolean): JQuery.Node[]; + /** + * Takes a well-formed JSON string and returns the resulting JavaScript value. + * + * @param json The JSON string to parse. + * @see {@link https://api.jquery.com/jQuery.parseJSON/} + * @since 1.4.1 + * @deprecated 3.0 + */ + parseJSON(json: string): any; + /** + * Parses a string into an XML document. + * + * @param data a well-formed XML string to be parsed + * @see {@link https://api.jquery.com/jQuery.parseXML/} + * @since 1.5 + */ + parseXML(data: string): XMLDocument; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but + * can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see {@link https://api.jquery.com/jQuery.post/} + * @since 1.0 + */ + post(url: string, + data: JQuery.PlainObject | string, + success: JQuery.jqXHR.DoneCallback | null, + dataType?: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but + * can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see {@link https://api.jquery.com/jQuery.post/} + * @since 1.0 + */ + post(url: string, + success: JQuery.jqXHR.DoneCallback | null, + dataType: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but + * can be null in that case. + * A plain object or string that is sent to the server with the request. + * @see {@link https://api.jquery.com/jQuery.post/} + * @since 1.0 + */ + post(url: string, + success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url_settings A string containing the URL to which the request is sent. + * A set of key/value pairs that configure the Ajax request. All properties except for url are + * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a + * complete list of all settings. Type will automatically be set to POST. + * @see {@link https://api.jquery.com/jQuery.post/} + * @since 1.0 + * @since 1.12 + * @since 2.2 + */ + post(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: Function, context: object, ...additionalArguments: any[]): Function; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param context The object to which the context of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(context: T, name: keyof T, ...additionalArguments: any[]): Function; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue The new function to add to the queue. + * An array of functions to replace the current queue contents. + * @see {@link https://api.jquery.com/jQuery.queue/} + * @since 1.3 + */ + queue(element: T, queueName?: string, newQueue?: JQuery.TypeOrArray>): JQuery.Queue; + /** + * Handles errors thrown synchronously in functions wrapped in jQuery(). + * + * @param error An error thrown in the function wrapped in jQuery(). + * @see {@link https://api.jquery.com/jQuery.readyException/} + * @since 3.1 + */ + readyException(error: Error): any; + /** + * Remove a previously-stored piece of data. + * + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + * @see {@link https://api.jquery.com/jQuery.removeData/} + * @since 1.2.3 + */ + removeData(element: Element, name?: string): void; + /** + * Creates an object containing a set of properties ready to be used in the definition of custom animations. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see {@link https://api.jquery.com/jQuery.speed/} + * @since 1.1 + */ + speed(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; + /** + * Creates an object containing a set of properties ready to be used in the definition of custom animations. + * + * @param duration A string or number determining how long the animation will run. + * @param easing_complete A string indicating which easing function to use for the transition. + * A function to call once the animation is complete, called once per matched element. + * @see {@link https://api.jquery.com/jQuery.speed/} + * @since 1.0 + * @since 1.1 + */ + speed(duration: JQuery.Duration, + easing_complete: string | ((this: TElement) => void)): JQuery.EffectsOptions; + /** + * Creates an object containing a set of properties ready to be used in the definition of custom animations. + * + * @param duration_complete_settings A string or number determining how long the animation will run. + * A function to call once the animation is complete, called once per matched element. + * @see {@link https://api.jquery.com/jQuery.speed/} + * @since 1.0 + * @since 1.1 + */ + speed(duration_complete_settings?: JQuery.Duration | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str The string to trim. + * @see {@link https://api.jquery.com/jQuery.trim/} + * @since 1.0 + */ + trim(str: string): string; + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + * @see {@link https://api.jquery.com/jQuery.type/} + * @since 1.4.3 + */ + type(obj: any): 'array' | 'boolean' | 'date' | 'error' | 'function' | 'null' | 'number' | 'object' | 'regexp' | 'string' | 'symbol' | 'undefined'; + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on + * arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + * @see {@link https://api.jquery.com/jQuery.unique/} + * @since 1.1.3 + * @deprecated 3.0 + */ + unique(array: T[]): T[]; + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on + * arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + * @see {@link https://api.jquery.com/jQuery.uniqueSort/} + * @since 1.12-2.2 + */ + uniqueSort(array: T[]): T[]; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when + (deferredT: JQuery.Promise | JQuery.Thenable | TR1, + deferredU: JQuery.Promise | JQuery.Thenable | UR1, + deferredV: JQuery.Promise | JQuery.Thenable | VR1): JQuery.Promise3; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when + (deferredT: JQuery.Promise | JQuery.Thenable | TR1, + deferredU: JQuery.Promise | JQuery.Thenable | UR1): JQuery.Promise2; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when + (deferredT: JQuery.Promise3 | + JQuery.Promise2): JQuery.Promise3; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when(deferred: JQuery.Promise | JQuery.Thenable | TR1): JQuery.Promise; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @param deferreds Zero or more Thenable objects. + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when(...deferreds: Array | JQuery.Thenable | TR1>): JQuery.Promise; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @param deferreds Zero or more Thenable objects. + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when(...deferreds: any[]): JQuery.Promise; +} + interface JQuery extends Iterable { /** * A string containing the jQuery version number. @@ -2394,943 +3331,6 @@ interface JQuery extends Iterable [n: number]: TElement; } -interface JQueryStatic { - /** - * A factory function that returns a chainable utility object with methods to register multiple - * callbacks into callback queues, invoke callback queues, and relay the success or failure state of - * any synchronous or asynchronous function. - * - * @param beforeStart A function that is called just before the constructor returns. - * @see {@link https://api.jquery.com/jQuery.Deferred/} - * @since 1.5 - */ - Deferred: JQuery.DeferredStatic; - Event: JQuery.EventStatic; - /** - * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize - * CSS property naming, or create custom properties. - * - * @see {@link https://api.jquery.com/jQuery.cssHooks/} - * @since 1.4.3 - */ - cssHooks: JQuery.PlainObject>; - /** - * An object containing all CSS properties that may be used without a unit. The .css() method uses this - * object to see if it may append px to unitless values. - * - * @see {@link https://api.jquery.com/jQuery.cssNumber/} - * @since 1.4.3 - */ - cssNumber: JQuery.PlainObject; - readonly fn: JQuery; - fx: { - /** - * The rate (in milliseconds) at which animations fire. - * - * @see {@link https://api.jquery.com/jQuery.fx.interval/} - * @since 1.4.3 - * @deprecated 3.0 - */ - interval: number; - /** - * Globally disable all animations. - * - * @see {@link https://api.jquery.com/jQuery.fx.off/} - * @since 1.3 - */ - off: boolean; - step: JQuery.PlainObject>; - }; - /** - * A Promise-like object (or "thenable") that resolves when the document is ready. - * - * @see {@link https://api.jquery.com/jQuery.ready/} - * @since 1.8 - */ - ready: JQuery.Thenable>; - /** - * A collection of properties that represent the presence of different browser features or bugs. - * Intended for jQuery's internal use; specific properties may be removed when they are no longer - * needed internally to improve page startup performance. For your own project's feature-detection - * needs, we strongly recommend the use of an external library such as Modernizr instead of dependency - * on properties in jQuery.support. - * - * @see {@link https://api.jquery.com/jQuery.support/} - * @since 1.3 - * @deprecated 1.9 - */ - support: JQuery.PlainObject; - valHooks: JQuery.PlainObject>; - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. - * A string defining a single, standalone, HTML element (e.g.
    or
    ). - * @param ownerDocument_attributes A document in which the new elements will be created. - * An object of attributes, events, and methods to call on the newly-created element. - * @see {@link https://api.jquery.com/jQuery/} - * @since 1.0 - * @since 1.4 - */ - (html: JQuery.htmlString, ownerDocument_attributes: Document | JQuery.PlainObject): JQuery; - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM Element, Document, or jQuery to use as context - * @see {@link https://api.jquery.com/jQuery/} - * @since 1.0 - */ - (selector: JQuery.Selector, context: Element | Document | JQuery | undefined): JQuery; - // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. - // HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function. - (window: Window, discriminator: boolean): JQueryStatic; - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * Binds a function to be executed when the DOM has finished loading. - * - * @param selector_object_callback A string containing a selector expression - * A DOM element to wrap in a jQuery object. - * An array containing a set of DOM elements to wrap in a jQuery object. - * A plain object to wrap in a jQuery object. - * An existing jQuery object to clone. - * The function to execute when the DOM is ready. - * @see {@link https://api.jquery.com/jQuery/} - * @since 1.0 - * @since 1.4 - */ - (selector_object_callback?: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery | - JQuery.PlainObject | - ((this: Document, $: JQueryStatic) => void)): JQuery; - /** - * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. - * - * @param flags An optional list of space-separated flags that change how the callback list behaves. - * @see {@link https://api.jquery.com/jQuery.Callbacks/} - * @since 1.7 - */ - Callbacks(flags?: string): JQuery.Callbacks; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param url A string containing the URL to which the request is sent. - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can - * be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. - * @see {@link https://api.jquery.com/jQuery.ajax/} - * @since 1.5 - */ - ajax(url: string, settings?: JQuery.AjaxSettings): JQuery.jqXHR; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can - * be set for any option with $.ajaxSetup(). - * @see {@link https://api.jquery.com/jQuery.ajax/} - * @since 1.0 - */ - ajax(settings?: JQuery.AjaxSettings): JQuery.jqXHR; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they - * are processed by $.ajax(). - * - * @param dataTypes An optional string containing one or more space-separated dataTypes - * @param handler A handler to set default values for future Ajax requests. - * @see {@link https://api.jquery.com/jQuery.ajaxPrefilter/} - * @since 1.5 - */ - ajaxPrefilter(dataTypes: string, - handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they - * are processed by $.ajax(). - * - * @param handler A handler to set default values for future Ajax requests. - * @see {@link https://api.jquery.com/jQuery.ajaxPrefilter/} - * @since 1.5 - */ - ajaxPrefilter(handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; - /** - * Set default values for future Ajax requests. Its use is not recommended. - * - * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. - * @see {@link https://api.jquery.com/jQuery.ajaxSetup/} - * @since 1.1 - */ - ajaxSetup(options: JQuery.AjaxSettings): JQuery.AjaxSettings; - /** - * Creates an object that handles the actual transmission of Ajax data. - * - * @param dataType A string identifying the data type to use - * @param handler A handler to return the new transport object to use with the data type provided in the first argument. - * @see {@link https://api.jquery.com/jQuery.ajaxTransport/} - * @since 1.5 - */ - ajaxTransport(dataType: string, - handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => JQuery.Transport | void): void; - /** - * Check to see if a DOM element is a descendant of another DOM element. - * - * @param container The DOM element that may contain the other element. - * @param contained The DOM element that may be contained by (a descendant of) the other element. - * @see {@link https://api.jquery.com/jQuery.contains/} - * @since 1.4 - */ - contains(container: Element, contained: Element): boolean; - css(elem: Element, unknown: any): any; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or - * the full data store for the element. - * - * @param element The DOM element to query for the data. - * @param key Name of the data stored. - * @param undefined - * @see {@link https://api.jquery.com/jQuery.data/} - * @since 1.2.3 - */ - data(element: Element, key: string, undefined: undefined): any; // tslint:disable-line:unified-signatures - /** - * Store arbitrary data associated with the specified element. Returns the value that was set. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - * @param value The new data value; this can be any Javascript type except undefined. - * @see {@link https://api.jquery.com/jQuery.data/} - * @since 1.2.3 - */ - data(element: Element, key: string, value: T): T; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or - * the full data store for the element. - * - * @param element The DOM element to query for the data. - * @param key Name of the data stored. - * @see {@link https://api.jquery.com/jQuery.data/} - * @since 1.2.3 - * @since 1.4 - */ - data(element: Element, key?: string): any; - /** - * Execute the next function on the queue for the matched element. - * - * @param element A DOM element from which to remove and execute a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see {@link https://api.jquery.com/jQuery.dequeue/} - * @since 1.3 - */ - dequeue(element: Element, queueName?: string): void; - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. - * Arrays and array-like objects with a length property (such as a function's arguments object) are - * iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param array The array to iterate over. - * @param callback The function that will be executed on every object. - * @see {@link https://api.jquery.com/jQuery.each/} - * @since 1.0 - */ - each(array: ArrayLike, callback: (this: T, indexInArray: number, value: T) => false | any): ArrayLike; - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. - * Arrays and array-like objects with a length property (such as a function's arguments object) are - * iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param obj The object to iterate over. - * @param callback The function that will be executed on every object. - * @see {@link https://api.jquery.com/jQuery.each/} - * @since 1.0 - */ - each(obj: T, callback: (this: T[K], propertyName: K, valueOfProperty: T[K]) => false | any): T; - /** - * Takes a string and throws an exception containing it. - * - * @param message The message to send out. - * @see {@link https://api.jquery.com/jQuery.error/} - * @since 1.4.1 - */ - error(message: string): any; - /** - * Escapes any character that has a special meaning in a CSS selector. - * - * @param selector A string containing a selector expression to escape. - * @see {@link https://api.jquery.com/jQuery.escapeSelector/} - * @since 3.0 - */ - escapeSelector(selector: JQuery.Selector): JQuery.Selector; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.1.4 - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.1.4 - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.1.4 - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.1.4 - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W): T & U & V & W; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.1.4 - */ - extend(deep: true, target: T, object1: U, object2: V): T & U & V; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.1.4 - */ - extend(deep: true, target: T, object1: U): T & U; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.1.4 - */ - extend(deep: true, target: any, object1: any, ...objects: any[]): any; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.0 - */ - extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.0 - */ - extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.0 - */ - extend(target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.0 - */ - extend(target: T, object1: U, object2: V, object3: W): T & U & V & W; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.0 - */ - extend(target: T, object1: U, object2: V): T & U & V; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.0 - */ - extend(target: T, object1: U): T & U; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @see {@link https://api.jquery.com/jQuery.extend/} - * @since 1.0 - */ - extend(target: any, object1: any, ...objects: any[]): any; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.get/} - * @since 1.0 - */ - get(url: string, - data: JQuery.PlainObject | string, - success: JQuery.jqXHR.DoneCallback | null, - dataType?: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.get/} - * @since 1.0 - */ - get(url: string, - success: JQuery.jqXHR.DoneCallback | null, - dataType: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. - * A plain object or string that is sent to the server with the request. - * @see {@link https://api.jquery.com/jQuery.get/} - * @since 1.0 - */ - get(url: string, - success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url_settings A string containing the URL to which the request is sent. - * A set of key/value pairs that configure the Ajax request. All properties except for url are - * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a - * complete list of all settings. The type option will automatically be set to GET. - * @see {@link https://api.jquery.com/jQuery.get/} - * @since 1.0 - * @since 1.12 - * @since 2.2 - */ - get(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @see {@link https://api.jquery.com/jQuery.getJSON/} - * @since 1.0 - */ - getJSON(url: string, - data: JQuery.PlainObject | string, - success: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. - * A plain object or string that is sent to the server with the request. - * @see {@link https://api.jquery.com/jQuery.getJSON/} - * @since 1.0 - */ - getJSON(url: string, - success_data?: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; - /** - * Load a JavaScript file from the server using a GET HTTP request, then execute it. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - * @see {@link https://api.jquery.com/jQuery.getScript/} - * @since 1.0 - */ - getScript(url: string, - success?: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; - /** - * Execute some JavaScript code globally. - * - * @param code The JavaScript code to execute. - * @see {@link https://api.jquery.com/jQuery.globalEval/} - * @since 1.0.4 - */ - globalEval(code: string): void; - /** - * Finds the elements of an array which satisfy a filter function. The original array is not affected. - * - * @param array The array-like object to search through. - * @param fn The function to process each item against. The first argument to the function is the item, and the - * second argument is the index. The function should return a Boolean value. this will be the global window object. - * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements - * for which "callback" returns true. If "invert" is true, then the function returns an array - * consisting of all elements for which "callback" returns false. - * @see {@link https://api.jquery.com/jQuery.grep/} - * @since 1.0 - */ - grep(array: ArrayLike, - fn: (elementOfArray: T, indexInArray: number) => boolean, - invert?: boolean): T[]; - /** - * Determine whether an element has any jQuery data associated with it. - * - * @param element A DOM element to be checked for data. - * @see {@link https://api.jquery.com/jQuery.hasData/} - * @since 1.5 - */ - hasData(element: Element): boolean; - /** - * Holds or releases the execution of jQuery's ready event. - * - * @param hold Indicates whether the ready hold is being requested or released - * @see {@link https://api.jquery.com/jQuery.holdReady/} - * @since 1.6 - * @deprecated 3.2 - */ - holdReady(hold: boolean): void; - /** - * Modify and filter HTML strings passed through jQuery manipulation methods. - * - * @param html The HTML string on which to operate. - * @see {@link https://api.jquery.com/jQuery.htmlPrefilter/} - * @since 1.12/2.2 - */ - htmlPrefilter(html: JQuery.htmlString): JQuery.htmlString; - /** - * Search for a specified value within an array and return its index (or -1 if not found). - * - * @param value The value to search for. - * @param array An array through which to search. - * @param fromIndex The index of the array at which to begin the search. The default is 0, which will search the whole array. - * @see {@link https://api.jquery.com/jQuery.inArray/} - * @since 1.2 - */ - inArray(value: T, array: T[], fromIndex?: number): number; - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - * @see {@link https://api.jquery.com/jQuery.isArray/} - * @since 1.3 - * @deprecated 3.2 - */ - isArray(obj: any): obj is any[]; - /** - * Check to see if an object is empty (contains no enumerable properties). - * - * @param obj The object that will be checked to see if it's empty. - * @see {@link https://api.jquery.com/jQuery.isEmptyObject/} - * @since 1.4 - */ - isEmptyObject(obj: any): obj is {}; - /** - * Determine if the argument passed is a JavaScript function object. - * - * @param obj Object to test whether or not it is a function. - * @see {@link https://api.jquery.com/jQuery.isFunction/} - * @since 1.2 - */ - isFunction(obj: any): obj is Function; - /** - * Determines whether its argument represents a JavaScript number. - * - * @param value The value to be tested. - * @see {@link https://api.jquery.com/jQuery.isNumeric/} - * @since 1.7 - */ - isNumeric(value: any): value is number; - /** - * Check to see if an object is a plain object (created using "{}" or "new Object"). - * - * @param obj The object that will be checked to see if it's a plain object. - * @see {@link https://api.jquery.com/jQuery.isPlainObject/} - * @since 1.4 - */ - isPlainObject(obj: any): obj is JQuery.PlainObject; - /** - * Determine whether the argument is a window. - * - * @param obj Object to test whether or not it is a window. - * @see {@link https://api.jquery.com/jQuery.isWindow/} - * @since 1.4.3 - */ - isWindow(obj: any): obj is Window; - /** - * Check to see if a DOM node is within an XML document (or is an XML document). - * - * @param node The DOM node that will be checked to see if it's in an XML document. - * @see {@link https://api.jquery.com/jQuery.isXMLDoc/} - * @since 1.1.4 - */ - isXMLDoc(node: Node): boolean; - /** - * Convert an array-like object into a true JavaScript array. - * - * @param obj Any object to turn into a native Array. - * @see {@link https://api.jquery.com/jQuery.makeArray/} - * @since 1.2 - */ - makeArray(obj: ArrayLike): T[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param array The Array to translate. - * @param callback The function to process each item against. The first argument to the function is the array item, the - * second argument is the index in array The function can return any value. A returned array will be - * flattened into the resulting array. Within the function, this refers to the global (window) object. - * @see {@link https://api.jquery.com/jQuery.map/} - * @since 1.0 - */ - map(array: T[], callback: (elementOfArray: T, indexInArray: number) => R): R[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param obj The Object to translate. - * @param callback The function to process each item against. The first argument to the function is the value; the - * second argument is the key of the object property. The function can return any value to add to the - * array. A returned array will be flattened into the resulting array. Within the function, this refers - * to the global (window) object. - * @see {@link https://api.jquery.com/jQuery.map/} - * @since 1.6 - */ - map(obj: T, callback: (propertyOfObject: T[K], key: K) => R): R[]; - /** - * Merge the contents of two arrays together into the first array. - * - * @param first The first array-like object to merge, the elements of second added. - * @param second The second array-like object to merge into the first, unaltered. - * @see {@link https://api.jquery.com/jQuery.merge/} - * @since 1.0 - */ - merge(first: ArrayLike, second: ArrayLike): Array; - /** - * Relinquish jQuery's control of the $ variable. - * - * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - * @see {@link https://api.jquery.com/jQuery.noConflict/} - * @since 1.0 - */ - noConflict(removeAll?: boolean): this; - /** - * An empty function. - * - * @see {@link https://api.jquery.com/jQuery.noop/} - * @since 1.4 - */ - noop(): undefined; - /** - * Return a number representing the current time. - * - * @see {@link https://api.jquery.com/jQuery.now/} - * @since 1.4.3 - */ - now(): number; - /** - * Create a serialized representation of an array, a plain object, or a jQuery object suitable for use - * in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input - * elements with name/value properties. - * - * @param obj An array, a plain object, or a jQuery object to serialize. - * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. - * @see {@link https://api.jquery.com/jQuery.param/} - * @since 1.2 - * @since 1.4 - */ - param(obj: any[] | JQuery.PlainObject | JQuery, traditional?: boolean): string; - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context Document element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - * @see {@link https://api.jquery.com/jQuery.parseHTML/} - * @since 1.8 - */ - parseHTML(data: string, context: Document | null | undefined, keepScripts: boolean): JQuery.Node[]; - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context_keepScripts Document element to serve as the context in which the HTML fragment will be created - * A Boolean indicating whether to include scripts passed in the HTML string - * @see {@link https://api.jquery.com/jQuery.parseHTML/} - * @since 1.8 - */ - parseHTML(data: string, context_keepScripts?: Document | null | undefined | boolean): JQuery.Node[]; - /** - * Takes a well-formed JSON string and returns the resulting JavaScript value. - * - * @param json The JSON string to parse. - * @see {@link https://api.jquery.com/jQuery.parseJSON/} - * @since 1.4.1 - * @deprecated 3.0 - */ - parseJSON(json: string): any; - /** - * Parses a string into an XML document. - * - * @param data a well-formed XML string to be parsed - * @see {@link https://api.jquery.com/jQuery.parseXML/} - * @since 1.5 - */ - parseXML(data: string): XMLDocument; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.post/} - * @since 1.0 - */ - post(url: string, - data: JQuery.PlainObject | string, - success: JQuery.jqXHR.DoneCallback | null, - dataType?: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see {@link https://api.jquery.com/jQuery.post/} - * @since 1.0 - */ - post(url: string, - success: JQuery.jqXHR.DoneCallback | null, - dataType: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but - * can be null in that case. - * A plain object or string that is sent to the server with the request. - * @see {@link https://api.jquery.com/jQuery.post/} - * @since 1.0 - */ - post(url: string, - success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url_settings A string containing the URL to which the request is sent. - * A set of key/value pairs that configure the Ajax request. All properties except for url are - * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a - * complete list of all settings. Type will automatically be set to POST. - * @see {@link https://api.jquery.com/jQuery.post/} - * @since 1.0 - * @since 1.12 - * @since 2.2 - */ - post(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (this) of the function should be set. - * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - * @see {@link https://api.jquery.com/jQuery.proxy/} - * @since 1.4 - * @since 1.6 - */ - proxy(fn: Function, context: object, ...additionalArguments: any[]): Function; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param context The object to which the context of the function should be set. - * @param name The name of the function whose context will be changed (should be a property of the context object). - * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. - * @see {@link https://api.jquery.com/jQuery.proxy/} - * @since 1.4 - * @since 1.6 - */ - proxy(context: T, name: keyof T, ...additionalArguments: any[]): Function; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element where the array of queued functions is attached. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue The new function to add to the queue. - * An array of functions to replace the current queue contents. - * @see {@link https://api.jquery.com/jQuery.queue/} - * @since 1.3 - */ - queue(element: T, queueName?: string, newQueue?: JQuery.TypeOrArray>): JQuery.Queue; - /** - * Handles errors thrown synchronously in functions wrapped in jQuery(). - * - * @param error An error thrown in the function wrapped in jQuery(). - * @see {@link https://api.jquery.com/jQuery.readyException/} - * @since 3.1 - */ - readyException(error: Error): any; - /** - * Remove a previously-stored piece of data. - * - * @param element A DOM element from which to remove data. - * @param name A string naming the piece of data to remove. - * @see {@link https://api.jquery.com/jQuery.removeData/} - * @since 1.2.3 - */ - removeData(element: Element, name?: string): void; - /** - * Creates an object containing a set of properties ready to be used in the definition of custom animations. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/jQuery.speed/} - * @since 1.1 - */ - speed(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; - /** - * Creates an object containing a set of properties ready to be used in the definition of custom animations. - * - * @param duration A string or number determining how long the animation will run. - * @param easing_complete A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/jQuery.speed/} - * @since 1.0 - * @since 1.1 - */ - speed(duration: JQuery.Duration, - easing_complete: string | ((this: TElement) => void)): JQuery.EffectsOptions; - /** - * Creates an object containing a set of properties ready to be used in the definition of custom animations. - * - * @param duration_complete_settings A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * @see {@link https://api.jquery.com/jQuery.speed/} - * @since 1.0 - * @since 1.1 - */ - speed(duration_complete_settings?: JQuery.Duration | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; - /** - * Remove the whitespace from the beginning and end of a string. - * - * @param str The string to trim. - * @see {@link https://api.jquery.com/jQuery.trim/} - * @since 1.0 - */ - trim(str: string): string; - /** - * Determine the internal JavaScript [[Class]] of an object. - * - * @param obj Object to get the internal JavaScript [[Class]] of. - * @see {@link https://api.jquery.com/jQuery.type/} - * @since 1.4.3 - */ - type(obj: any): 'array' | 'boolean' | 'date' | 'error' | 'function' | 'null' | 'number' | 'object' | 'regexp' | 'string' | 'symbol' | 'undefined'; - /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on - * arrays of DOM elements, not strings or numbers. - * - * @param array The Array of DOM elements. - * @see {@link https://api.jquery.com/jQuery.unique/} - * @since 1.1.3 - * @deprecated 3.0 - */ - unique(array: T[]): T[]; - /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on - * arrays of DOM elements, not strings or numbers. - * - * @param array The Array of DOM elements. - * @see {@link https://api.jquery.com/jQuery.uniqueSort/} - * @since 1.12-2.2 - */ - uniqueSort(array: T[]): T[]; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see {@link https://api.jquery.com/jQuery.when/} - * @since 1.5 - */ - when - (deferredT: JQuery.Promise | JQuery.Thenable | TR1, - deferredU: JQuery.Promise | JQuery.Thenable | UR1, - deferredV: JQuery.Promise | JQuery.Thenable | VR1): JQuery.Promise3; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see {@link https://api.jquery.com/jQuery.when/} - * @since 1.5 - */ - when - (deferredT: JQuery.Promise | JQuery.Thenable | TR1, - deferredU: JQuery.Promise | JQuery.Thenable | UR1): JQuery.Promise2; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see {@link https://api.jquery.com/jQuery.when/} - * @since 1.5 - */ - when - (deferredT: JQuery.Promise3 | - JQuery.Promise2): JQuery.Promise3; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see {@link https://api.jquery.com/jQuery.when/} - * @since 1.5 - */ - when(deferred: JQuery.Promise | JQuery.Thenable | TR1): JQuery.Promise; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @param deferreds Zero or more Thenable objects. - * @see {@link https://api.jquery.com/jQuery.when/} - * @since 1.5 - */ - when(...deferreds: Array | JQuery.Thenable | TR1>): JQuery.Promise; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @param deferreds Zero or more Thenable objects. - * @see {@link https://api.jquery.com/jQuery.when/} - * @since 1.5 - */ - when(...deferreds: any[]): JQuery.Promise; -} - declare namespace JQuery { type TypeOrArray = T | T[]; type Node = Element | Text | Comment; diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 35b91fe1d3..e5be26c558 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -1,5 +1,1322 @@ // tslint:disable:interface-name +function JQueryStatic() { + function type_assertion() { + const $Canvas = $ as JQueryStatic; + } + + function type_annotation() { + const jq: JQueryStatic = $; + } + + function call_signature() { + // $ExpectType JQuery + $('

    ', new Document()); + + // $ExpectType JQuery + $('

    ', { + class: 'my-div', + on: { + touchstart() { + // Do something + } + } + }); + + // $ExpectType JQuery + $('span', new HTMLElement()); + + // $ExpectType JQuery + $('span', new Document()); + + // $ExpectType JQuery + $('span', $('p')); + + // $ExpectType JQuery + $('span'); + + // $ExpectType JQuery + $('

    '); + + // $ExpectType JQuery + $(new HTMLElement()); + + // $ExpectType JQuery + $([new HTMLElement()]); + + // $ExpectType JQuery + $({ foo: 'bar', hello: 'world' }); + + // $ExpectType JQuery + $($('p')); + + // $ExpectType JQuery + $(function($) { + // $ExpectType Document + this; + // $ExpectType JQueryStatic + $; + }); + + // $ExpectType JQuery + $(); + } + + function Event() { + // $ExpectType EventStatic + $.Event; + } + + function cssHooks() { + // $ExpectType PlainObject> + $.cssHooks; + } + + function cssNumber() { + // $ExpectType PlainObject + $.cssNumber; + } + + function fn() { + // $ExpectType JQuery + $.fn; + } + + function fx() { + function interval() { + // $ExpectType number + $.fx.interval; + } + + function off() { + // $ExpectType boolean + $.fx.off; + } + + function step() { + // $ExpectType PlainObject> + $.fx.step; + } + } + + function ready() { + // $ExpectType Thenable> + $.ready; + } + + function support() { + // $ExpectType PlainObject + $.support; + } + + function valHooks() { + // $ExpectType PlainObject> + $.valHooks; + } + + function Callbacks() { + // $ExpectType Callbacks + $.Callbacks('once'); + + // $ExpectType Callbacks + $.Callbacks(); + } + + function Deferred() { + function call_signature() { + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + } + + function exceptionHook() { + $.Deferred.exceptionHook = undefined; + } + } + + function ajax() { + // $ExpectType jqXHR + $.ajax('url', { + cache: true + }); + } + + function ajaxPrefilter() { + // $ExpectType void + $.ajaxPrefilter('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + + return 'filtered'; + }); + + // $ExpectType void + $.ajaxPrefilter('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType void + $.ajaxPrefilter((options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + + return 'filtered'; + }); + + // $ExpectType void + $.ajaxPrefilter((options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + }); + } + + function ajaxSetup() { + // $ExpectType AjaxSettings + $.ajaxSetup({ + cache: true + }); + } + + function ajaxTransport() { + // $ExpectType void + $.ajaxTransport('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + + return { + send(headers, completeCallback) { + // $ExpectType PlainObject + headers; + // $ExpectType SuccessCallback + completeCallback; + }, + abort() { } + }; + }); + + // $ExpectType void + $.ajaxTransport('dataTypes', (options, originalOptions, jqXHR) => { + // $ExpectType AjaxSettings + options; + // $ExpectType AjaxSettings + originalOptions; + // $ExpectType jqXHR + jqXHR; + }); + } + + function contains() { + // $ExpectType boolean + $.contains(new HTMLElement(), new HTMLElement()); + } + + function css() { + // $ExpectType any + $.css(new HTMLElement(), {}); + } + + function data() { + // $ExpectType any + $.data(new HTMLElement(), 'myKey', undefined); + + // $ExpectType "myValue" + $.data(new HTMLElement(), 'myKey', 'myValue'); + + // $ExpectType any + $.data(new HTMLElement(), 'myKey'); + + // $ExpectType any + $.data(new HTMLElement()); + } + + function dequeue() { + // $ExpectType void + $.dequeue(new HTMLElement(), 'myQueue'); + + // $ExpectType void + $.dequeue(new HTMLElement()); + } + + function each() { + // $ExpectType ArrayLike + $.each(['myVal1', 'myVal2'], function(index, val) { + // $ExpectType string + this; + // $ExpectType number + index; + // $ExpectType string + val; + + return false; + }); + + // $ExpectType ArrayLike + $.each(['myVal1', 'myVal2'], function(index, val) { + // $ExpectType string + this; + // $ExpectType number + index; + // $ExpectType string + val; + + return 10; + }); + + // $ExpectType ArrayLike + $.each(['myVal1', 'myVal2'], function(index, val) { + // $ExpectType string + this; + // $ExpectType number + index; + // $ExpectType string + val; + }); + + // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } + $.each({ + myVal1: false, + myVal2: () => { + return 10; + }, + myVal3: 'myVal3' + }, function(propertyName, valueOfProperty) { + // $ExpectType string | boolean | (() => 10) + this; + // $ExpectType "myVal1" | "myVal2" | "myVal3" + propertyName; + // $ExpectType string | boolean | (() => 10) + valueOfProperty; + + return false; + }); + + // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } + $.each({ + myVal1: false, + myVal2: () => { + return 10; + }, + myVal3: 'myVal3' + }, function(propertyName, valueOfProperty) { + // $ExpectType string | boolean | (() => 10) + this; + // $ExpectType "myVal1" | "myVal2" | "myVal3" + propertyName; + // $ExpectType string | boolean | (() => 10) + valueOfProperty; + + return 10; + }); + + // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } + $.each({ + myVal1: false, + myVal2: () => { + return 10; + }, + myVal3: 'myVal3' + }, function(propertyName, valueOfProperty) { + // $ExpectType string | boolean | (() => 10) + this; + // $ExpectType "myVal1" | "myVal2" | "myVal3" + propertyName; + // $ExpectType string | boolean | (() => 10) + valueOfProperty; + }); + } + + function error() { + jQuery.error = console.error; + } + + function escapeSelector() { + // $ExpectType string + $.escapeSelector('span'); + } + + function extend() { + const t = { name: 'myObj' }; + const u = new EventTarget(); + const v = new Node(); + const w = new Comment(); + const x = new Text(); + const y = new Element(); + const z = new HTMLElement(); + const a = new SVGElement(); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element & HTMLElement + $.extend(true, t, u, v, w, x, y, z); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element + $.extend(true, t, u, v, w, x, y); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text + $.extend(true, t, u, v, w, x); + + // $ExpectType { name: string; } & EventTarget & Node & Comment + $.extend(true, t, u, v, w); + + // $ExpectType { name: string; } & EventTarget & Node + $.extend(true, t, u, v); + + // $ExpectType { name: string; } & EventTarget + $.extend(true, t, u); + + // $ExpectType any + $.extend(true, t, u, v, w, x, y, z, a); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element & HTMLElement + $.extend(t, u, v, w, x, y, z); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element + $.extend(t, u, v, w, x, y); + + // $ExpectType { name: string; } & EventTarget & Node & Comment & Text + $.extend(t, u, v, w, x); + + // $ExpectType { name: string; } & EventTarget & Node & Comment + $.extend(t, u, v, w); + + // $ExpectType { name: string; } & EventTarget & Node + $.extend(t, u, v); + + // $ExpectType { name: string; } & EventTarget + $.extend(t, u); + + // $ExpectType any + $.extend(t, u, v, w, x, y, z, a); + } + + function get() { + // $ExpectType jqXHR + $.get('url', { myData: 'myData' }, (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', 'myData', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', { myData: 'myData' }, null, 'script'); + + // $ExpectType jqXHR + $.get('url', 'myData', null, 'script'); + + // $ExpectType jqXHR + $.get('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', null, 'script'); + + // $ExpectType jqXHR + $.get('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.get('url', { myData: 'myData' }); + + // $ExpectType jqXHR + $.get('url', 'myData'); + + // $ExpectType jqXHR + $.get('url'); + + // $ExpectType jqXHR + $.get({ url: 'url' }); + + // $ExpectType jqXHR + $.get(); + } + + function getJSON() { + // $ExpectType jqXHR + $.getJSON('url', { myVal1: 'myVal1' }, (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.getJSON('url', 'myVal1', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.getJSON('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.getJSON('url', { myVal1: 'myVal1' }); + + // $ExpectType jqXHR + $.getJSON('url', 'myVal1'); + + // $ExpectType jqXHR + $.getJSON('url'); + } + + function getScript() { + // $ExpectType jqXHR + $.getScript('url', (data, textStatus, jqXHR) => { + // $ExpectType string | undefined + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + } + + function globalEval() { + // $ExpectType void + $.globalEval('throw new Error();'); + } + + function grep() { + // $ExpectType string[] + $.grep(['myVal1', 'myVal2'], (elementOfArray, indexInArray) => { + // $ExpectType string + elementOfArray; + // $ExpectType number + indexInArray; + + return true; + }, true); + + // $ExpectType string[] + $.grep(['myVal1', 'myVal2'], (elementOfArray, indexInArray) => { + // $ExpectType string + elementOfArray; + // $ExpectType number + indexInArray; + + return true; + }); + } + + function hasData() { + // $ExpectType boolean + $.hasData(new HTMLElement()); + } + + function holdReady() { + // $ExpectType void + $.holdReady(true); + } + + function htmlPrefilter() { + // $ExpectType string + $.htmlPrefilter(''); + } + + function inArray() { + // $ExpectType number + $.inArray(1, [1, 2], 1); + + // $ExpectType number + $.inArray(1, [1, 2]); + } + + function isArray() { + function type_guard(obj: object) { + if ($.isArray(obj)) { + // $ExpectType any[] + obj; + } + } + } + + function isEmptyObject() { + function type_guard(obj: object) { + if ($.isEmptyObject(obj)) { + // $ExpectType {} + obj; + } + } + } + + function isFunction() { + function type_guard(obj: object) { + if ($.isFunction(obj)) { + // $ExpectType Function + obj; + } + } + } + + function isNumeric() { + function type_guard(obj: boolean) { + if ($.isNumeric(obj)) { + // $ExpectType (true & number) | (false & number) + obj; + } + } + } + + function isPlainObject() { + function type_guard(obj: object) { + if ($.isPlainObject(obj)) { + // $ExpectType PlainObject + obj; + } + } + } + + function isWindow() { + function type_guard(obj: object) { + if ($.isWindow(obj)) { + // $ExpectType Window + obj; + } + } + } + + function isXMLDoc() { + // $ExpectType boolean + $.isXMLDoc(new Node()); + } + + function makeArray() { + // $ExpectType number[] + $.makeArray([1, 2]); + } + + function map() { + // $ExpectType number[] + $.map([1, 2, 3], (elementOfArray, indexInArray) => { + // $ExpectType number + elementOfArray; + // $ExpectType number + indexInArray; + + return 200 + 10; + }); + + // $ExpectType (false | 1)[] + $.map({ + myProp: true, + name: 'Rogers', + }, (propertyOfObject, key) => { + // $ExpectType string | boolean + propertyOfObject; + // $ExpectType "myProp" | "name" + key; + + switch (key) { + case 'myProp': + return 1; + case 'name': + return false; + } + }); + } + + function merge() { + // $ExpectType (string | number)[] + $.merge([1, 2, 3], ['myVal1', 'myVal2']); + } + + function noConflict() { + // $ExpectType JQueryStatic + $.noConflict(true); + + // $ExpectType JQueryStatic + $.noConflict(); + } + + function noop() { + // $ExpectType undefined + $.noop(); + } + + function now() { + // $ExpectType number + $.now(); + } + + function param() { + // $ExpectType string + $.param([true, 20], true); + + // $ExpectType string + $.param({ + myVal1: true, + myVal2: 20 + }, true); + + // $ExpectType string + $.param($('input'), true); + + // $ExpectType string + $.param([true, 20]); + + // $ExpectType string + $.param({ + myVal1: true, + myVal2: 20 + }); + + // $ExpectType string + $.param($('input')); + } + + function parseHTML() { + // $ExpectType Node[] + $.parseHTML('', document, true); + + // $ExpectType Node[] + $.parseHTML('', null, true); + + // $ExpectType Node[] + $.parseHTML('', undefined, true); + + // $ExpectType Node[] + $.parseHTML('', document); + + // $ExpectType Node[] + $.parseHTML('', null); + + // $ExpectType Node[] + $.parseHTML('', undefined); + + // $ExpectType Node[] + $.parseHTML('', false); + + // $ExpectType Node[] + $.parseHTML(''); + } + + function parseJSON() { + // $ExpectType any + $.parseJSON('{}'); + } + + function parseXML() { + // $ExpectType XMLDocument + $.parseXML(''); + } + + function post() { + // $ExpectType jqXHR + $.post('url', { myData: 'myData' }, (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', 'myData', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', { myData: 'myData' }, null, 'script'); + + // $ExpectType jqXHR + $.post('url', 'myData', null, 'script'); + + // $ExpectType jqXHR + $.post('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', null, 'script'); + + // $ExpectType jqXHR + $.post('url', (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, 'script'); + + // $ExpectType jqXHR + $.post('url', { myData: 'myData' }); + + // $ExpectType jqXHR + $.post('url', 'myData'); + + // $ExpectType jqXHR + $.post('url'); + + // $ExpectType jqXHR + $.post({ url: 'url' }); + + // $ExpectType jqXHR + $.post(); + } + + function proxy() { + // $ExpectType Function + $.proxy($.noop, {}, 1, 2); + + // $ExpectType Function + $.proxy($.noop, {}); + + // $ExpectType Function + $.proxy({ myFunc: $.noop }, 'myFunc', 1, 2); + + // $ExpectType Function + $.proxy({ myFunc: $.noop }, 'myFunc'); + } + + function queue() { + // $ExpectType Queue + $.queue(new HTMLElement(), 'myQueue', function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }); + + // $ExpectType Queue + $.queue(new HTMLElement(), 'myQueue', [function(next) { + // $ExpectType HTMLElement + this; + // $ExpectType () => void + next; + }]); + + // $ExpectType Queue + $.queue(new HTMLElement(), 'myQueue'); + + // $ExpectType Queue + $.queue(new HTMLElement()); + } + + function readyException() { + jQuery.readyException = (error) => { + console.error(error); + }; + } + + function removeData() { + // $ExpectType void + $.removeData(new HTMLElement(), 'test1'); + + // $ExpectType void + $.removeData(new HTMLElement()); + } + + function speed() { + // $ExpectType EffectsOptions + $.speed(5000, 'linear', function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType EffectsOptions + $.speed(5000, 'linear'); + + // $ExpectType EffectsOptions + $.speed(5000, function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType EffectsOptions + $.speed(5000); + + // $ExpectType EffectsOptions + $.speed(function() { + // $ExpectType HTMLElement + this; + }); + + // $ExpectType EffectsOptions + $.speed({ + duration: 5000, + easing: 'linear', + complete() { + // $ExpectType HTMLElement + this; + } + }); + + // $ExpectType EffectsOptions + $.speed(); + } + + function trim() { + // $ExpectType string + $.trim('myStr'); + } + + function type() { + // $ExpectType "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" | "error" | "array" | "date" | "null" | "regexp" + $.type({}); + } + + function unique() { + // $ExpectType HTMLElement[] + $.unique([new HTMLElement()]); + } + + function uniqueSort() { + // $ExpectType HTMLElement[] + $.uniqueSort([new HTMLElement()]); + } + + function when() { + interface I1 { kind: 'I1'; } + interface I2 { kind: 'I2'; } + interface I3 { kind: 'I3'; } + interface I4 { kind: 'I4'; } + interface I5 { kind: 'I5'; } + interface I6 { kind: 'I6'; } + interface I7 { kind: 'I7'; } + interface I8 { kind: 'I8'; } + interface I9 { kind: 'I9'; } + + function Promise3() { + const t = $.ajax() as JQuery.jqXHR; + const u = $.ajax() as JQuery.jqXHR; + const v = $.ajax() as JQuery.jqXHR; + + // // 3 parameters + // { + // const w = $.when(t, u, v); + // + // w.then((a, b, c) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType SuccessTextStatus + // a[2]; // $ExpectType jqXHR + // b[0]; // $ExpectType number + // b[1]; // $ExpectType SuccessTextStatus + // b[2]; // $ExpectType jqXHR + // c[0]; // $ExpectType boolean + // c[1]; // $ExpectType SuccessTextStatus + // c[2]; // $ExpectType jqXHR + // }, (a, b, c) => { + // a[0]; // $ExpectType jqXHR + // a[1]; // $ExpectType ErrorTextStatus + // a[2]; // $ExpectType string + // b[0]; // $ExpectType jqXHR + // b[1]; // $ExpectType ErrorTextStatus + // b[2]; // $ExpectType string + // c[0]; // $ExpectType jqXHR + // c[1]; // $ExpectType ErrorTextStatus + // c[2]; // $ExpectType string + // }, (a, b, c) => { + // a; // $ExpectType never + // b; // $ExpectType never + // c; // $ExpectType never + // }); + // } + // + // // 2 parameters + // { + // const w = $.when(t, u); + // + // w.then((a, b) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType SuccessTextStatus + // a[2]; // $ExpectType jqXHR + // b[0]; // $ExpectType number + // b[1]; // $ExpectType SuccessTextStatus + // b[2]; // $ExpectType jqXHR + // }, (a, b) => { + // a[0]; // $ExpectType jqXHR + // a[1]; // $ExpectType ErrorTextStatus + // a[2]; // $ExpectType string + // b[0]; // $ExpectType jqXHR + // b[1]; // $ExpectType ErrorTextStatus + // b[2]; // $ExpectType string + // }, (a, b) => { + // a; // $ExpectType never + // b; // $ExpectType never + // }); + // } + + // 1 parameter + { + const w = $.when(t); + + w.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType SuccessTextStatus + c; // $ExpectType jqXHR + }, (a, b, c) => { + a; // $ExpectType jqXHR + b; // $ExpectType ErrorTextStatus + c; // $ExpectType string + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + } + + function Promise2() { + const t: JQuery.Promise2 = {} as any; + const u: JQuery.Promise2 = {} as any; + const v: JQuery.Promise2 = {} as any; + + // // 3 parameters + // { + // const w = $.when(t, u, v); + // + // w.then((a, b, c) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType boolean + // b[0]; // $ExpectType string + // b[1]; // $ExpectType boolean + // c[0]; // $ExpectType string + // c[1]; // $ExpectType boolean + // }, (a, b, c) => { + // a[0]; // $ExpectType Error + // a[1]; // $ExpectType any + // b[0]; // $ExpectType Error + // b[1]; // $ExpectType any + // c[0]; // $ExpectType Error + // c[1]; // $ExpectType any + // }, (a, b, c) => { + // a; // $ExpectType never + // b; // $ExpectType never + // c; // $ExpectType never + // }); + // } + // + // // 2 parameters + // { + // const w = $.when(t, u); + // + // w.then((a, b) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType boolean + // b[0]; // $ExpectType string + // b[1]; // $ExpectType boolean + // }, (a, b) => { + // a[0]; // $ExpectType Error + // a[1]; // $ExpectType any + // b[0]; // $ExpectType Error + // b[1]; // $ExpectType any + // }, (a, b) => { + // a; // $ExpectType never + // b; // $ExpectType never + // }); + // } + + // 1 parameter + { + const w = $.when(t); + + w.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType boolean + }, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType any + }, (a, b) => { + a; // $ExpectType never + b; // $ExpectType never + }); + } + } + + function Promise() { + const p1: JQuery.Promise = {} as any; + const p2: JQuery.Promise = {} as any; + const p3: JQuery.Promise = {} as any; + + // 3 parameters + { + const w = $.when(p1, p2, p3); + + w.then((a, b, c) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + c; // $ExpectType I3 + }, (a, b, c) => { + a; // $ExpectType I2 + b; // $ExpectType I3 + c; // $ExpectType I4 + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // 2 parameters + { + const w = $.when(p1, p2); + + w.then((a, b) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + }, (a, b) => { + a; // $ExpectType I2 + b; // $ExpectType I3 + }, (a, b) => { + a; // $ExpectType never + b; // $ExpectType never + }); + } + + // 1 parameter + { + const w = $.when(p1); + + w.then(a => { + a; // $ExpectType I1 + }, a => { + a; // $ExpectType I2 + }, a => { + a; // $ExpectType never + }); + } + } + + function Thenable() { + const t1: JQuery.Thenable = {} as any; + const t2: JQuery.Thenable = {} as any; + const t3: JQuery.Thenable = {} as any; + + // 3 parameters + { + const w = $.when(t1, t2, t3); + + w.then((a, b, c) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + c; // $ExpectType I3 + }, (a, b, c) => { + a; // $ExpectType any + b; // $ExpectType any + c; // $ExpectType any + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // 2 parameters + { + const w = $.when(t1, t2); + + w.then((a, b) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + }, (a, b) => { + a; // $ExpectType any + b; // $ExpectType any + }, (a, b) => { + a; // $ExpectType never + b; // $ExpectType never + }); + } + + // 1 parameter + { + const w = $.when(t1); + + w.then(a => { + a; // $ExpectType I1 + }, a => { + a; // $ExpectType any + }, a => { + a; // $ExpectType never + }); + } + } + + function value() { + const w = $.when('myVal1'); + + w.then(a => { + a; // $ExpectType string + }); + } + + function Zero() { + const w = $.when(); + + w.then(a => { + a; // $ExpectType never + }, a => { + a; // $ExpectType never + }, a => { + a; // $ExpectType never + }); + } + + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/2725 + function issue_2725() { + function first() { + return $.when('1'); + } + + $.when().then(() => { + return first(); + }).then((value) => { + value; // $ExpectType string + }); + } + + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/10159 + function issue_10159() { + interface One { result: number; } + interface Two { Result: number; } + interface Three { TheResult: number; } + + class AsyncRunner { + Run(): void { + const task1 = this.runTask1(); + const task2 = this.runTask2(); + const task3 = this.runTask3(); + + $.when(task1, task2, task3) + .then((r1, r2, r3) => { + r1; // $ExpectType One + r2; // $ExpectType Two + r3; // $ExpectType Three + }); + } + + runTask1() { + let dfd = $.Deferred(); + console.log('Task 1'); + setTimeout(() => { dfd.resolve({ result: 1 }); }, Math.floor(400 + Math.random() * 2000)); + return dfd.promise(); + } + + runTask2() { + let dfd = $.Deferred(); + console.log('Task 2'); + setTimeout(() => { dfd.resolve({ Result: 2 }); }, Math.floor(400 + Math.random() * 2000)); + return dfd.promise(); + } + + runTask3() { + let dfd = $.Deferred(); + console.log('Task 3'); + setTimeout(() => { dfd.resolve({ TheResult: 3 }); }, Math.floor(400 + Math.random() * 2000)); + return dfd.promise(); + } + } + } + } +} + function JQuery() { function type_assertion() { const $el = $(document.createElement('canvas')); @@ -3471,1323 +4788,6 @@ function JQuery() { } } -function JQueryStatic() { - function type_assertion() { - const $Canvas = $ as JQueryStatic; - } - - function type_annotation() { - const jq: JQueryStatic = $; - } - - function call_signature() { - // $ExpectType JQuery - $('

    ', new Document()); - - // $ExpectType JQuery - $('

    ', { - class: 'my-div', - on: { - touchstart() { - // Do something - } - } - }); - - // $ExpectType JQuery - $('span', new HTMLElement()); - - // $ExpectType JQuery - $('span', new Document()); - - // $ExpectType JQuery - $('span', $('p')); - - // $ExpectType JQuery - $('span'); - - // $ExpectType JQuery - $('

    '); - - // $ExpectType JQuery - $(new HTMLElement()); - - // $ExpectType JQuery - $([new HTMLElement()]); - - // $ExpectType JQuery - $({ foo: 'bar', hello: 'world' }); - - // $ExpectType JQuery - $($('p')); - - // $ExpectType JQuery - $(function($) { - // $ExpectType Document - this; - // $ExpectType JQueryStatic - $; - }); - - // $ExpectType JQuery - $(); - } - - function Event() { - // $ExpectType EventStatic - $.Event; - } - - function cssHooks() { - // $ExpectType PlainObject> - $.cssHooks; - } - - function cssNumber() { - // $ExpectType PlainObject - $.cssNumber; - } - - function fn() { - // $ExpectType JQuery - $.fn; - } - - function fx() { - function interval() { - // $ExpectType number - $.fx.interval; - } - - function off() { - // $ExpectType boolean - $.fx.off; - } - - function step() { - // $ExpectType PlainObject> - $.fx.step; - } - } - - function ready() { - // $ExpectType Thenable> - $.ready; - } - - function support() { - // $ExpectType PlainObject - $.support; - } - - function valHooks() { - // $ExpectType PlainObject> - $.valHooks; - } - - function Callbacks() { - // $ExpectType Callbacks - $.Callbacks('once'); - - // $ExpectType Callbacks - $.Callbacks(); - } - - function Deferred() { - function call_signature() { - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - } - - function exceptionHook() { - $.Deferred.exceptionHook = undefined; - } - } - - function ajax() { - // $ExpectType jqXHR - $.ajax('url', { - cache: true - }); - } - - function ajaxPrefilter() { - // $ExpectType void - $.ajaxPrefilter('dataTypes', (options, originalOptions, jqXHR) => { - // $ExpectType AjaxSettings - options; - // $ExpectType AjaxSettings - originalOptions; - // $ExpectType jqXHR - jqXHR; - - return 'filtered'; - }); - - // $ExpectType void - $.ajaxPrefilter('dataTypes', (options, originalOptions, jqXHR) => { - // $ExpectType AjaxSettings - options; - // $ExpectType AjaxSettings - originalOptions; - // $ExpectType jqXHR - jqXHR; - }); - - // $ExpectType void - $.ajaxPrefilter((options, originalOptions, jqXHR) => { - // $ExpectType AjaxSettings - options; - // $ExpectType AjaxSettings - originalOptions; - // $ExpectType jqXHR - jqXHR; - - return 'filtered'; - }); - - // $ExpectType void - $.ajaxPrefilter((options, originalOptions, jqXHR) => { - // $ExpectType AjaxSettings - options; - // $ExpectType AjaxSettings - originalOptions; - // $ExpectType jqXHR - jqXHR; - }); - } - - function ajaxSetup() { - // $ExpectType AjaxSettings - $.ajaxSetup({ - cache: true - }); - } - - function ajaxTransport() { - // $ExpectType void - $.ajaxTransport('dataTypes', (options, originalOptions, jqXHR) => { - // $ExpectType AjaxSettings - options; - // $ExpectType AjaxSettings - originalOptions; - // $ExpectType jqXHR - jqXHR; - - return { - send(headers, completeCallback) { - // $ExpectType PlainObject - headers; - // $ExpectType SuccessCallback - completeCallback; - }, - abort() { } - }; - }); - - // $ExpectType void - $.ajaxTransport('dataTypes', (options, originalOptions, jqXHR) => { - // $ExpectType AjaxSettings - options; - // $ExpectType AjaxSettings - originalOptions; - // $ExpectType jqXHR - jqXHR; - }); - } - - function contains() { - // $ExpectType boolean - $.contains(new HTMLElement(), new HTMLElement()); - } - - function css() { - // $ExpectType any - $.css(new HTMLElement(), {}); - } - - function data() { - // $ExpectType any - $.data(new HTMLElement(), 'myKey', undefined); - - // $ExpectType "myValue" - $.data(new HTMLElement(), 'myKey', 'myValue'); - - // $ExpectType any - $.data(new HTMLElement(), 'myKey'); - - // $ExpectType any - $.data(new HTMLElement()); - } - - function dequeue() { - // $ExpectType void - $.dequeue(new HTMLElement(), 'myQueue'); - - // $ExpectType void - $.dequeue(new HTMLElement()); - } - - function each() { - // $ExpectType ArrayLike - $.each(['myVal1', 'myVal2'], function(index, val) { - // $ExpectType string - this; - // $ExpectType number - index; - // $ExpectType string - val; - - return false; - }); - - // $ExpectType ArrayLike - $.each(['myVal1', 'myVal2'], function(index, val) { - // $ExpectType string - this; - // $ExpectType number - index; - // $ExpectType string - val; - - return 10; - }); - - // $ExpectType ArrayLike - $.each(['myVal1', 'myVal2'], function(index, val) { - // $ExpectType string - this; - // $ExpectType number - index; - // $ExpectType string - val; - }); - - // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } - $.each({ - myVal1: false, - myVal2: () => { - return 10; - }, - myVal3: 'myVal3' - }, function(propertyName, valueOfProperty) { - // $ExpectType string | boolean | (() => 10) - this; - // $ExpectType "myVal1" | "myVal2" | "myVal3" - propertyName; - // $ExpectType string | boolean | (() => 10) - valueOfProperty; - - return false; - }); - - // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } - $.each({ - myVal1: false, - myVal2: () => { - return 10; - }, - myVal3: 'myVal3' - }, function(propertyName, valueOfProperty) { - // $ExpectType string | boolean | (() => 10) - this; - // $ExpectType "myVal1" | "myVal2" | "myVal3" - propertyName; - // $ExpectType string | boolean | (() => 10) - valueOfProperty; - - return 10; - }); - - // $ExpectType { myVal1: boolean; myVal2: () => 10; myVal3: string; } - $.each({ - myVal1: false, - myVal2: () => { - return 10; - }, - myVal3: 'myVal3' - }, function(propertyName, valueOfProperty) { - // $ExpectType string | boolean | (() => 10) - this; - // $ExpectType "myVal1" | "myVal2" | "myVal3" - propertyName; - // $ExpectType string | boolean | (() => 10) - valueOfProperty; - }); - } - - function error() { - jQuery.error = console.error; - } - - function escapeSelector() { - // $ExpectType string - $.escapeSelector('span'); - } - - function extend() { - const t = { name: 'myObj' }; - const u = new EventTarget(); - const v = new Node(); - const w = new Comment(); - const x = new Text(); - const y = new Element(); - const z = new HTMLElement(); - const a = new SVGElement(); - - // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element & HTMLElement - $.extend(true, t, u, v, w, x, y, z); - - // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element - $.extend(true, t, u, v, w, x, y); - - // $ExpectType { name: string; } & EventTarget & Node & Comment & Text - $.extend(true, t, u, v, w, x); - - // $ExpectType { name: string; } & EventTarget & Node & Comment - $.extend(true, t, u, v, w); - - // $ExpectType { name: string; } & EventTarget & Node - $.extend(true, t, u, v); - - // $ExpectType { name: string; } & EventTarget - $.extend(true, t, u); - - // $ExpectType any - $.extend(true, t, u, v, w, x, y, z, a); - - // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element & HTMLElement - $.extend(t, u, v, w, x, y, z); - - // $ExpectType { name: string; } & EventTarget & Node & Comment & Text & Element - $.extend(t, u, v, w, x, y); - - // $ExpectType { name: string; } & EventTarget & Node & Comment & Text - $.extend(t, u, v, w, x); - - // $ExpectType { name: string; } & EventTarget & Node & Comment - $.extend(t, u, v, w); - - // $ExpectType { name: string; } & EventTarget & Node - $.extend(t, u, v); - - // $ExpectType { name: string; } & EventTarget - $.extend(t, u); - - // $ExpectType any - $.extend(t, u, v, w, x, y, z, a); - } - - function get() { - // $ExpectType jqXHR - $.get('url', { myData: 'myData' }, (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.get('url', 'myData', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.get('url', { myData: 'myData' }, null, 'script'); - - // $ExpectType jqXHR - $.get('url', 'myData', null, 'script'); - - // $ExpectType jqXHR - $.get('url', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.get('url', null, 'script'); - - // $ExpectType jqXHR - $.get('url', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.get('url', { myData: 'myData' }); - - // $ExpectType jqXHR - $.get('url', 'myData'); - - // $ExpectType jqXHR - $.get('url'); - - // $ExpectType jqXHR - $.get({ url: 'url' }); - - // $ExpectType jqXHR - $.get(); - } - - function getJSON() { - // $ExpectType jqXHR - $.getJSON('url', { myVal1: 'myVal1' }, (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }); - - // $ExpectType jqXHR - $.getJSON('url', 'myVal1', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }); - - // $ExpectType jqXHR - $.getJSON('url', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }); - - // $ExpectType jqXHR - $.getJSON('url', { myVal1: 'myVal1' }); - - // $ExpectType jqXHR - $.getJSON('url', 'myVal1'); - - // $ExpectType jqXHR - $.getJSON('url'); - } - - function getScript() { - // $ExpectType jqXHR - $.getScript('url', (data, textStatus, jqXHR) => { - // $ExpectType string | undefined - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }); - } - - function globalEval() { - // $ExpectType void - $.globalEval('throw new Error();'); - } - - function grep() { - // $ExpectType string[] - $.grep(['myVal1', 'myVal2'], (elementOfArray, indexInArray) => { - // $ExpectType string - elementOfArray; - // $ExpectType number - indexInArray; - - return true; - }, true); - - // $ExpectType string[] - $.grep(['myVal1', 'myVal2'], (elementOfArray, indexInArray) => { - // $ExpectType string - elementOfArray; - // $ExpectType number - indexInArray; - - return true; - }); - } - - function hasData() { - // $ExpectType boolean - $.hasData(new HTMLElement()); - } - - function holdReady() { - // $ExpectType void - $.holdReady(true); - } - - function htmlPrefilter() { - // $ExpectType string - $.htmlPrefilter(''); - } - - function inArray() { - // $ExpectType number - $.inArray(1, [1, 2], 1); - - // $ExpectType number - $.inArray(1, [1, 2]); - } - - function isArray() { - function type_guard(obj: object) { - if ($.isArray(obj)) { - // $ExpectType any[] - obj; - } - } - } - - function isEmptyObject() { - function type_guard(obj: object) { - if ($.isEmptyObject(obj)) { - // $ExpectType {} - obj; - } - } - } - - function isFunction() { - function type_guard(obj: object) { - if ($.isFunction(obj)) { - // $ExpectType Function - obj; - } - } - } - - function isNumeric() { - function type_guard(obj: boolean) { - if ($.isNumeric(obj)) { - // $ExpectType (true & number) | (false & number) - obj; - } - } - } - - function isPlainObject() { - function type_guard(obj: object) { - if ($.isPlainObject(obj)) { - // $ExpectType PlainObject - obj; - } - } - } - - function isWindow() { - function type_guard(obj: object) { - if ($.isWindow(obj)) { - // $ExpectType Window - obj; - } - } - } - - function isXMLDoc() { - // $ExpectType boolean - $.isXMLDoc(new Node()); - } - - function makeArray() { - // $ExpectType number[] - $.makeArray([1, 2]); - } - - function map() { - // $ExpectType number[] - $.map([1, 2, 3], (elementOfArray, indexInArray) => { - // $ExpectType number - elementOfArray; - // $ExpectType number - indexInArray; - - return 200 + 10; - }); - - // $ExpectType (false | 1)[] - $.map({ - myProp: true, - name: 'Rogers', - }, (propertyOfObject, key) => { - // $ExpectType string | boolean - propertyOfObject; - // $ExpectType "myProp" | "name" - key; - - switch (key) { - case 'myProp': - return 1; - case 'name': - return false; - } - }); - } - - function merge() { - // $ExpectType (string | number)[] - $.merge([1, 2, 3], ['myVal1', 'myVal2']); - } - - function noConflict() { - // $ExpectType JQueryStatic - $.noConflict(true); - - // $ExpectType JQueryStatic - $.noConflict(); - } - - function noop() { - // $ExpectType undefined - $.noop(); - } - - function now() { - // $ExpectType number - $.now(); - } - - function param() { - // $ExpectType string - $.param([true, 20], true); - - // $ExpectType string - $.param({ - myVal1: true, - myVal2: 20 - }, true); - - // $ExpectType string - $.param($('input'), true); - - // $ExpectType string - $.param([true, 20]); - - // $ExpectType string - $.param({ - myVal1: true, - myVal2: 20 - }); - - // $ExpectType string - $.param($('input')); - } - - function parseHTML() { - // $ExpectType Node[] - $.parseHTML('', document, true); - - // $ExpectType Node[] - $.parseHTML('', null, true); - - // $ExpectType Node[] - $.parseHTML('', undefined, true); - - // $ExpectType Node[] - $.parseHTML('', document); - - // $ExpectType Node[] - $.parseHTML('', null); - - // $ExpectType Node[] - $.parseHTML('', undefined); - - // $ExpectType Node[] - $.parseHTML('', false); - - // $ExpectType Node[] - $.parseHTML(''); - } - - function parseJSON() { - // $ExpectType any - $.parseJSON('{}'); - } - - function parseXML() { - // $ExpectType XMLDocument - $.parseXML(''); - } - - function post() { - // $ExpectType jqXHR - $.post('url', { myData: 'myData' }, (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.post('url', 'myData', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.post('url', { myData: 'myData' }, null, 'script'); - - // $ExpectType jqXHR - $.post('url', 'myData', null, 'script'); - - // $ExpectType jqXHR - $.post('url', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.post('url', null, 'script'); - - // $ExpectType jqXHR - $.post('url', (data, textStatus, jqXHR) => { - // $ExpectType any - data; - // $ExpectType SuccessTextStatus - textStatus; - // $ExpectType jqXHR - jqXHR; - }, 'script'); - - // $ExpectType jqXHR - $.post('url', { myData: 'myData' }); - - // $ExpectType jqXHR - $.post('url', 'myData'); - - // $ExpectType jqXHR - $.post('url'); - - // $ExpectType jqXHR - $.post({ url: 'url' }); - - // $ExpectType jqXHR - $.post(); - } - - function proxy() { - // $ExpectType Function - $.proxy($.noop, {}, 1, 2); - - // $ExpectType Function - $.proxy($.noop, {}); - - // $ExpectType Function - $.proxy({ myFunc: $.noop }, 'myFunc', 1, 2); - - // $ExpectType Function - $.proxy({ myFunc: $.noop }, 'myFunc'); - } - - function queue() { - // $ExpectType Queue - $.queue(new HTMLElement(), 'myQueue', function(next) { - // $ExpectType HTMLElement - this; - // $ExpectType () => void - next; - }); - - // $ExpectType Queue - $.queue(new HTMLElement(), 'myQueue', [function(next) { - // $ExpectType HTMLElement - this; - // $ExpectType () => void - next; - }]); - - // $ExpectType Queue - $.queue(new HTMLElement(), 'myQueue'); - - // $ExpectType Queue - $.queue(new HTMLElement()); - } - - function readyException() { - jQuery.readyException = (error) => { - console.error(error); - }; - } - - function removeData() { - // $ExpectType void - $.removeData(new HTMLElement(), 'test1'); - - // $ExpectType void - $.removeData(new HTMLElement()); - } - - function speed() { - // $ExpectType EffectsOptions - $.speed(5000, 'linear', function() { - // $ExpectType HTMLElement - this; - }); - - // $ExpectType EffectsOptions - $.speed(5000, 'linear'); - - // $ExpectType EffectsOptions - $.speed(5000, function() { - // $ExpectType HTMLElement - this; - }); - - // $ExpectType EffectsOptions - $.speed(5000); - - // $ExpectType EffectsOptions - $.speed(function() { - // $ExpectType HTMLElement - this; - }); - - // $ExpectType EffectsOptions - $.speed({ - duration: 5000, - easing: 'linear', - complete() { - // $ExpectType HTMLElement - this; - } - }); - - // $ExpectType EffectsOptions - $.speed(); - } - - function trim() { - // $ExpectType string - $.trim('myStr'); - } - - function type() { - // $ExpectType "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" | "error" | "array" | "date" | "null" | "regexp" - $.type({}); - } - - function unique() { - // $ExpectType HTMLElement[] - $.unique([new HTMLElement()]); - } - - function uniqueSort() { - // $ExpectType HTMLElement[] - $.uniqueSort([new HTMLElement()]); - } - - function when() { - interface I1 { kind: 'I1'; } - interface I2 { kind: 'I2'; } - interface I3 { kind: 'I3'; } - interface I4 { kind: 'I4'; } - interface I5 { kind: 'I5'; } - interface I6 { kind: 'I6'; } - interface I7 { kind: 'I7'; } - interface I8 { kind: 'I8'; } - interface I9 { kind: 'I9'; } - - function Promise3() { - const t = $.ajax() as JQuery.jqXHR; - const u = $.ajax() as JQuery.jqXHR; - const v = $.ajax() as JQuery.jqXHR; - - // // 3 parameters - // { - // const w = $.when(t, u, v); - // - // w.then((a, b, c) => { - // a[0]; // $ExpectType string - // a[1]; // $ExpectType SuccessTextStatus - // a[2]; // $ExpectType jqXHR - // b[0]; // $ExpectType number - // b[1]; // $ExpectType SuccessTextStatus - // b[2]; // $ExpectType jqXHR - // c[0]; // $ExpectType boolean - // c[1]; // $ExpectType SuccessTextStatus - // c[2]; // $ExpectType jqXHR - // }, (a, b, c) => { - // a[0]; // $ExpectType jqXHR - // a[1]; // $ExpectType ErrorTextStatus - // a[2]; // $ExpectType string - // b[0]; // $ExpectType jqXHR - // b[1]; // $ExpectType ErrorTextStatus - // b[2]; // $ExpectType string - // c[0]; // $ExpectType jqXHR - // c[1]; // $ExpectType ErrorTextStatus - // c[2]; // $ExpectType string - // }, (a, b, c) => { - // a; // $ExpectType never - // b; // $ExpectType never - // c; // $ExpectType never - // }); - // } - // - // // 2 parameters - // { - // const w = $.when(t, u); - // - // w.then((a, b) => { - // a[0]; // $ExpectType string - // a[1]; // $ExpectType SuccessTextStatus - // a[2]; // $ExpectType jqXHR - // b[0]; // $ExpectType number - // b[1]; // $ExpectType SuccessTextStatus - // b[2]; // $ExpectType jqXHR - // }, (a, b) => { - // a[0]; // $ExpectType jqXHR - // a[1]; // $ExpectType ErrorTextStatus - // a[2]; // $ExpectType string - // b[0]; // $ExpectType jqXHR - // b[1]; // $ExpectType ErrorTextStatus - // b[2]; // $ExpectType string - // }, (a, b) => { - // a; // $ExpectType never - // b; // $ExpectType never - // }); - // } - - // 1 parameter - { - const w = $.when(t); - - w.then((a, b, c) => { - a; // $ExpectType string - b; // $ExpectType SuccessTextStatus - c; // $ExpectType jqXHR - }, (a, b, c) => { - a; // $ExpectType jqXHR - b; // $ExpectType ErrorTextStatus - c; // $ExpectType string - }, (a, b, c) => { - a; // $ExpectType never - b; // $ExpectType never - c; // $ExpectType never - }); - } - } - - function Promise2() { - const t: JQuery.Promise2 = {} as any; - const u: JQuery.Promise2 = {} as any; - const v: JQuery.Promise2 = {} as any; - - // // 3 parameters - // { - // const w = $.when(t, u, v); - // - // w.then((a, b, c) => { - // a[0]; // $ExpectType string - // a[1]; // $ExpectType boolean - // b[0]; // $ExpectType string - // b[1]; // $ExpectType boolean - // c[0]; // $ExpectType string - // c[1]; // $ExpectType boolean - // }, (a, b, c) => { - // a[0]; // $ExpectType Error - // a[1]; // $ExpectType any - // b[0]; // $ExpectType Error - // b[1]; // $ExpectType any - // c[0]; // $ExpectType Error - // c[1]; // $ExpectType any - // }, (a, b, c) => { - // a; // $ExpectType never - // b; // $ExpectType never - // c; // $ExpectType never - // }); - // } - // - // // 2 parameters - // { - // const w = $.when(t, u); - // - // w.then((a, b) => { - // a[0]; // $ExpectType string - // a[1]; // $ExpectType boolean - // b[0]; // $ExpectType string - // b[1]; // $ExpectType boolean - // }, (a, b) => { - // a[0]; // $ExpectType Error - // a[1]; // $ExpectType any - // b[0]; // $ExpectType Error - // b[1]; // $ExpectType any - // }, (a, b) => { - // a; // $ExpectType never - // b; // $ExpectType never - // }); - // } - - // 1 parameter - { - const w = $.when(t); - - w.then((a, b) => { - a; // $ExpectType string - b; // $ExpectType boolean - }, (a, b) => { - a; // $ExpectType Error - b; // $ExpectType any - }, (a, b) => { - a; // $ExpectType never - b; // $ExpectType never - }); - } - } - - function Promise() { - const p1: JQuery.Promise = {} as any; - const p2: JQuery.Promise = {} as any; - const p3: JQuery.Promise = {} as any; - - // 3 parameters - { - const w = $.when(p1, p2, p3); - - w.then((a, b, c) => { - a; // $ExpectType I1 - b; // $ExpectType I2 - c; // $ExpectType I3 - }, (a, b, c) => { - a; // $ExpectType I2 - b; // $ExpectType I3 - c; // $ExpectType I4 - }, (a, b, c) => { - a; // $ExpectType never - b; // $ExpectType never - c; // $ExpectType never - }); - } - - // 2 parameters - { - const w = $.when(p1, p2); - - w.then((a, b) => { - a; // $ExpectType I1 - b; // $ExpectType I2 - }, (a, b) => { - a; // $ExpectType I2 - b; // $ExpectType I3 - }, (a, b) => { - a; // $ExpectType never - b; // $ExpectType never - }); - } - - // 1 parameter - { - const w = $.when(p1); - - w.then(a => { - a; // $ExpectType I1 - }, a => { - a; // $ExpectType I2 - }, a => { - a; // $ExpectType never - }); - } - } - - function Thenable() { - const t1: JQuery.Thenable = {} as any; - const t2: JQuery.Thenable = {} as any; - const t3: JQuery.Thenable = {} as any; - - // 3 parameters - { - const w = $.when(t1, t2, t3); - - w.then((a, b, c) => { - a; // $ExpectType I1 - b; // $ExpectType I2 - c; // $ExpectType I3 - }, (a, b, c) => { - a; // $ExpectType any - b; // $ExpectType any - c; // $ExpectType any - }, (a, b, c) => { - a; // $ExpectType never - b; // $ExpectType never - c; // $ExpectType never - }); - } - - // 2 parameters - { - const w = $.when(t1, t2); - - w.then((a, b) => { - a; // $ExpectType I1 - b; // $ExpectType I2 - }, (a, b) => { - a; // $ExpectType any - b; // $ExpectType any - }, (a, b) => { - a; // $ExpectType never - b; // $ExpectType never - }); - } - - // 1 parameter - { - const w = $.when(t1); - - w.then(a => { - a; // $ExpectType I1 - }, a => { - a; // $ExpectType any - }, a => { - a; // $ExpectType never - }); - } - } - - function value() { - const w = $.when('myVal1'); - - w.then(a => { - a; // $ExpectType string - }); - } - - function Zero() { - const w = $.when(); - - w.then(a => { - a; // $ExpectType never - }, a => { - a; // $ExpectType never - }, a => { - a; // $ExpectType never - }); - } - - // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/2725 - function issue_2725() { - function first() { - return $.when('1'); - } - - $.when().then(() => { - return first(); - }).then((value) => { - value; // $ExpectType string - }); - } - - // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/10159 - function issue_10159() { - interface One { result: number; } - interface Two { Result: number; } - interface Three { TheResult: number; } - - class AsyncRunner { - Run(): void { - const task1 = this.runTask1(); - const task2 = this.runTask2(); - const task3 = this.runTask3(); - - $.when(task1, task2, task3) - .then((r1, r2, r3) => { - r1; // $ExpectType One - r2; // $ExpectType Two - r3; // $ExpectType Three - }); - } - - runTask1() { - let dfd = $.Deferred(); - console.log('Task 1'); - setTimeout(() => { dfd.resolve({ result: 1 }); }, Math.floor(400 + Math.random() * 2000)); - return dfd.promise(); - } - - runTask2() { - let dfd = $.Deferred(); - console.log('Task 2'); - setTimeout(() => { dfd.resolve({ Result: 2 }); }, Math.floor(400 + Math.random() * 2000)); - return dfd.promise(); - } - - runTask3() { - let dfd = $.Deferred(); - console.log('Task 3'); - setTimeout(() => { dfd.resolve({ TheResult: 3 }); }, Math.floor(400 + Math.random() * 2000)); - return dfd.promise(); - } - } - } - } -} - function AjaxSettings() { $.ajax({ accepts: { From 1c6c4aaf5b9edec3d11304cfce572756b046f368 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sat, 8 Jul 2017 11:35:14 -0400 Subject: [PATCH 0350/1618] [jquery] scrollLeft() and scrollTop() can also return undefined. scrollLeft() and scrollTop() will return undefined when used on an empty set. --- types/jquery/index.d.ts | 4 ++-- types/jquery/jquery-tests.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 9d290ebf43..2f23d64003 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -2845,7 +2845,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/scrollLeft/} * @since 1.2.6 */ - scrollLeft(): number; + scrollLeft(): number | undefined; /** * Set the current vertical position of the scroll bar for each of the set of matched elements. * @@ -2861,7 +2861,7 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/scrollTop/} * @since 1.2.6 */ - scrollTop(): number; + scrollTop(): number | undefined; /** * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index e5be26c558..42291bd7a1 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -1936,7 +1936,7 @@ function JQuery() { // $ExpectType JQuery $('p').scrollLeft(200); - // $ExpectType number + // $ExpectType number | undefined $('p').scrollLeft(); } @@ -1944,7 +1944,7 @@ function JQuery() { // $ExpectType JQuery $('p').scrollTop(200); - // $ExpectType number + // $ExpectType number | undefined $('p').scrollTop(); } From c7393ce5466a46fbd20efa8242e46938ed785537 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sat, 8 Jul 2017 11:56:30 -0400 Subject: [PATCH 0351/1618] [jquery] Fix tests. --- types/jquery/jquery-tests.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 42291bd7a1..088340b61b 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -959,7 +959,7 @@ function JQueryStatic() { } function type() { - // $ExpectType "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" | "error" | "array" | "date" | "null" | "regexp" + // $ExpectType "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" | "array" | "date" | "error" | "null" | "regexp" $.type({}); } @@ -1432,7 +1432,7 @@ function JQuery() { this; // $ExpectType string responseText; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType jqXHR jqXHR; @@ -1444,7 +1444,7 @@ function JQuery() { this; // $ExpectType string responseText; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType jqXHR jqXHR; @@ -1456,7 +1456,7 @@ function JQuery() { this; // $ExpectType string responseText; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType jqXHR jqXHR; @@ -4420,7 +4420,7 @@ function JQuery() { } function contents() { - // $ExpectType JQuery + // $ExpectType JQuery $('p').contents(); } @@ -4808,7 +4808,7 @@ function AjaxSettings() { this; // $ExpectType jqXHR jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; }, contents: { @@ -4919,7 +4919,7 @@ function AjaxSettings() { this; // $ExpectType jqXHR jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; }], contentType: false, @@ -5126,21 +5126,21 @@ function jqXHR() { $.ajax('/echo/json').always((data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; }, [(data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; }], (data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; @@ -5150,14 +5150,14 @@ function jqXHR() { $.ajax('/echo/json').always((data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; }, [(data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; @@ -5167,14 +5167,14 @@ function jqXHR() { $.ajax('/echo/json').always([(data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; }], (data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; @@ -5184,7 +5184,7 @@ function jqXHR() { $.ajax('/echo/json').always((data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; @@ -5194,7 +5194,7 @@ function jqXHR() { $.ajax('/echo/json').always([(data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any data_jqXHR; - // $ExpectType TextStatus + // $ExpectType "success" | "notmodified" | "nocontent" | "error" | "timeout" | "abort" | "parsererror" textStatus; // $ExpectType string | jqXHR jqXHR_errorThrown; From af079db266fb09ad990e094ff54216fcdf636c1a Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 9 Jul 2017 17:54:54 -0400 Subject: [PATCH 0352/1618] [jquery] Split @since. --- types/jquery/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 2f23d64003..c038daa684 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -906,7 +906,8 @@ interface JQueryStatic { * * @param array The Array of DOM elements. * @see {@link https://api.jquery.com/jQuery.uniqueSort/} - * @since 1.12-2.2 + * @since 1.12 + * @since 2.2 */ uniqueSort(array: T[]): T[]; /** From 263ecda46312a80fb246deaf2e247c48b506a007 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Mon, 10 Jul 2017 11:54:27 -0400 Subject: [PATCH 0353/1618] [jquery] Improve declaration of proxy(). Return a specific function type instead of Function. Add support for passing null/undefined for context. --- types/jquery/index.d.ts | 2015 +++++++++++++++++++++++++++- types/jquery/jquery-tests.ts | 699 +++++++++- types/jquery/test/example-tests.ts | 12 +- 3 files changed, 2705 insertions(+), 21 deletions(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index c038daa684..c4b8e0ec63 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -792,6 +792,1965 @@ interface JQueryStatic { * @since 2.2 */ post(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; + + // region proxy + + // region (fn, null | undefined) + + // region 0 to 7 arguments + + // region 0 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C) => TReturn, + context: null | undefined, + a: A, b: B, c: C): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B) => TReturn, + context: null | undefined, + a: A, b: B): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4` + * @since 1.6 + */ + proxy(fn: (a: A) => TReturn, + context: null | undefined, + a: A): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: () => TReturn, + context: null | undefined): () => TReturn; + + // endregion + + // region 1 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, + t: T) => TReturn, + context: null | undefined, + a: A, b: B): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, + t: T) => TReturn, + context: null | undefined, + a: A): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (t: T) => TReturn, + context: null | undefined): (t: T) => TReturn; + + // endregion + + // region 2 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, + t: T, u: U) => TReturn, + context: null | undefined, + a: A): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (t: T, u: U) => TReturn, + context: null | undefined): (t: T, u: U) => TReturn; + + // endregion + + // region 3 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (t: T, u: U, v: V) => TReturn, + context: null | undefined): (t: T, u: U, v: V) => TReturn; + + // endregion + + // region 4 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W) => TReturn; + + // endregion + + // region 5 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W, x: X) => TReturn; + + // endregion + + // region 6 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + + // endregion + + // region 7+ parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + + // endregion + + // endregion + + // region 8+ arguments + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.9 + */ + proxy(fn: (...args: any[]) => TReturn, + context: null | undefined, + ...additionalArguments: any[]): (...args: any[]) => TReturn; + + // endregion + + // endregion + + // region (fn, context) + + // region 0 to 7 arguments + + // region 0 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B) => TReturn, + context: TContext, + a: A, b: B): (this: TContext) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4` + * @since 1.6 + */ + proxy(fn: (a: A) => TReturn, + context: TContext, + a: A): (this: TContext) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: () => TReturn, + context: TContext): (this: TContext) => TReturn; + + // endregion + + // region 1 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext, t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext, t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, + t: T) => TReturn, + context: TContext, + a: A, b: B): (this: TContext, t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, + t: T) => TReturn, + context: TContext, + a: A): (this: TContext, t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (t: T) => TReturn, + context: TContext): (this: TContext, t: T) => TReturn; + + // endregion + + // region 2 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext, t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B): (this: TContext, t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, + t: T, u: U) => TReturn, + context: TContext, + a: A): (this: TContext, t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (t: T, u: U) => TReturn, + context: TContext): (this: TContext, t: T, u: U) => TReturn; + + // endregion + + // region 3 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B): (this: TContext, t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A): (this: TContext, t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (t: T, u: U, v: V) => TReturn, + context: TContext): (this: TContext, t: T, u: U, v: V) => TReturn; + + // endregion + + // region 4 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (t: T, u: U, v: V, w: W) => TReturn, + context: TContext): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; + + // endregion + + // region 5 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; + + // endregion + + // region 6 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + + // endregion + + // region 7+ parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (a: A, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fn The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @see {@link https://api.jquery.com/jQuery.proxy/} + * @since 1.4 + * @since 1.6 + */ + proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + + // endregion + + // endregion + + // region 8+ arguments + /** * Takes a function and returns a new one that will always have a particular context. * @@ -802,7 +2761,17 @@ interface JQueryStatic { * @since 1.4 * @since 1.6 */ - proxy(fn: Function, context: object, ...additionalArguments: any[]): Function; + proxy(fn: (...args: any[]) => TReturn, + context: TContext, + ...additionalArguments: any[]): (this: TContext, ...args: any[]) => TReturn; + + // endregion + + // endregion + + // region (context, name) + /** * Takes a function and returns a new one that will always have a particular context. * @@ -813,7 +2782,14 @@ interface JQueryStatic { * @since 1.4 * @since 1.6 */ - proxy(context: T, name: keyof T, ...additionalArguments: any[]): Function; + proxy(context: TContext, + name: keyof TContext, + ...additionalArguments: any[]): (this: TContext, ...args: any[]) => any; + + // endregion + + // endregion + /** * Manipulate the queue of functions to be executed on the matched element. * @@ -2325,7 +4301,11 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/on/} * @since 1.7 */ - on(events: string, selector: JQuery.Selector | null, data: TData, handler: JQuery.EventHandler): this; + on(events: string, + selector: JQuery.Selector | null, + data: TData, + handler: JQuery.EventHandlerBase>): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -2337,7 +4317,9 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/on/} * @since 1.7 */ - on(events: string, selector: JQuery.Selector | null, handler: JQuery.EventHandler | false): this; + on(events: string, + selector: JQuery.Selector | null, + handler: JQuery.EventHandlerBase> | false): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -2347,7 +4329,10 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/on/} * @since 1.7 */ - on(events: string, data: TData, handler: JQuery.EventHandler): this; + on(events: string, + data: TData, + handler: JQuery.EventHandlerBase>): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -2357,7 +4342,17 @@ interface JQuery extends Iterable * @see {@link https://api.jquery.com/on/} * @since 1.7 */ - on(events: string, handler: JQuery.EventHandler | false): this; + on(events: string, handler: JQuery.EventHandlerBase> | false): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand + * for a function that simply does return false. + * @see {@link https://api.jquery.com/on/} + * @since 1.7 + */ + on(events: string, handler: JQuery.EventHandlerBase> | false): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -5316,9 +7311,11 @@ declare namespace JQuery { // endregion - // Extra parameters can be passed from trigger() - interface EventHandler { - (this: TContext, eventObject: JQuery.Event, ...args: any[]): void | false | any; + interface EventHandler extends EventHandlerBase> { } + + interface EventHandlerBase { + // Extra parameters can be passed from trigger() + (this: TContext, t: T, ...args: any[]): void | false | any; } // Provided for convenience for use with jQuery.Event.which diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 088340b61b..54a1418fe4 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -863,16 +863,703 @@ function JQueryStatic() { } function proxy() { - // $ExpectType Function - $.proxy($.noop, {}, 1, 2); + interface I1 { kind: 'I1'; } + interface I2 { kind: 'I2'; } + interface I3 { kind: 'I3'; } + interface I4 { kind: 'I4'; } + interface I5 { kind: 'I5'; } + interface I6 { kind: 'I6'; } + interface I7 { kind: 'I7'; } + interface I8 { kind: 'I8'; } - // $ExpectType Function - $.proxy($.noop, {}); + const a: I8 = {} as any; + const b: I7 = {} as any; + const c: I6 = {} as any; + const d: I5 = {} as any; + const e: I4 = {} as any; + const f: I3 = {} as any; + const g: I2 = {} as any; + const h: I2 = {} as any; - // $ExpectType Function + type A = typeof a; + type B = typeof b; + type C = typeof c; + type D = typeof d; + type E = typeof e; + type F = typeof f; + type G = typeof g; + type H = typeof h; + + // (fn, null) + { + // $ExpectType () => void + $.proxy((a, b, c, d, e, f, g) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType () => void + $.proxy((a, b, c, d, e, f) => { }, null, a, b, c, d, e, f); + + // $ExpectType () => void + $.proxy((a, b, c, d, e) => { }, null, a, b, c, d, e); + + // $ExpectType () => void + $.proxy((a, b, c, d) => { }, null, a, b, c, d); + + // $ExpectType () => void + $.proxy((a, b, c) => { }, null, a, b, c); + + // $ExpectType () => void + $.proxy((a, b) => { }, null, a, b); + + // $ExpectType () => void + $.proxy((a) => { }, null, a); + + // $ExpectType () => void + $.proxy(() => { }, null); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1) => { }, null, a, b, c, d); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, t: I1) => { }, null, a, b, c); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, t: I1) => { }, null, a, b); + + // $ExpectType (t: I1) => void + $.proxy((a: A, t: I1) => { }, null, a); + + // $ExpectType (t: I1) => void + $.proxy((t: I1) => { }, null); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2) => { }, null, a, b, c, d); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2) => { }, null, a, b, c); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, t: I1, u: I2) => { }, null, a, b); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, t: I1, u: I2) => { }, null, a); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((t: I1, u: I2) => { }, null); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3) => { }, null, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3) => { }, null, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3) => { }, null, a, b); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, t: I1, u: I2, v: I3) => { }, null, a); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((t: I1, u: I2, v: I3) => { }, null); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4) => { }, null, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((t: I1, u: I2, v: I3, w: I4) => { }, null); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null); + + // $ExpectType (...args: any[]) => void + $.proxy((a, b, c, d, e, f, g, h, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e, f, g, h); + } + + // (fn, undefined) + { + // $ExpectType () => void + $.proxy((a, b, c, d, e, f, g) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType () => void + $.proxy((a, b, c, d, e, f) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType () => void + $.proxy((a, b, c, d, e) => { }, undefined, a, b, c, d, e); + + // $ExpectType () => void + $.proxy((a, b, c, d) => { }, undefined, a, b, c, d); + + // $ExpectType () => void + $.proxy((a, b, c) => { }, undefined, a, b, c); + + // $ExpectType () => void + $.proxy((a, b) => { }, undefined, a, b); + + // $ExpectType () => void + $.proxy((a) => { }, undefined, a); + + // $ExpectType () => void + $.proxy(() => { }, undefined); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, c: C, t: I1) => { }, undefined, a, b, c); + + // $ExpectType (t: I1) => void + $.proxy((a: A, b: B, t: I1) => { }, undefined, a, b); + + // $ExpectType (t: I1) => void + $.proxy((a: A, t: I1) => { }, undefined, a); + + // $ExpectType (t: I1) => void + $.proxy((t: I1) => { }, undefined); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2) => { }, undefined, a, b, c); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, b: B, t: I1, u: I2) => { }, undefined, a, b); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((a: A, t: I1, u: I2) => { }, undefined, a); + + // $ExpectType (t: I1, u: I2) => void + $.proxy((t: I1, u: I2) => { }, undefined); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3) => { }, undefined, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3) => { }, undefined, a, b); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((a: A, t: I1, u: I2, v: I3) => { }, undefined, a); + + // $ExpectType (t: I1, u: I2, v: I3) => void + $.proxy((t: I1, u: I2, v: I3) => { }, undefined); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void + $.proxy((t: I1, u: I2, v: I3, w: I4) => { }, undefined); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e, f, g); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e, f); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a); + + // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined); + + // $ExpectType (...args: any[]) => void + $.proxy((a, b, c, d, e, f, g, h, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e, f, g, h); + } + + // (fn, context) + { + // $ExpectType (this: {}) => void + $.proxy((a, b, c, d, e, f, g) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}) => void + $.proxy((a, b, c, d, e, f) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}) => void + $.proxy((a, b, c, d, e) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}) => void + $.proxy((a, b, c, d) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}) => void + $.proxy((a, b, c) => { }, {}, a, b, c); + + // $ExpectType (this: {}) => void + $.proxy((a, b) => { }, {}, a, b); + + // $ExpectType (this: {}) => void + $.proxy((a) => { }, {}, a); + + // $ExpectType (this: {}) => void + $.proxy(() => { }, {}); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((a: A, b: B, c: C, t: I1) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((a: A, b: B, t: I1) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((a: A, t: I1) => { }, {}, a); + + // $ExpectType (this: {}, t: I1) => void + $.proxy((t: I1) => { }, {}); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((a: A, b: B, t: I1, u: I2) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((a: A, t: I1, u: I2) => { }, {}, a); + + // $ExpectType (this: {}, t: I1, u: I2) => void + $.proxy((t: I1, u: I2) => { }, {}); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((a: A, t: I1, u: I2, v: I3) => { }, {}, a); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void + $.proxy((t: I1, u: I2, v: I3) => { }, {}); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4) => { }, {}, a); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void + $.proxy((t: I1, u: I2, v: I3, w: I4) => { }, {}); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e, f, g); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e, f); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a); + + // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void + $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}); + + // $ExpectType (this: {}, ...args: any[]) => void + $.proxy((a, b, c, d, e, f, g, h, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e, f, g, h); + } + + // $ExpectType (this: { myFunc: () => undefined; }, ...args: any[]) => any $.proxy({ myFunc: $.noop }, 'myFunc', 1, 2); - // $ExpectType Function + // $ExpectType (this: { myFunc: () => undefined; }, ...args: any[]) => any $.proxy({ myFunc: $.noop }, 'myFunc'); } diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 0c871de0a7..5d4e27d970 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -3032,13 +3032,13 @@ function examples() { // attach click handlers to #test $('#test') // this === "zombie"; handler unbound after first click - .on('click', $.proxy(me.test, me) as JQuery.EventHandler) + .on('click', $.proxy(me.test, me)) // this === "person" - .on('click', youClick as JQuery.EventHandler) + .on('click', youClick) // this === "zombie" - .on('click', $.proxy(you.test, me) as JQuery.EventHandler) + .on('click', $.proxy(you.test, me)) // this === "