diff --git a/.gitignore b/.gitignore index f7927724d5..5b79863e52 100644 --- a/.gitignore +++ b/.gitignore @@ -38,5 +38,6 @@ node_modules .sublimets .settings/launch.json +.vs .vscode yarn.lock diff --git a/3d-bin-packing/index.d.ts b/3d-bin-packing/index.d.ts index 2461538194..14228f3141 100644 --- a/3d-bin-packing/index.d.ts +++ b/3d-bin-packing/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/betterwaysystems/packer // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1036be548d..6e2c883f3a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1680,7 +1680,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](swig/swig.d.ts) [swig](http://github.com/paularmstrong/swig) by [Peter Harris](https://github.com/CodeAnimal), [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](swig-email-templates/swig-email-templates.d.ts) [swig-email-templates](https://github.com/andrewrk/swig-email-templates) by [Adam Babcock](https://github.com/mrhen) * [:link:](swipe/swipe.d.ts) [Swipe](https://github.com/thebird/Swipe) by [Andrey Kurdyumov](https://github.com/kant2002) -* [:link:](swiper/swiper.d.ts) [Swiper](https://github.com/nolimits4web/Swiper) by [Sebastián Galiano](https://github.com/sgaliano) +* [:link:](swiper/swiper.d.ts) [Swiper](https://github.com/nolimits4web/Swiper) by [Sebastián Galiano](https://github.com/sgaliano), [Luca Trazzi](https://github.com/lucax88x) * [:link:](swipeview/swipeview.d.ts) [SwipeView](http://cubiq.org/swipeview) by [Boris Yankov](https://github.com/borisyankov) * [:link:](switchery/switchery.d.ts) [switchery](https://github.com/abpetkov/switchery) by [Bruno Grieder](https://github.com/bgrieder), [Clayton Lautier](https://github.com/claylaut) * [:link:](swiz/swiz.d.ts) [swiz](https://github.com/racker/node-swiz) by [Jeff Goddard](https://github.com/jedigo) diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md index a9ae498738..4078b4808b 100644 --- a/ISSUE_TEMPLATE.md +++ b/ISSUE_TEMPLATE.md @@ -1,5 +1,5 @@ -- [ ] I tried using the latest `xxxx/xxxx.d.ts` file in this repo and had problems. +- [ ] I tried using the `@types/xxxx` package and had problems. - [ ] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript - [ ] I have a question that is inappropriate for [StackOverflow](https://stackoverflow.com/). (Please ask any appropriate questions there). -- [ ] I want to talk about `xxxx/xxxx.d.ts`. - - The authors of that type definition are cc/ @.... +- [ ] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see `Definitions by:` in `index.d.ts`) so they can respond. + - Authors: @.... diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 4d9a7aab6f..1fc8897d23 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -3,8 +3,8 @@ Please fill in this template. - [ ] Make your PR against the `master` branch. - [ ] Use a meaningful title for the pull request. Include the name of the package modified. - [ ] Test the change in your own code. (Compile and run.) -- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped#make-a-pull-request). -- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes). +- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request). +- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes). - [ ] Run `tsc` without errors. - [ ] Run `npm run lint package-name` if a `tslint.json` is present. diff --git a/README.md b/README.md index 4940649a6e..23bb52f13c 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,9 @@ Your package should have this structure: | tsconfig.json | This allows you to run `tsc` within the package. | | tslint.json | Enables linting. | -Generate these by running `npm run new-package -- new-package-name`. +Generate these by running `npm run new-package -- --name my-package-name --template module`. +(Other templates are `module-class`, `module-function`, `module-plugin`, `global`, `global-plugin`, and `global-modifying-module`. +This just wraps [dts-gen](https://github.com/Microsoft/dts-gen), so it supports all options from that.) You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option. @@ -167,10 +169,8 @@ If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. (To indicate that a lint rule truly does not apply, use `// tslint:disable:rule-name` or better, `//tslint:disable-next-line:rule-name`.) -Only `.d.ts` files are linted. Test the linter by running `npm run lint -- package-name`. Do not use a globally installed tslint. - ## FAQ #### What exactly is the relationship between this repository and the `@types` packages on NPM? @@ -224,6 +224,38 @@ If the standard is still a draft, it belongs here. Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header. When it graduates draft mode, we may remove it from DefinitelyTyped and deprecate the associated `@types` package. +#### I want to update a package to a new major version + +Before making your change, please create a new subfolder with the current version e.g. `v2`, and copy existing files to it. You will need to: + +1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. +2. Add path mapping rules to ensure that tests are running against the intended version. + +For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/history/v2/tsconfig.json) looks like: + +```json +{ + "compilerOptions": { + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "history": [ "history/v2" ] + }, + }, + "files": [ + "index.d.ts", + "history-tests.ts" + ] +} +``` + +Please note that unless upgrading something backwards-compatible like `node`, all packages depending of the updated package need a path mapping to it, as well as packages depending on *those*. +For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`; +transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/react-router-bootstrap/tsconfig.json). + +Also, `/// ` will not work with path mapping, so dependencies must use `import`. + + ## License This project is licensed under the MIT license. diff --git a/ably/ably-tests.ts b/ably/ably-tests.ts new file mode 100644 index 0000000000..026ef48adc --- /dev/null +++ b/ably/ably-tests.ts @@ -0,0 +1,256 @@ +import * as Ably from 'ably'; + +declare var console: { log(message: any): void }; + +const ApiKey = 'appId.keyId:secret'; +const client = new Ably.Realtime(ApiKey); +const restClient = new Ably.Rest(ApiKey); + +// Connection +// Successful connection: + +client.connection.on('connected', () => { + // successful connection +}); + +// Failed connection: + +client.connection.on('failed', () => { + // failed connection +}); + + +// Subscribing to a channel + +var channel = client.channels.get('test'); +channel.subscribe(message => { + message.name; // 'greeting' + message.data; // 'Hello World!' +}); + +// Only certain events: + +channel.subscribe('myEvent', message => { + message.name; // 'myEvent' + message.data; // 'myData' +}); + +// Publishing to a channel + +// Publish a single message with name and data +channel.publish('greeting', 'Hello World!'); + +// Optionally, you can use a callback to be notified of success or failure +channel.publish('greeting', 'Hello World!', err => { + if (err) { + console.log('publish failed with error ' + err); + } else { + console.log('publish succeeded'); + } +}); + +// Publish several messages at once +channel.publish([{name: 'greeting', data: 'Hello World!'}], () => { }); + +// Querying the History + +channel.history((err, messagesPage) => { + messagesPage.items; // array of Message + messagesPage.items[0].data; // payload for first message + messagesPage.items.length; // number of messages in the current page of history + messagesPage.hasNext(); // true if there are further pages + messagesPage.isLast(); // true if this page is the last page + messagesPage.next(nextPage => { nextPage; }); // retrieves the next page as PaginatedResult +}); + +// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history +channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards'}, (err, messagesPage) => { + console.log(messagesPage.items.length); +}); + + +// Presence on a channel +// Getting presence: + +channel.presence.get(presenceSet => { + presenceSet; // array of PresenceMessages +}); + +// Note that presence#get on a realtime channel does not return a PaginatedResult, as the library maintains a local copy of the presence set. + +// Entering (and leaving) the presence set: + +channel.presence.enter('my status', err => { + // now I am entered +}); + +channel.presence.update('new status', err => { + // my presence data is updated +}); + +channel.presence.leave(null, err => { + // I've left the presence set +}); + +channel.presence.enterClient('myClientId', 'status', err => { +}); + +// and similiarly, updateClient and leaveClient +// Querying the Presence History + +channel.presence.history((err, messagesPage) => { // PaginatedResult + messagesPage.items; // array of PresenceMessage + messagesPage.items[0].data; // payload for first message + messagesPage.items.length; // number of messages in the current page of history + messagesPage.hasNext(); // true if there are further pages + messagesPage.isLast(); // true if this page is the last page + messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult +}); + +// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history +channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); + +// Symmetrical end-to-end encrypted payloads on a channel + +// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key. +// The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption + +// Generate a random 256-bit key for demonstration purposes (in +// practice you need to create one and distribute it to clients yourselves) +Ably.Realtime.Crypto.generateRandomKey((err, key) => { + var channel = client.channels.get('channelName', { cipher: { key } }); + + channel.subscribe(message => { + message.name; // 'name is not encrypted' + message.data; // 'sensitive data is encrypted' + }); + + channel.publish('name is not encrypted', 'sensitive data is encrypted'); +}); + +// You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect): + +channel.setOptions({cipher: {key: ''}}, () => { + // New encryption settings are in effect +}); + +// Using the REST API + +var restChannel = restClient.channels.get('test'); + +// Publishing to a channel + +// Publish a single message with name and data +restChannel.publish('greeting', 'Hello World!'); + +// Optionally, you can use a callback to be notified of success or failure +restChannel.publish('greeting', 'Hello World!', err => { + if (err) { + console.log('publish failed with error ' + err); + } else { + console.log('publish succeeded'); + } +}); + +// Publish several messages at once +restChannel.publish([{name: 'greeting', data: 'Hello World!'}], () => {}); + +// Querying the History + +restChannel.history((err, messagesPage) => { + messagesPage; // PaginatedResult + messagesPage.items; // array of Message + messagesPage.items[0].data; // payload for first message + messagesPage.items.length; // number of messages in the current page of history + messagesPage.hasNext(); // true if there are further pages + messagesPage.isLast(); // true if this page is the last page + messagesPage.next(nextPage => {}); // retrieves the next page as PaginatedResult +}); + +// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history +restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); + +// Presence on a channel + +restChannel.presence.get((err, presencePage) => { // PaginatedResult + presencePage.items; // array of PresenceMessage + presencePage.items[0].data; // payload for first message + presencePage.items.length; // number of messages in the current page of members + presencePage.hasNext(); // true if there are further pages + presencePage.isLast(); // true if this page is the last page + presencePage.next(nextPage => {}); // retrieves the next page as PaginatedResult +}); + +// Querying the Presence History + +restChannel.presence.history((err, messagesPage) => { // PaginatedResult + messagesPage.items; // array of PresenceMessage + messagesPage.items[0].data; // payload for first message + messagesPage.items.length; // number of messages in the current page of history + messagesPage.hasNext(); // true if there are further pages + messagesPage.isLast(); // true if this page is the last page + messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult +}); + +// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history +restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); + + +// Generate Token and Token Request +// See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism. + +// Requesting a token: + +client.auth.requestToken((err, tokenDetails) => { + // tokenDetails is instance of TokenDetails + // see https://www.ably.io/documentation/rest/authentication/#token-details for its properties + + // Now we have the token, we can send it to someone who can instantiate a client with it: + var clientUsingToken = new Ably.Realtime(tokenDetails.token); +}); + +// requestToken can take two optional params +// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params +// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options +client.auth.requestToken({}, {}, (err, tokenDetails) => { }); + +// Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms): + +client.auth.createTokenRequest((err, tokenRequest) => { + // now send the tokenRequest back to the client, which will + // use it to request a token and connect to Ably +}); + +// createTokenRequest can take two optional params +// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params +// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options +client.auth.createTokenRequest({}, {}, (err, tokenRequest) => { }); + +// Fetching your application's stats + +client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as PaginatedResult + statsPage.items; // array of Stats + statsPage.items[0].inbound.rest.messages.count; // total messages published over REST + statsPage.items.length; // number of stats in the current page of history + statsPage.hasNext(); // true if there are wrther pages + statsPage.isLast(); // true if this page is the last page + statsPage.next((nextPage) => {}); // retrieves the next page as PaginatedResult +}); + +// Fetching the Ably service time + +client.time({}, (err, time) => {}); // time is in ms since epoch + +// Getting decoded Message objects from JSON +var messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]); +console.log(messages[0].id); + +var message = Ably.Rest.Message.fromEncoded({ id: 'foo' }); +console.log(message.id); + +// Getting decoded PresenceMessage objects from JSON +var presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]); +console.log(presenceMessages[0].action); + +var presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' }); +console.log(presenceMessage.action); diff --git a/ably/index.d.ts b/ably/index.d.ts new file mode 100644 index 0000000000..a6ea5785ac --- /dev/null +++ b/ably/index.d.ts @@ -0,0 +1,473 @@ +// Type definitions for Ably Realtime and Rest client library 0.9 +// Project: https://www.ably.io/ +// Definitions by: Ably +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ablyLib { + namespace ChannelState { + type INITIALIZED = 'initialized'; + type ATTACHING = 'attaching'; + type ATTACHED = "attached"; + type DETACHING = "detaching"; + type DETACHED = "detached"; + type SUSPENDED = "suspended"; + type FAILED = "failed"; + } + type ChannelState = ChannelState.FAILED | ChannelState.INITIALIZED | ChannelState.SUSPENDED | ChannelState.ATTACHED | ChannelState.ATTACHING | ChannelState.DETACHED | ChannelState.DETACHING; + + namespace ConnectionState { + type INITIALIZED = "initialized"; + type CONNECTING = "connecting"; + type CONNECTED = "connected"; + type DISCONNECTED = "disconnected"; + type SUSPENDED = "suspended"; + type CLOSING = "closing"; + type CLOSED = "closed"; + type FAILED = "failed"; + } + type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED | + ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED; + + namespace ConnectionEvent { + type INITIALIZED = "initialized"; + type CONNECTING = "connecting"; + type CONNECTED = "connected"; + type DISCONNECTED = "disconnected"; + type SUSPENDED = "suspended"; + type CLOSING = "closing"; + type CLOSED = "closed"; + type FAILED = "failed"; + type UPDATE = "update"; + } + type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED | + ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE; + + namespace PresenceAction { + type ABSENT = "absent"; + type PRESENT = "present"; + type ENTER = "enter"; + type LEAVE = "leave"; + type UPDATE = "update"; + } + type PresenceAction = PresenceAction.ABSENT | PresenceAction.PRESENT | PresenceAction.ENTER | PresenceAction.LEAVE | PresenceAction.UPDATE; + + namespace StatsIntervalGranularity { + type MINUTE = "minute"; + type HOUR = "hour"; + type DAY = "day"; + type MONTH = "month"; + } + type StatsIntervalGranularity = StatsIntervalGranularity.MINUTE | StatsIntervalGranularity.HOUR | StatsIntervalGranularity.DAY | StatsIntervalGranularity.MONTH; + + namespace HTTPMethods { + type POST = "POST"; + type GET = "GET"; + } + type HTTPMethods = HTTPMethods.GET | HTTPMethods.POST; + + // Interfaces + interface ClientOptions extends AuthOptions { + /** + * When true will automatically connect to Ably when library is instanced. This is true by default + */ + autoConnect?: boolean; + + /** + * Optional clientId that can be used to specify the identity for this client. In most cases + * it is preferable to instead specift a clientId in the token issued to this client. + */ + clientId?: string; + + defaultTokenParams?: TokenParams; + + /** + * When true, messages published on channels by this client will be echoed back to this client. + * This is true by default + */ + echoMessages?: boolean; + + /** + * Use this only if you have been provided a dedicated environment by Ably + */ + environment?: string; + + /** + * Logger configuration + */ + log?: LogInfo; + port?: number; + + /** + * When true, messages will be queued whilst the connection is disconnected. True by default. + */ + queueMessages?: boolean; + + restHost?: string; + realtimeHost?: string; + fallbackHosts?: string[]; + + /** + * Can be used to explicitly recover a connection. + * See https://www.ably.io/documentation/realtime/connection#connection-state-recovery + */ + recover?: standardCallback | string; + + /** + * Use a non-secure connection connection. By default, a TLS connection is used to connect to Ably + */ + tls?: boolean; + tlsPort?: number; + + /** + * When true, the more efficient MsgPack binary encoding is used. + * When false, JSON text encoding is used. + */ + useBinaryProtocol?: boolean; + } + + interface AuthOptions { + /** + * A function which is called when a new token is required. + * The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically + * by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object. + **/ + authCallback?: (data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void) => void; + authHeaders?: { [index: string]: string }; + authMethod?: HTTPMethods; + authParams?: { [index: string]: string }; + + /** + * A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format). + **/ + authUrl?: string; + key?: string; + queryTime?: boolean; + token?: TokenDetails | string; + tokenDetails?: TokenDetails; + useTokenAuth?: boolean; + } + + interface TokenParams { + capability?: string; + clientId?: string; + nonce?: string; + timestamp?: number; + ttl?: number; + } + + interface CipherParams { + algorithm: string; + key: any; + keyLength: number; + mode: string; + } + + interface ErrorInfo { + code: number; + message: string; + statusCode: number; + } + + interface StatsMessageCount { + count: number; + data: number; + } + + interface StatsMessageTypes { + all: StatsMessageCount; + messages: StatsMessageCount; + presence: StatsMessageCount; + } + + interface StatsRequestCount { + failed: number; + refused: number; + succeeded: number; + } + + interface StatsResourceCount { + mean: number; + min: number; + opened: number; + peak: number; + refused: number; + } + + interface StatsConnectionTypes { + all: StatsResourceCount; + plain: StatsResourceCount; + tls: StatsResourceCount; + } + + interface StatsMessageTraffic { + all: StatsMessageTypes; + realtime: StatsMessageTypes; + rest: StatsMessageTypes; + webhook: StatsMessageTypes; + } + + interface TokenDetails { + capability: string; + clientId?: string; + expires: number; + issued: number; + token: string; + } + + interface TokenRequest { + capability: string; + clientId?: string; + keyName: string; + mac: string; + nonce: string; + timestamp: number; + ttl?: number; + } + + interface ChannelOptions { + cipher: any; + } + + interface RestPresenceHistoryParams { + start?: number; + end?: number; + direction?: string; + limit?: number; + } + + interface RestPresenceParams { + limit?: number; + clientId?: string; + connectionId?: string; + } + + interface RealtimePresenceParams { + waitForSync?: boolean; + clientId?: string; + connectionId?: string; + } + + interface RealtimePresenceHistoryParams { + start?: number; + end?: number; + direction?: string; + limit?: number; + untilAttach?: boolean; + } + + interface LogInfo { + /** + * A number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only), + * 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output). + **/ + level?: number; + + /** + * A function to handle each line of log output. If handler is not specified, console.log is used. + **/ + handler?: (...args: any[]) => void; + } + + interface ChannelEvent { + state: ChannelState; + } + + interface ChannelStateChange { + current: ChannelState; + previous: ChannelState; + reason?: ErrorInfo; + resumed: boolean; + } + + interface ConnectionStateChange { + current: ConnectionState; + previous: ConnectionState; + reason?: ErrorInfo; + retryIn?: number; + } + + // Common Listeners + type paginatedResultCallback = (error: ErrorInfo, results: PaginatedResult ) => void; + type standardCallback = (error: ErrorInfo, results: any) => void; + type messageCallback = (message: T) => void; + type errorCallback = (error: ErrorInfo) => void; + type channelEventCallback = (channelEvent: ChannelEvent, changeStateChange: ChannelStateChange) => void; + type connectionEventCallback = (connectionEvent: ConnectionEvent, connectionStateChange: ConnectionStateChange) => void; + type timeCallback = (error: ErrorInfo, time: number) => void; + type realtimePresenceGetCallback = (error: ErrorInfo, messages: PresenceMessage[]) => void; + type tokenDetailsCallback = (error: ErrorInfo, Results: TokenDetails) => void; + type tokenRequestCallback = (error: ErrorInfo, Results: TokenRequest) => void; + type fromEncoded = (JsonObject: any, channelOptions?: ChannelOptions) => T; + type fromEncodedArray = (JsonArray: any[], channelOptions?: ChannelOptions) => T[]; + + // Internal Classes + class EventEmitter { + on: (eventOrCallback: string | T, callback?: T) => void; + once: (eventOrCallback: string | T, callback?: T) => void; + off: (eventOrCallback?: string | T, callback?: T) => void; + } + + // Classes + class Auth { + clientId: string; + authorize: (tokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void; + createTokenRequest: (tokenParams?: TokenParams | tokenRequestCallback, authOptions?: AuthOptions | tokenRequestCallback, callback?: tokenRequestCallback) => void; + requestToken: (TokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void; + } + + class Presence { + get: (params: RestPresenceParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; + history: (params: RestPresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; + } + + class RealtimePresence { + syncComplete: () => boolean; + get: (Params: realtimePresenceGetCallback | RealtimePresenceParams, callback?: realtimePresenceGetCallback) => void; + history: (ParamsOrCallback: RealtimePresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; + subscribe: (presenceOrCallback: PresenceAction | messageCallback, listener?: messageCallback) => void; + unsubscribe: (presence?: PresenceAction, listener?: messageCallback) => void; + enter: (data?: errorCallback | any, callback?: errorCallback) => void; + update: (data?: errorCallback | any, callback?: errorCallback) => void; + leave: (data?: errorCallback | any, callback?: errorCallback) => void; + enterClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void; + updateClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void; + leaveClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void; + } + + class Channel { + name: string; + presence: Presence; + history: (paramsOrCallback?: RestPresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; + publish: (messagesOrName: any, messagedataOrCallback?: errorCallback | any, callback?: errorCallback) => void; + } + + class RealtimeChannel extends EventEmitter { + name: string; + errorReason: ErrorInfo; + state: ChannelState; + presence: RealtimePresence; + attach: (callback?: standardCallback) => void; + detach: (callback?: standardCallback) => void; + history: (paramsOrCallback?: RealtimePresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; + subscribe: (eventOrCallback: messageCallback | string, listener?: messageCallback) => void; + unsubscribe: (eventOrCallback?: messageCallback | string, listener?: messageCallback) => void; + publish: (messagesOrName: any, messageDataOrCallback?: errorCallback | any, callback?: errorCallback) => void; + setOptions: (options: any, callback?: errorCallback) => void; + } + + class Channels { + get: (name: string, channelOptions?: ChannelOptions) => T; + release: (name: string) => void; + } + + class Message { + constructor(); + static fromEncoded: fromEncoded; + static fromEncodedArray: fromEncodedArray; + clientId: string; + connectionId: string; + data: any; + encoding: string; + extras: any; + id: string; + name: string; + timestamp: number; + } + + interface MessageStatic { + fromEncoded: fromEncoded; + fromEncodedArray: fromEncodedArray; + } + + class PresenceMessage { + constructor(); + static fromEncoded: fromEncoded; + static fromEncodedArray: fromEncodedArray; + action: PresenceAction; + clientId: string; + connectionId: string; + data: any; + encoding: string; + id: string; + timestamp: number; + } + + interface PresenceMessageStatic { + fromEncoded: fromEncoded; + fromEncodedArray: fromEncodedArray; + } + + interface Crypto { + generateRandomKey: (callback: (error: ErrorInfo, key: string) => void) => void; + } + + class Connection extends EventEmitter { + errorReason: ErrorInfo; + id: string; + key: string; + recoveryKey: string; + serial: number; + state: ConnectionState; + close: () => void; + connect: () => void; + ping: (callback?: (error: ErrorInfo, responseTime: number ) => void ) => void; + } + + class Stats { + all: StatsMessageTypes; + apiRequests: StatsRequestCount; + channels: StatsResourceCount; + connections: StatsConnectionTypes; + inbound: StatsMessageTraffic; + intervalId: string; + outbound: StatsMessageTraffic; + persisted: StatsMessageTypes; + tokenRequests: StatsRequestCount; + } + + class PaginatedResult { + items: T[]; + first: (results: paginatedResultCallback) => void; + next: (results: paginatedResultCallback) => void; + current: (results: paginatedResultCallback) => void; + hasNext: () => boolean; + isLast: () => boolean; + } + + class HttpPaginatedResponse extends PaginatedResult { + items: string[]; + statusCode: number; + success: boolean; + errorCode: number; + errorMessage: string; + headers: any; + } +} + +export declare class Rest { + constructor(options: ablyLib.ClientOptions | string); + static Crypto: ablyLib.Crypto; + static Message: ablyLib.MessageStatic; + static PresenceMessage: ablyLib.PresenceMessageStatic; + auth: ablyLib.Auth; + channels: ablyLib.Channels; + request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void; + stats: (paramsOrCallback?: ablyLib.paginatedResultCallback | any, callback?: ablyLib.paginatedResultCallback) => void; + time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void; +} + +export declare class Realtime { + constructor(options: ablyLib.ClientOptions | string); + static Crypto: ablyLib.Crypto; + static Message: ablyLib.MessageStatic; + static PresenceMessage: ablyLib.PresenceMessageStatic; + auth: ablyLib.Auth; + channels: ablyLib.Channels; + clientId: string; + connection: ablyLib.Connection; + request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void; + stats: (paramsOrCallback?: ablyLib.paginatedResultCallback | any, callback?: ablyLib.paginatedResultCallback) => void; + close: () => void; + connect: () => void; + time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void; +} diff --git a/ably/tsconfig.json b/ably/tsconfig.json new file mode 100644 index 0000000000..86c7bc0114 --- /dev/null +++ b/ably/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", + "ably-tests.ts" + ] +} \ No newline at end of file diff --git a/gaea-model/tslint.json b/ably/tslint.json similarity index 100% rename from gaea-model/tslint.json rename to ably/tslint.json diff --git a/abs/tslint.json b/abs/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/abs/tslint.json +++ b/abs/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/accepts/index.d.ts b/accepts/index.d.ts index ff6a9d0995..a12dcaf5c9 100644 --- a/accepts/index.d.ts +++ b/accepts/index.d.ts @@ -3,29 +3,60 @@ // Definitions by: Stefan Reichel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -import { IncomingMessage } from "http"; - declare namespace accepts { + export interface Headers { + [key: string]: string | string[]; + } + export interface Accepts { - charset(charsets: string[]): string | string[] | boolean; - charset(...charsets: string[]): string | string[] | boolean; + /** + * Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned. + */ + charset(charsets: string[]): string | false; + charset(...charsets: string[]): string | false; + + /** + * Return the charsets that the request accepts, in the order of the client's preference (most preferred first). + */ charsets(): string[]; - encoding(encodings: string[]): string | string[] | boolean; - encoding(...encodings: string[]): string | string[] | boolean; + /** + * Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned. + */ + encoding(encodings: string[]): string | false; + encoding(...encodings: string[]): string | false; + + /** + * Return the encodings that the request accepts, in the order of the client's preference (most preferred first). + */ encodings(): string[]; - language(languages: string[]): string | string[] | boolean; - language(...languages: string[]): string | string[] | boolean; + /** + * Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned. + */ + language(languages: string[]): string | false; + language(...languages: string[]): string | false; + + /** + * Return the languages that the request accepts, in the order of the client's preference (most preferred first). + */ languages(): string[]; - type(types: string[]): string | string[] | boolean; - type(...types: string[]): string | string[] | boolean; + /** + * Return the first accepted type (and it is returned as the same text as what appears in the `types` array). If nothing in `types` is accepted, then `false` is returned. + * + * The `types` array can contain full MIME types or file extensions. Any value that is not a full MIME types is passed to `require('mime-types').lookup`. + */ + type(types: string[]): string | false; + type(...types: string[]): string | false; + + /** + * Return the types that the request accepts, in the order of the client's preference (most preferred first). + */ types(): string[]; } } -declare function accepts(req: IncomingMessage): accepts.Accepts; +declare function accepts(req: { headers: accepts.Headers }): accepts.Accepts; export = accepts; diff --git a/accounting/tslint.json b/accounting/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/accounting/tslint.json +++ b/accounting/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/alt/index.d.ts b/alt/index.d.ts index 561de28ac3..00e171484b 100644 --- a/alt/index.d.ts +++ b/alt/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/goatslacker/alt // Definitions by: Michael Shearer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/amplify-deferred/amplify-deferred-tests.ts b/amplify-deferred/amplify-deferred-tests.ts index a4c7c656c4..5a65dd9dde 100644 --- a/amplify-deferred/amplify-deferred-tests.ts +++ b/amplify-deferred/amplify-deferred-tests.ts @@ -1,5 +1,5 @@ amplify.request({ resourceId: "statusExample1" -}).done(function (data, status) { -}).fail(function (data, status) { -}).always(function (data, status) { }); +}).done((data, status) => { +}).fail((data, status) => { +}).always((data, status) => { }); diff --git a/amplify-deferred/tslint.json b/amplify-deferred/tslint.json index 0f47deabb4..f05741c59b 100644 --- a/amplify-deferred/tslint.json +++ b/amplify-deferred/tslint.json @@ -3,4 +3,4 @@ "rules": { "forbidden-types": false } -} \ No newline at end of file +} diff --git a/amplify/amplify-tests.ts b/amplify/amplify-tests.ts index f844642b8e..edf2988122 100644 --- a/amplify/amplify-tests.ts +++ b/amplify/amplify-tests.ts @@ -7,7 +7,7 @@ import amplify = require("amplify"); // Subscribe and publish with no data -amplify.subscribe("nodataexample", function () { +amplify.subscribe("nodataexample", () => { alert("nodataexample topic published!"); }); @@ -15,24 +15,24 @@ amplify.subscribe("nodataexample", function () { amplify.publish("nodataexample"); -amplify.subscribe("dataexample", function (data) { +amplify.subscribe("dataexample", data => { alert(data.foo); // bar }); amplify.publish("dataexample", { foo: "bar" }); -amplify.subscribe("dataexample2", function (param1, param2) { +amplify.subscribe("dataexample2", (param1, param2) => { alert(param1 + param2); // barbaz }); -//... +// ... amplify.publish("dataexample2", "bar", "baz"); // Subscribe and publish with context and data -amplify.subscribe("datacontextexample", $("p:first"), function (data) { +amplify.subscribe("datacontextexample", $("p:first"), data => { this.text(data.exampleText); // first p element would have "foo bar baz" as text }); @@ -40,11 +40,11 @@ amplify.publish("datacontextexample", { exampleText: "foo bar baz" }); // Subscribe to a topic with high priority -amplify.subscribe("priorityexample", function (data) { +amplify.subscribe("priorityexample", data => { alert(data.foo); }); -amplify.subscribe("priorityexample", function (data) { +amplify.subscribe("priorityexample", data => { if (data.foo === "oops") { return false; } @@ -87,7 +87,7 @@ amplify.request.define("ajaxExample1", "ajax", { }); // later in code -amplify.request("ajaxExample1", function (data) { +amplify.request("ajaxExample1", data => { data.foo; // bar }); @@ -101,21 +101,21 @@ amplify.request.define("ajaxExample2", "ajax", { }); // later in code -amplify.request("ajaxExample2", function (data) { +amplify.request("ajaxExample2", data => { data.foo; // bar }); // a second call will result in pulling from the cache -amplify.request("ajaxExample2", function (data) { +amplify.request("ajaxExample2", data => { data.baz; // qux -}) +}); // Set up and use a RESTful request utilizing Ajax amplify.request.define("ajaxRESTFulExample", "ajax", { url: "/myRestFulApi/{type}/{id}", type: "GET" -}) +}); // later in code amplify.request("ajaxRESTFulExample", @@ -123,7 +123,7 @@ amplify.request("ajaxRESTFulExample", type: "foo", id: "bar" }, - function (data) { + data => { // /myRESTFulApi/foo/bar was the URL used data.foo; // bar } @@ -132,9 +132,9 @@ amplify.request("ajaxRESTFulExample", // POST data with Ajax amplify.request.define("ajaxPostExample", "ajax", { - url: "/myRestFulApi", - type: "POST" - }) + url: "/myRestFulApi", + type: "POST" +}); // later in code amplify.request("ajaxPostExample", @@ -142,7 +142,7 @@ amplify.request("ajaxPostExample", type: "foo", id: "bar" }, - function (data) { + data => { data.foo; // bar } ); @@ -165,7 +165,7 @@ amplify.request("twitter-search", { term: "amplifyjs" } ); amplify.request.define("twitter-mentions", "ajax", { url: "http://search.twitter.com/search.json", dataType: "jsonp", - dataMap: function (data) { + dataMap: data => { return { q: "@" + data.user }; @@ -176,9 +176,9 @@ amplify.request("twitter-mentions", { user: "amplifyjs" }); // Setting up and using decoders -//Example: +// Example: -var appEnvelopeDecoder: amplify.Decoder = function (data, status, xhr, success, error) { +var appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => { if (data.status === "success") { success(data.data); } else if (data.status === "fail" || data.status === "error") { @@ -188,7 +188,7 @@ var appEnvelopeDecoder: amplify.Decoder = function (data, status, xhr, success, } }; -//a new decoder can be added to the amplifyDecoders interface +// a new decoder can be added to the amplifyDecoders interface declare module "amplify" { interface Decoders { appEnvelope: amplify.Decoder; @@ -197,7 +197,7 @@ declare module "amplify" { amplify.request.decoders.appEnvelope = appEnvelopeDecoder; -//but you can also just add it via an index +// but you can also just add it via an index amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder; @@ -209,10 +209,10 @@ amplify.request.define("decoderExample", "ajax", { amplify.request({ resourceId: "decoderExample", - success: function (data) { + success(data) { data.foo; // bar }, - error: function (message, level) { + error(message, level) { alert("always handle errors with alerts."); } }); @@ -224,7 +224,7 @@ amplify.request({ amplify.request.define("decoderSingleExample", "ajax", { url: "/myAjaxUrl", type: "POST", - decoder: function (data, status, xhr, success, error) { + decoder(data, status, xhr, success, error) { if (data.status === "success") { success(data.data); } else if (data.status === "fail" || data.status === "error") { @@ -237,10 +237,10 @@ amplify.request.define("decoderSingleExample", "ajax", { amplify.request({ resourceId: "decoderSingleExample", - success: function (data) { + success: data => { data.foo; // bar }, - error: function (message, level) { + error: (message, level) => { alert("always handle errors with alerts."); } }); @@ -250,14 +250,14 @@ amplify.request({ // amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition. amplify.request.define("statusExample1", "ajax", { - //... + // ... }); amplify.request({ resourceId: "statusExample1", - success: function (data, status) { + success: (data, status) => { }, - error: function (data, status) { + error: (data, status) => { } }); diff --git a/amplify/index.d.ts b/amplify/index.d.ts index d0e8d5b620..1e62e57a01 100644 --- a/amplify/index.d.ts +++ b/amplify/index.d.ts @@ -162,7 +162,9 @@ declare namespace amplify { * Publish a message. * topic: The name of the message to publish. * Any additional parameters will be passed to the subscriptions. - * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. + * amplify.publish returns a boolean indicating whether any subscriptions returned false. + * The return value is true if none of the subscriptions returned false, and false otherwise. + * Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. */ publish(topic: string, ...args: any[]): boolean; diff --git a/amplify/tslint.json b/amplify/tslint.json index 2d6cd90f81..fe03bea79d 100644 --- a/amplify/tslint.json +++ b/amplify/tslint.json @@ -4,4 +4,4 @@ "forbidden-types": false, "unified-signatures": false } -} \ No newline at end of file +} diff --git a/amqplib/amqplib-tests.ts b/amqplib/amqplib-tests.ts index b17128653a..24dade85dc 100644 --- a/amqplib/amqplib-tests.ts +++ b/amqplib/amqplib-tests.ts @@ -31,11 +31,11 @@ var anqpAssertExchangeReplies: amqp.Replies.AssertExchange; import amqpcb = require('amqplib/callback_api'); amqpcb.connect('amqp://localhost', (err, connection) => { - if(!err) { + if (!err) { connection.createChannel((err, channel) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { - if(!err) { + if (!err) { channel.sendToQueue('myQueue', new Buffer(msg)); } }); @@ -45,11 +45,11 @@ amqpcb.connect('amqp://localhost', (err, connection) => { }); amqpcb.connect('amqp://localhost', (err, connection) => { - if(!err) { + if (!err) { connection.createChannel((err, channel) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { - if(!err) { + if (!err) { channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString())); } }); diff --git a/amqplib/tslint.json b/amqplib/tslint.json index 9bc375c06b..105f5736e6 100644 --- a/amqplib/tslint.json +++ b/amqplib/tslint.json @@ -3,4 +3,4 @@ "rules": { "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/angular-gridster/angular-gridster-tests.ts b/angular-gridster/angular-gridster-tests.ts index 7333a20f4d..7af4908d2d 100644 --- a/angular-gridster/angular-gridster-tests.ts +++ b/angular-gridster/angular-gridster-tests.ts @@ -21,7 +21,7 @@ myApp.run(["gridsterConfig", (gridsterConfig: angular.gridster.GridsterConfig) = gridsterConfig.floating = true; gridsterConfig.swapping = true; gridsterConfig.draggable = { enabled: true}; - gridsterConfig.resizable = { enabled: true, + gridsterConfig.resizable = { enabled: true, handles: ["n", "s", "e", "w", "ne", "se", "sw", "nw"]}; } ]); \ No newline at end of file diff --git a/angular-gridster/index.d.ts b/angular-gridster/index.d.ts index de60d6377b..fc0e990d41 100644 --- a/angular-gridster/index.d.ts +++ b/angular-gridster/index.d.ts @@ -32,7 +32,7 @@ declare module "angular" { // width of grid columns. "auto" will divide the width of the grid evenly among the columns colWidth?: string; - // height of grid rows. 'match' will make it the same as the column width, a numeric value will be interpreted as pixels, + // height of grid rows. 'match' will make it the same as the column width, a numeric value will be interpreted as pixels, // '/2' is half the column width, '*5' is five times the column width, etc. rowHeight?: string; @@ -84,7 +84,7 @@ declare module "angular" { // options to pass to resizable handler resizable?: { - // whether the items are resizable + // whether the items are resizable enabled?: boolean; // location of the resize handles @@ -104,7 +104,7 @@ declare module "angular" { // options to pass to draggable handler draggable?: { - // whether the items are resizable + // whether the items are resizable enabled?: boolean; // Distance in pixels from the edge of the viewport after which the viewport should scroll, relative to pointer @@ -142,4 +142,4 @@ declare module "angular" { col: number; } } -} \ No newline at end of file +} diff --git a/angular-gridster/tslint.json b/angular-gridster/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/angular-gridster/tslint.json +++ b/angular-gridster/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts index 9118cd92c2..0e27fe3b60 100644 --- a/angular-material/index.d.ts +++ b/angular-material/index.d.ts @@ -106,6 +106,7 @@ declare module 'angular' { onComplete?: Function; onRemoving?: Function; skipHide?: boolean; + multiple?: boolean; fullscreen?: boolean; // default: false } diff --git a/angular-mocks/angular-mocks-tests.ts b/angular-mocks/angular-mocks-tests.ts index 8ea42e4122..cabbf7c578 100644 --- a/angular-mocks/angular-mocks-tests.ts +++ b/angular-mocks/angular-mocks-tests.ts @@ -118,6 +118,7 @@ httpBackendService.flush(); httpBackendService.flush(1234); httpBackendService.resetExpectations(); httpBackendService.verifyNoOutstandingExpectation(); +httpBackendService.verifyNoOutstandingExpectation(false); httpBackendService.verifyNoOutstandingRequest(); requestHandler = httpBackendService.expect('GET', 'http://test.local'); diff --git a/angular-mocks/index.d.ts b/angular-mocks/index.d.ts index ddded4d0a8..8b94fab445 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -132,8 +132,9 @@ declare module 'angular' { /** * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. + * @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code. */ - verifyNoOutstandingExpectation(): void; + verifyNoOutstandingExpectation(digest?: boolean): void; /** * Verifies that there are no outstanding requests that need to be flushed. diff --git a/angular-translate/index.d.ts b/angular-translate/index.d.ts index 19e1962fab..3b911ba313 100644 --- a/angular-translate/index.d.ts +++ b/angular-translate/index.d.ts @@ -51,8 +51,8 @@ declare module 'angular' { cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; fallbackLanguage(langKey?: string[]): string; - instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; - instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string }; + instant(translationId: string, interpolateParams?: any, interpolationId?: string, forceLanguage?: string, sanitizeStrategy?: string): string; + instant(translationId: string[], interpolateParams?: any, interpolationId?: string, forceLanguage?: string, sanitizeStrategy?: string): { [key: string]: string }; isPostCompilingEnabled(): boolean; preferredLanguage(langKey?: string): string; proposedLanguage(): string; diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index 16eaff3b39..15f0f2b661 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -7,6 +7,7 @@ testApp.config(( $buttonConfig: ng.ui.bootstrap.IButtonConfig, $datepickerConfig: ng.ui.bootstrap.IDatepickerConfig, $datepickerPopupConfig: ng.ui.bootstrap.IDatepickerPopupConfig, + $dropdownConfig: ng.ui.bootstrap.IDropdownConfig, $modalProvider: ng.ui.bootstrap.IModalProvider, $paginationConfig: ng.ui.bootstrap.IPaginationConfig, $pagerConfig: ng.ui.bootstrap.IPagerConfig, @@ -47,13 +48,18 @@ testApp.config(( $datepickerConfig.showWeeks = false; $datepickerConfig.startingDay = 1; $datepickerConfig.yearRange = 10; - - + $datepickerConfig.monthColumns = 3; + $datepickerConfig.yearColumns = 9; + $datepickerConfig.yearRows = 6; + $datepickerConfig.ngModelOptions.allowInvalid = false; + $datepickerConfig.ngModelOptions.timezone = "EST"; + $datepickerConfig.ngModelOptions.updateOn = "click"; /** * $datepickerPopupConfig tests */ + $datepickerPopupConfig.altInputFormats = ["mm/dd/YYYY", "mm-dd-YY"]; $datepickerPopupConfig.appendToBody = true; $datepickerPopupConfig.currentText = 'Select Today'; $datepickerPopupConfig.clearText = 'Reset Selection'; @@ -63,8 +69,18 @@ testApp.config(( $datepickerPopupConfig.datepickerPopupTemplateUrl = 'template.html'; $datepickerPopupConfig.datepickerTemplateUrl = 'template.html'; $datepickerPopupConfig.html5Types.date = 'MM-dd-yyyy'; + $datepickerPopupConfig.html5Types['datetime-local'] = 'yyyy-MM-ddTHH:mm:ss.sss'; + $datepickerPopupConfig.html5Types.month = 'yyyy-MM'; $datepickerPopupConfig.onOpenFocus = false; $datepickerPopupConfig.showButtonBar = false; + $datepickerPopupConfig.placement = "auto bottom left"; + + + /** + * $dropdownConfig tests + */ + $dropdownConfig.appendToOpenClass = "some-thing"; + $dropdownConfig.openClass = "show"; /** @@ -77,6 +93,7 @@ testApp.config(( * $paginationConfig tests */ $paginationConfig.boundaryLinks = true; + $paginationConfig.boundaryLinkNumbers = true; $paginationConfig.directionLinks = false; $paginationConfig.firstText = 'First Page'; $paginationConfig.itemsPerPage = 25; @@ -88,6 +105,7 @@ testApp.config(( $paginationConfig.rotate = false; $paginationConfig.templateUrl = 'template.html'; $paginationConfig.totalItems = 13; + $paginationConfig.forceEllipses = true; /** @@ -121,11 +139,14 @@ testApp.config(( $timepickerConfig.hourStep = 2; $timepickerConfig.meridians = ['-AM-', '-PM-']; $timepickerConfig.minuteStep = 5; + $timepickerConfig.secondStep = 5; $timepickerConfig.mousewheel = false; $timepickerConfig.readonlyInput = true; $timepickerConfig.showMeridian = false; $timepickerConfig.arrowkeys = false; $timepickerConfig.showSpinners = false; + $timepickerConfig.showSeconds = true; + $timepickerConfig.templateUrl = "template.html"; /** * $tooltipProvider tests @@ -134,6 +155,7 @@ testApp.config(( placement: 'bottom', animation: false, popupDelay: 1000, + popupCloseDelay: 1000, appendToBody: true, trigger: 'mouseenter hover', useContentExp: true, diff --git a/angular-ui-bootstrap/index.d.ts b/angular-ui-bootstrap/index.d.ts index 73043c4e7a..bc80d96b5a 100644 --- a/angular-ui-bootstrap/index.d.ts +++ b/angular-ui-bootstrap/index.d.ts @@ -11,6 +11,7 @@ export type IAccordionConfig = angular.ui.bootstrap.IAccordionConfig; export type IButtonConfig = angular.ui.bootstrap.IButtonConfig; export type IDatepickerConfig = angular.ui.bootstrap.IDatepickerConfig; export type IDatepickerPopupConfig = angular.ui.bootstrap.IDatepickerPopupConfig; +export type IDropdownConfig = angular.ui.bootstrap.IDropdownConfig; export type IModalProvider = angular.ui.bootstrap.IModalProvider; export type IModalService = angular.ui.bootstrap.IModalService; export type IModalServiceInstance = angular.ui.bootstrap.IModalServiceInstance; @@ -54,6 +55,11 @@ declare module 'angular' { toggleEvent?: string; } + interface IDropdownConfigNgOptions extends angular.INgModelOptions { + allowInvalid?: boolean; + timezone?: string; + } + interface IDatepickerConfig { /** * Format of day in month. @@ -155,7 +161,7 @@ declare module 'angular' { /** * Defines the initial date, when no model value is specified. - * + * * @default null */ initDate?: any; @@ -166,9 +172,45 @@ declare module 'angular' { * @default false */ shortcutPropagation?: boolean; + + /** + * The number of columns displayed in month selection. + * + * @default 3 + */ + monthColumns?: number; + + /** + * The number of columns displayed in year selection. + * + * @default 5 + */ + yearColumns?: number; + + /** + * The number of rows displayed in year selection + * + * @default 4 + */ + yearRows?: number; + + /** + * All supported angular ngModelOptions plus some + * + * @default {} + */ + ngModelOptions?: IDropdownConfigNgOptions } interface IDatepickerPopupConfig { + + /** + * A list of alternate formats acceptable for manual entry. + * + * @default [] + */ + altInputFormats?: string[]; + /** * The format for displayed dates. * @@ -247,8 +289,26 @@ declare module 'angular' { * @default true */ onOpenFocus?: boolean; + + /** + * Passing in 'auto' separated by a space before the placement will enable auto positioning, e.g: "auto bottom-left". The popup will attempt to position where it fits in the closest scrollable ancestor. + * + * @default 'auto bottom-left' + */ + placement?: string; } + interface IDropdownConfig { + /** + * @default: 'uib-dropdown-open' + */ + appendToOpenClass?: string; + + /** + * @default: 'open' + */ + openClass?: string; + } interface IModalProvider { /** @@ -543,6 +603,13 @@ declare module 'angular' { */ boundaryLinks?: boolean; + /** + * Whether to always display the first and last page numbers. If max-size is smaller than the number of pages, then the first and last page numbers are still shown with ellipses in-between as necessary. NOTE: max-size refers to the center of the range. This option may add up to 2 more numbers on each side of the displayed range for the end value and what would be an ellipsis but is replaced by a number because it is sequential. + * + * @default false + */ + boundaryLinkNumbers?: boolean; + /** * Text for First button. * @@ -563,6 +630,13 @@ declare module 'angular' { * @default 'template/pagination/pagination.html' */ templateUrl?: string; + + /** + * Also displays ellipses when rotate is true and max-size is smaller than the number of pages. + * + * @default false + */ + forceEllipses?: boolean; } interface IPagerConfig { @@ -679,6 +753,13 @@ declare module 'angular' { */ minuteStep?: number; + /** + * Number of seconds to increase or decrease when using a button. + * + * @default 1 + */ + secondStep?: number; + /** * Whether to display 12H or 24H mode. * @@ -720,6 +801,20 @@ declare module 'angular' { * @default true */ showSpinners?: boolean; + + /** + * Show seconds input. + * + * @default false + */ + showSeconds?: boolean; + + /** + * Add the ability to override the template used on the component. + * + * @default 'uib/template/timepicker/timepicker.html' + */ + templateUrl?: string; } @@ -739,12 +834,19 @@ declare module 'angular' { animation?: boolean; /** - * For how long should the user have to have the mouse over the element before the tooltip shows (in milliseconds)? + * Popup delay in milliseconds until it opens. * * @default 0 */ popupDelay?: number; + /** + * For how long should the tooltip remain open after the close trigger event? + * + * @default 0 + */ + popupCloseDelay?: number; + /** * Should the tooltip be appended to `$body` instead of the parent element? * diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index 38ddcca26b..174c319f97 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -143,7 +143,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService { private $state: ng.ui.IStateService ) { $rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event)); - $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => + $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => this.onStateNotFound(event, unfoundState, fromState, fromParams)); } @@ -157,8 +157,8 @@ class UrlLocatorTestService implements IUrlLocatorTestService { // Note that we do not concern ourselves with what to do if this request fails, // because if it fails, the web page will be redirected away to the login screen. - this.$http({ url: "/api/me", method: "GET" }).success((user: any) => { - this.currentUser = user; + this.$http({ url: "/api/me", method: "GET" }).then((response: ng.IHttpPromiseCallbackArg) => { + this.currentUser = response.data; // sync the ui-state with the location in the browser, which effectively // restarts the state change that was stopped previously @@ -166,14 +166,14 @@ class UrlLocatorTestService implements IUrlLocatorTestService { }); } } - + private onStateNotFound(event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) { var unfoundTo: string = unfoundState.to; var unfoundToParams: {} = unfoundState.toParams; - var unfoundOptions: ng.ui.IStateOptions = unfoundState.options + var unfoundOptions: ng.ui.IStateOptions = unfoundState.options } private stateServiceTest() { diff --git a/angular-wizard/index.d.ts b/angular-wizard/index.d.ts index 862a6e3ae8..81af2e80c7 100644 --- a/angular-wizard/index.d.ts +++ b/angular-wizard/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mgonto/angular-wizard // Definitions by: Marko Jurisic , Ronald Wildenberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as angular from 'angular'; diff --git a/angular/angular-component-router.d.ts b/angular/angular-component-router.d.ts index 99ae821c72..92458331d6 100644 --- a/angular/angular-component-router.d.ts +++ b/angular/angular-component-router.d.ts @@ -1,9 +1,9 @@ +/* tslint:disable:dt-header variable-name */ // Type definitions for Angular JS 1.5 component router // Project: http://angularjs.org // Definitions by: David Reher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace angular { /** * `Instruction` is a tree of {@link ComponentInstruction}s with all the information needed @@ -263,7 +263,7 @@ declare namespace angular { /** * Subscribe to URL updates from the router */ - subscribe(onNext: (value: any) => void): Object; + subscribe(onNext: (value: any) => void): {}; /** * Removes the contents of this router's outlet and all descendant outlets diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index c6ee7c7a00..4e1f33ce47 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -1,4 +1,3 @@ - // issue: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/369 // https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js /** @@ -7,46 +6,49 @@ * License: MIT */ +/* tslint:disable:no-empty no-shadowed-variable */ + class AuthService { /** * Holds all the requests which failed due to 401 response, * so they can be re-requested in future, once login is completed. */ - buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; + buffer: Array<{ config: ng.IRequestConfig; deferred: ng.IDeferred; }> = []; /** * Required by HTTP interceptor. * Function is attached to provider to be invisible for regular users of this service. */ - pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + pushToBuffer = (config: ng.IRequestConfig, deferred: ng.IDeferred) => { this.buffer.push({ - config: config, - deferred: deferred + config, + deferred }); } $get = [ - '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { - var $http: ng.IHttpService; //initialized later because of circular dependency problem + '$rootScope', '$injector', ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) => { + let $http: ng.IHttpService; // initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { $http = $http || $injector.get('$http'); - $http(config).then(function (response) { + $http(config).then(response => { deferred.resolve(response); }); } function retryAll() { - for (var i = 0; i < this.buffer.length; ++i) { - retry(this.buffer[i].config, this.buffer[i].deferred); + for (const request of this.buffer) { + retry(request.config, request.deferred); } + this.buffer = []; } return { - loginConfirmed: function () { + loginConfirmed() { $rootScope.$broadcast('event:auth-loginConfirmed'); retryAll(); } - } + }; } ]; } @@ -59,20 +61,20 @@ angular.module('http-auth-interceptor', []) * $http interceptor. * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. */ - .config(['$httpProvider', 'authServiceProvider', function ($httpProvider: ng.IHttpProvider, authServiceProvider: any) { + .config(['$httpProvider', 'authServiceProvider', ($httpProvider: ng.IHttpProvider, authServiceProvider: any) => { - $httpProvider.defaults.headers.common = {'Authorization': 'Bearer token'}; + $httpProvider.defaults.headers.common = {Authorization: 'Bearer token'}; $httpProvider.defaults.headers.get['Authorization'] = 'Bearer token'; - $httpProvider.defaults.headers.post['Authorization'] = function (config:ng.IRequestConfig):string { return 'Bearer token'; } + $httpProvider.defaults.headers.post['Authorization'] = (config: ng.IRequestConfig) => 'Bearer token'; - var interceptor = ['$rootScope', '$q', function ($rootScope: ng.IScope, $q: ng.IQService) { + const interceptor = ['$rootScope', '$q', ($rootScope: ng.IScope, $q: ng.IQService) => { function success(response: ng.IHttpPromiseCallbackArg) { return response; } function error(response: ng.IHttpPromiseCallbackArg) { if (response.status === 401) { - var deferred = $q.defer(); + const deferred = $q.defer(); authServiceProvider.pushToBuffer(response.config, deferred); $rootScope.$broadcast('event:auth-loginRequired'); return deferred.promise; @@ -81,22 +83,18 @@ angular.module('http-auth-interceptor', []) return $q.reject(response); } - return function (promise: ng.IHttpPromise) { - return promise.then(success, error); - } - - }]; + return (promise: ng.IHttpPromise) => promise.then(success, error); + }]; $httpProvider.interceptors.push(interceptor); }]); - namespace HttpAndRegularPromiseTests { interface Person { firstName: string; lastName: string; } - interface ExpectedResponse extends Person { } + type ExpectedResponse = Person; interface SomeControllerScope extends ng.IScope { person: Person; @@ -106,13 +104,8 @@ namespace HttpAndRegularPromiseTests { nothing?: string; } - var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { - $http.get("http://somewhere/some/resource") - .success((data: ExpectedResponse) => { - $scope.person = data; - }); - - $http.get("http://somewhere/some/resource") + function someController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) { + $http.get('http://somewhere/some/resource') .then((response: ng.IHttpPromiseCallbackArg) => { // typing lost, so something like // var i: number = response.data @@ -120,7 +113,7 @@ namespace HttpAndRegularPromiseTests { $scope.person = response.data; }); - $http.get("http://somewhere/some/resource") + $http.get('http://somewhere/some/resource') .then((response: ng.IHttpPromiseCallbackArg) => { // typing lost, so something like // var i: number = response.data @@ -128,47 +121,33 @@ namespace HttpAndRegularPromiseTests { $scope.person = response.data; }); - var aPromise: ng.IPromise = $q.when({ firstName: "Jack", lastName: "Sparrow" }); + const aPromise: ng.IPromise = $q.when({ firstName: 'Jack', lastName: 'Sparrow' }); aPromise.then((person: Person) => { $scope.person = person; }); - var bPromise: ng.IPromise = $q.when(42); + const bPromise: ng.IPromise = $q.when(42); bPromise.then((answer: number) => { $scope.theAnswer = answer; }); - var cPromise: ng.IPromise = $q.when(["a", "b", "c"]); + const cPromise: ng.IPromise = $q.when(['a', 'b', 'c']); cPromise.then((letters: string[]) => { $scope.letters = letters; }); // When $q.when is passed an IPromise, it returns an IPromise - var dPromise: ng.IPromise = $q.when($q.when("ALBATROSS!")); + const dPromise: ng.IPromise = $q.when($q.when('ALBATROSS!')); dPromise.then((snack: string) => { $scope.snack = snack; }); // $q.when may be called without arguments - var ePromise: ng.IPromise = $q.when(); + const ePromise: ng.IPromise = $q.when(); ePromise.then(() => { - $scope.nothing = "really nothing"; + $scope.nothing = 'really nothing'; }); } - - // Test that we can pass around a type-checked success/error Promise Callback - var anotherController: Function = ($scope: SomeControllerScope, $http: - ng.IHttpService, $q: ng.IQService) => { - - var buildFooData: Function = () => 42; - - var doFoo: Function = (callback: ng.IHttpPromiseCallback) => { - $http.get('/foo', buildFooData()) - .success(callback); - } - - doFoo((data: any) => console.log(data)); - } } // Test for AngularJS Syntax @@ -178,9 +157,9 @@ namespace My.Namespace { } // IModule Registering Test -var mod = angular.module('tests', []); -mod.controller('name', function ($scope: ng.IScope) { }); -mod.controller('name', ['$scope', function ($scope: ng.IScope) { }]); +let mod = angular.module('tests', []); +mod.controller('name', ($scope: ng.IScope) => { }); +mod.controller('name', ['$scope', ($scope: ng.IScope) => { }]); mod.controller('name', class { // Uncommenting the next line should lead to a type error because this signature isn't compatible // with the signature of the `$onChanges` hook: @@ -188,8 +167,8 @@ mod.controller('name', class { }); mod.controller({ MyCtrl: class{}, - MyCtrl2: function() {}, - MyCtrl3: ['$fooService', function($fooService: any) { }] + MyCtrl2() {}, + MyCtrl3: ['$fooService', ($fooService: any) => { }] }); mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { return (scope, el, attrs) => { @@ -201,7 +180,7 @@ mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { scope.$watch(() => foo, () => el.text(foo)); }; }); -mod.directive('myDirectiveB', ['$rootScope', function ($rootScope: ng.IRootScopeService) { +mod.directive('myDirectiveB', ['$rootScope', ($rootScope: ng.IRootScopeService) => { return { link(scope, el, attrs) { el.click(e => { @@ -218,38 +197,37 @@ mod.directive({ template: 'my-bar-dir.tpl.html' })] }); -mod.factory('name', function ($scope: ng.IScope) { }) -mod.factory('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.factory('name', ($scope: ng.IScope) => {}); +mod.factory('name', ['$scope', ($scope: ng.IScope) => {}]); mod.factory({ - name1: function (foo: any) { }, - name2: ['foo', function (foo: any) { }] + name1(foo: any) {}, + name2: ['foo', (foo: any) => {}] }); -mod.filter('name', function ($scope: ng.IScope) { }) -mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.filter('name', ($scope: ng.IScope) => {}); +mod.filter('name', ['$scope', ($scope: ng.IScope) => {}]); mod.filter({ - name1: function (foo: any) { }, - name2: ['foo', function (foo: any) { }] + name1(foo: any) {}, + name2: ['foo', (foo: any) => {}] }); -mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } }) +mod.provider('name', ($scope: ng.IScope) => ({ $get: () => { } })); mod.provider('name', TestProvider); -mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.provider('name', ['$scope', ($scope: ng.IScope) => {}]); mod.provider(My.Namespace); -mod.service('name', function ($scope: ng.IScope) { }) -mod.service('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.service('name', ($scope: ng.IScope) => {}); +mod.service('name', ['$scope', ($scope: ng.IScope) => {}]); mod.service({ MyCtrl: class{}, - MyCtrl2: function() {}, - MyCtrl3: ['$fooService', function($fooService: any) { }] + MyCtrl2: () => {}, // tslint:disable-line:object-literal-shorthand + MyCtrl3: ['$fooService', ($fooService: any) => {}] }); mod.constant('name', 23); -mod.constant('name', "23"); +mod.constant('name', '23'); mod.constant(My.Namespace); mod.value('name', 23); -mod.value('name', "23"); +mod.value('name', '23'); mod.value(My.Namespace); -mod.decorator('name', function($scope:ng.IScope){ }); -mod.decorator('name', ['$scope', function($scope: ng.IScope){ }]); - +mod.decorator('name', ($scope: ng.IScope) => {}); +mod.decorator('name', ['$scope', ($scope: ng.IScope) => {}]); class TestProvider implements ng.IServiceProvider { constructor(private $scope: ng.IScope) { @@ -261,35 +239,46 @@ class TestProvider implements ng.IServiceProvider { // QProvider tests angular.module('qprovider-test', []) - .config(['$qProvider', function ($qProvider: ng.IQProvider) { + .config(['$qProvider', ($qProvider: ng.IQProvider) => { const provider: ng.IQProvider = $qProvider.errorOnUnhandledRejections(false); const currentValue: boolean = $qProvider.errorOnUnhandledRejections(); }]); // Promise signature tests -var foo: ng.IPromise; +let foo: ng.IPromise; foo.then((x) => { // x is inferred to be a number - return "asdf"; + x.toFixed(); + return 'asdf'; }).then((x) => { // x is inferred to be string - x.length; + const len = x.length; return 123; +}, (e) => { + return anyOf2([123], toPromise([123])); // IPromise | T, both are good for the 2nd arg of .then() }).then((x) => { - // x is infered to be a number - x.toFixed(); + // x is infered to be a number or number[] + if (Array.isArray(x)) { + x[0].toFixed(); + } else { + x.toFixed(); + } return; -}).then((x) => { - // x is infered to be void - // Typescript will prevent you to actually use x as a local variable +}).catch(e => { + return foo || 123; // IPromise | T, both are good for .catch() +}).then(x => { + // x is infered to be void | number + x && x.toFixed(); + // Typescript will prevent you to actually use x as a local variable before you check it is not void // Try object: return { a: 123 }; }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + // Try a promise var y: ng.IPromise; - return y; + var condition: boolean; + return condition ? y : x.a; // IPromise | T, both are good for the 1st arg of .then() }).then((x) => { // x is infered to be a number, which is the resolved value of a promise x.toFixed(); @@ -306,14 +295,22 @@ namespace TestQ { e: number; f: boolean; } + interface TOther { + g: string; + h: number; + } var tResult: TResult; var promiseTResult: angular.IPromise; var tValue: TValue; var promiseTValue: angular.IPromise; + var tOther: TOther; + var promiseTOther: angular.IPromise; var $q: angular.IQService; var promiseAny: angular.IPromise; + const assertPromiseType = (arg: angular.IPromise) => arg; + // $q constructor { let result: angular.IPromise; @@ -336,26 +333,32 @@ namespace TestQ { result = $q.all([promiseAny, promiseAny]); } { - let result: angular.IPromise<{[id: string]: any;}>; + let result: angular.IPromise<{[id: string]: any; }>; result = $q.all({a: promiseAny, b: promiseAny}); } { - let result: angular.IPromise<{a: number; b: string;}>; - result = $q.all<{a: number; b: string;}>({a: promiseAny, b: promiseAny}); + let result: angular.IPromise<{a: number; b: string; }>; + result = $q.all<{a: number; b: string; }>({a: promiseAny, b: promiseAny}); } - // $q.defer { let result: angular.IDeferred; result = $q.defer(); + result.resolve(tResult); + var anyValue: any; + result.reject(anyValue); + result.promise.then(result => { + return $q.resolve(result); + }); } // $q.reject { - let result: angular.IPromise; + let result: angular.IPromise; result = $q.reject(); result = $q.reject(''); + result.catch(() => 5).then(x => x.toFixed()); } // $q.resolve @@ -367,6 +370,8 @@ namespace TestQ { let result: angular.IPromise; result = $q.resolve(tResult); result = $q.resolve(promiseTResult); + result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); + result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); } // $q.when @@ -376,6 +381,8 @@ namespace TestQ { } { let result: angular.IPromise; + let resultOther: angular.IPromise; + result = $q.when(tResult); result = $q.when(promiseTResult); @@ -384,38 +391,40 @@ namespace TestQ { result = $q.when(tValue, (result: TValue) => tResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => tResult); - result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => promiseTResult); - result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther, (any) => any); } } - -var httpFoo: ng.IHttpPromise; +let httpFoo: ng.IHttpPromise; httpFoo.then((x) => { // When returning a promise the generic type must be inferred. - var innerPromise : ng.IPromise; + var innerPromise: ng.IPromise; return innerPromise; }).then((x) => { // must still be number. x.toFixed(); }); -httpFoo.success((data, status, headers, config) => { - var h = headers("test"); +httpFoo.then((response: ng.IHttpPromiseCallbackArg) => { + const h = response.headers('test'); h.charAt(0); - var hs = headers(); - hs["content-type"].charAt(1); + const hs = response.headers(); + hs['content-type'].charAt(1); }); - // Deferred signature tests namespace TestDeferred { var any: any; @@ -432,8 +441,8 @@ namespace TestDeferred { // deferred.resolve { let result: void; - result = deferred.resolve(); - result = deferred.resolve(tResult); + result = deferred.resolve() as void; + result = deferred.resolve(tResult) as void; } // deferred.reject @@ -458,7 +467,7 @@ namespace TestDeferred { } namespace TestInjector { - let $injector: angular.auto.IInjectorService; + var $injector: angular.auto.IInjectorService; $injector.strictDi = true; @@ -466,23 +475,28 @@ namespace TestInjector { $injector.annotate(() => {}, true); } - // Promise signature tests namespace TestPromise { - var result: any; var any: any; interface TResult { + kind: 'result'; a: number; b: string; c: boolean; } + interface TOther { + kind: 'other'; d: number; e: string; f: boolean; } + function isTResult(x: TResult | TOther): x is TResult { + return x.kind === 'result'; + } + var tresult: TResult; var tresultPromise: ng.IPromise; var tresultHttpPromise: ng.IHttpPromise; @@ -492,65 +506,100 @@ namespace TestPromise { var totherHttpPromise: ng.IHttpPromise; var promise: angular.IPromise; + var $q: angular.IQService; + + const assertPromiseType = (arg: angular.IPromise) => arg; + const reject = $q.reject(); // promise.then - result = >promise.then((result) => any); - result = >promise.then((result) => any, (any) => any); - result = >promise.then((result) => any, (any) => any, (any) => any); + assertPromiseType(promise.then((result) => any)); + assertPromiseType(promise.then((result) => any, (any) => any)); + assertPromiseType(promise.then((result) => any, (any) => any, (any) => any)); - result = >promise.then((result) => result); - result = >promise.then((result) => result, (any) => any); - result = >promise.then((result) => result, (any) => any, (any) => any); - result = >promise.then((result) => tresultPromise); - result = >promise.then((result) => tresultPromise, (any) => any); - result = >promise.then((result) => tresultPromise, (any) => any, (any) => any); - result = >>promise.then((result) => tresultHttpPromise); - result = >>promise.then((result) => tresultHttpPromise, (any) => any); - result = >>promise.then((result) => tresultHttpPromise, (any) => any, (any) => any); + assertPromiseType(promise.then((result) => reject)); + assertPromiseType(promise.then((result) => reject, (any) => reject)); + assertPromiseType(promise.then((result) => reject, (any) => reject, (any) => any)); - result = >promise.then((result) => tother); - result = >promise.then((result) => tother, (any) => any); - result = >promise.then((result) => tother, (any) => any, (any) => any); - result = >promise.then((result) => totherPromise); - result = >promise.then((result) => totherPromise, (any) => any); - result = >promise.then((result) => totherPromise, (any) => any, (any) => any); - result = >>promise.then((result) => totherHttpPromise); - result = >>promise.then((result) => totherHttpPromise, (any) => any); - result = >>promise.then((result) => totherHttpPromise, (any) => any, (any) => any); + assertPromiseType(promise.then((result) => result)); + assertPromiseType(promise.then((result) => tresult)); + assertPromiseType(promise.then((result) => tresultPromise)); + assertPromiseType(promise.then((result) => result, (any) => any)); + assertPromiseType(promise.then((result) => result, (any) => any, (any) => any)); + assertPromiseType(promise.then((result) => result, (any) => reject, (any) => any)); + + assertPromiseType(promise.then((result) => anyOf2(reject, result))); + assertPromiseType(promise.then((result) => anyOf3(result, tresultPromise, reject))); + assertPromiseType(promise.then( + (result) => anyOf3(reject, result, tresultPromise), + (reason) => anyOf3(reject, tresult, tresultPromise) + )); + + assertPromiseType>(promise.then((result) => tresultHttpPromise)); + + assertPromiseType(promise.then((result) => result, (any) => tother)); + assertPromiseType(promise.then( + (result) => anyOf3(reject, result, totherPromise), + (reason) => anyOf3(reject, tother, tresultPromise) + )); + + assertPromiseType(promise.then( + (result) => anyOf3(tresultPromise, result, totherPromise) + )); + + assertPromiseType(promise.then((result) => result, (any) => tother, (any) => any)); + assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise)); + assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise, (any) => any)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise, (any) => any)); + + assertPromiseType(promise.then((result) => tother)); + assertPromiseType(promise.then((result) => tother, (any) => any)); + assertPromiseType(promise.then((result) => tother, (any) => any, (any) => any)); + assertPromiseType(promise.then((result) => totherPromise)); + assertPromiseType(promise.then((result) => totherPromise, (any) => any)); + assertPromiseType(promise.then((result) => totherPromise, (any) => any, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any, (any) => any)); + + assertPromiseType(promise.then((result) => tresult, (any) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); // promise.catch - result = >promise.catch((err) => any); - result = >promise.catch((err) => tresult); - result = >promise.catch((err) => tresultPromise); - result = >>promise.catch((err) => tresultHttpPromise); - result = >promise.catch((err) => tother); - result = >promise.catch((err) => totherPromise); - result = >>promise.catch((err) => totherHttpPromise); + assertPromiseType(promise.catch((err) => err)); + assertPromiseType(promise.catch((err) => any)); + assertPromiseType(promise.catch((err) => tresult)); + assertPromiseType(promise.catch((err) => anyOf2(tresult, reject))); + assertPromiseType(promise.catch((err) => anyOf3(tresult, tresultPromise, reject))); + assertPromiseType(promise.catch((err) => tresultPromise)); + assertPromiseType>(promise.catch((err) => tresultHttpPromise)); + assertPromiseType(promise.catch((err) => tother)); + assertPromiseType(promise.catch((err) => totherPromise)); + assertPromiseType>(promise.catch((err) => totherHttpPromise)); + + assertPromiseType(promise.catch((err) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); // promise.finally - result = >promise.finally(() => any); - result = >promise.finally(() => tresult); - result = >promise.finally(() => tother); + assertPromiseType(promise.finally(() => any)); + assertPromiseType(promise.finally(() => tresult)); + assertPromiseType(promise.finally(() => tother)); } - function test_angular_forEach() { - var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; - var log: string[] = []; - angular.forEach(values, function (value, key) { + const values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + const log: string[] = []; + angular.forEach(values, (value, key) => { this.push(key + ': ' + value); }, log); - //expect(log).toEqual(['name: misko', 'gender: male']); + // expect(log).toEqual(['name: misko', 'gender: male']); } // angular.element() tests -var element = angular.element("div.myApp"); -var scope: ng.IScope = element.scope(); -var isolateScope: ng.IScope = element.isolateScope(); +let element = angular.element('div.myApp'); +let scope: ng.IScope = element.scope(); +let isolateScope: ng.IScope = element.isolateScope(); isolateScope = element.find('div.foo').isolateScope(); isolateScope = element.children().isolateScope(); - // $timeout signature tests namespace TestTimeout { interface TResult { @@ -590,25 +639,24 @@ namespace TestTimeout { } } - -function test_IAttributes(attributes: ng.IAttributes){ +function test_IAttributes(attributes: ng.IAttributes) { return attributes; } test_IAttributes({ - $normalize: function (classVal){ return "foo" }, - $addClass: function (classVal){}, - $removeClass: function(classVal){}, - $updateClass: function(newClass, oldClass){}, - $set: function(key, value){}, - $observe: function(name: any, fn: any){ + $normalize(classVal) { return 'foo'; }, + $addClass(classVal) {}, + $removeClass(classVal) {}, + $updateClass(newClass, oldClass) {}, + $set(key, value) {}, + $observe(name: any, fn: any) { return fn; }, $attr: {} }); class SampleDirective implements ng.IDirective { - public restrict = 'A'; + restrict = 'A'; name = 'doh'; compile(templateElement: ng.IAugmentedJQuery) { @@ -617,7 +665,7 @@ class SampleDirective implements ng.IDirective { }; } - static instance():ng.IDirective { + static instance(): ng.IDirective { return new SampleDirective(); } @@ -627,7 +675,7 @@ class SampleDirective implements ng.IDirective { } class SampleDirective2 implements ng.IDirective { - public restrict = 'EAC'; + restrict = 'EAC'; compile(templateElement: ng.IAugmentedJQuery) { return { @@ -635,7 +683,7 @@ class SampleDirective2 implements ng.IDirective { }; } - static instance():ng.IDirective { + static instance(): ng.IDirective { return new SampleDirective2(); } @@ -654,23 +702,16 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo $interpolate('', true)(scope); $interpolate('', true, 'html')(scope); $interpolate('', true, 'html', true)(scope); - var defer = $q.defer(); + const defer = $q.defer(); defer.reject(); defer.resolve(); - defer.promise.then(function(d) { - return d; - }).then(function(): any { - return null; - }, function(): any { - return null; - }) - .catch((): any => { - return null; - }) - .finally((): any => { - return null; - }); - var promise = new $q((resolve) => { + defer.promise.then(d => d) + .then( + (): any => null, + (): any => null) + .catch((): any => null) + .finally((): any => null); + let promise = new $q((resolve) => { resolve(); }); @@ -689,39 +730,39 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo // test from https://docs.angularjs.org/guide/directive angular.module('docsSimpleDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { template: 'Name: {{customer.name}} Address: {{customer.address}}' }; }); angular.module('docsTemplateUrlDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { templateUrl: 'my-customer.html' }; }); angular.module('docsRestrictDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', templateUrl: 'my-customer.html' @@ -729,19 +770,19 @@ angular.module('docsRestrictDirective', []) }); angular.module('docsScopeProblemExample', []) - .controller('NaomiController', ['$scope', function($scope: any) { + .controller('NaomiController', ['$scope', ($scope: any) => { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) - .controller('IgorController', ['$scope', function($scope: any) { + .controller('IgorController', ['$scope', ($scope: any) => { $scope.customer = { name: 'Igor', address: '123 Somewhere' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', templateUrl: 'my-customer.html' @@ -749,11 +790,11 @@ angular.module('docsScopeProblemExample', []) }); angular.module('docsIsolateScopeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; $scope.igor = { name: 'Igor', address: '123 Somewhere' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', scope: { @@ -764,11 +805,11 @@ angular.module('docsIsolateScopeDirective', []) }); angular.module('docsIsolationExample', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; }]) - .directive('myCustomer', function() { + .directive('myCustomer', () => { return { restrict: 'E', scope: { @@ -779,31 +820,31 @@ angular.module('docsIsolationExample', []) }); angular.module('docsTimeDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.format = 'M/d/yy h:mm:ss a'; }]) - .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) { + .directive('myCurrentTime', ['$interval', 'dateFilter', ($interval: any, dateFilter: any) => { return { - link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) { - var format: any, + link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) { + let format: any, timeoutId: any; function updateTime() { element.text(dateFilter(new Date(), format)); } - scope.$watch(attrs['myCurrentTime'], function (value: any) { + scope.$watch(attrs['myCurrentTime'], (value: any) => { format = value; updateTime(); }); - element.on('$destroy', function () { + element.on('$destroy', () => { $interval.cancel(timeoutId); }); // start the UI update process; save the timeoutId for canceling - timeoutId = $interval(function () { + timeoutId = $interval(() => { updateTime(); // update DOM }, 1000); } @@ -811,10 +852,10 @@ angular.module('docsTimeDirective', []) }]); angular.module('docsTransclusionDirective', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.name = 'Tobias'; }]) - .directive('myDialog', function() { + .directive('myDialog', () => { return { restrict: 'E', transclude: true, @@ -823,47 +864,46 @@ angular.module('docsTransclusionDirective', []) }); angular.module('docsTransclusionExample', []) - .controller('Controller', ['$scope', function($scope: any) { + .controller('Controller', ['$scope', ($scope: any) => { $scope.name = 'Tobias'; }]) - .directive('myDialog', function() { + .directive('myDialog', () => { return { restrict: 'E', transclude: true, scope: {}, templateUrl: 'my-dialog.html', - link: function (scope: ng.IScope, element: ng.IAugmentedJQuery) { + link(scope: ng.IScope, element: ng.IAugmentedJQuery) { scope['name'] = 'Jeff'; } }; }); - angular.module('docsIsoFnBindExample', []) - .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + .controller('Controller', ['$scope', '$timeout', ($scope: any, $timeout: any) => { $scope.name = 'Tobias'; - $scope.hideDialog = function () { + $scope.hideDialog = () => { $scope.dialogIsHidden = true; - $timeout(function () { + $timeout(() => { $scope.dialogIsHidden = false; }, 2000); }; }]) - .directive('myDialog', function() { + .directive('myDialog', () => { return { restrict: 'E', transclude: true, scope: { - 'close': '&onClose' + close: '&onClose' }, templateUrl: 'my-dialog-close.html' }; }); angular.module('dragModule', []) - .directive('myDraggable', ['$document', function($document: any) { - return function(scope: any, element: any, attr: any) { - var startX = 0, startY = 0, x = 0, y = 0; + .directive('myDraggable', ['$document', ($document: any) => { + return (scope: any, element: any, attr: any) => { + let startX = 0, startY = 0, x = 0, y = 0; element.css({ position: 'relative', @@ -872,7 +912,7 @@ angular.module('dragModule', []) cursor: 'pointer' }); - element.on('mousedown', function(event: any) { + element.on('mousedown', (event: any) => { // Prevent default dragging of selected content event.preventDefault(); startX = event.pageX - x; @@ -898,22 +938,22 @@ angular.module('dragModule', []) }]); angular.module('docsTabsExample', []) - .directive('myTabs', function() { + .directive('myTabs', () => { return { restrict: 'E', transclude: true, scope: {}, - controller: function($scope: ng.IScope) { - var panes: any = $scope['panes'] = []; + controller($scope: ng.IScope) { + const panes: any = $scope['panes'] = []; - $scope['select'] = function(pane: any) { - angular.forEach(panes, function(pane: any) { + $scope['select'] = (pane: any) => { + angular.forEach(panes, (pane: any) => { pane.selected = false; }); pane.selected = true; }; - this.addPane = function(pane: any) { + this.addPane = (pane: any) => { if (panes.length === 0) { $scope['select'](pane); } @@ -923,7 +963,7 @@ angular.module('docsTabsExample', []) templateUrl: 'my-tabs.html' }; }) - .directive('myPane', function() { + .directive('myPane', () => { return { require: '^myTabs', restrict: 'E', @@ -931,7 +971,7 @@ angular.module('docsTabsExample', []) scope: { title: '@' }, - link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { + link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { tabsCtrl.addPane(scope); }, templateUrl: 'my-pane.html' @@ -939,13 +979,13 @@ angular.module('docsTabsExample', []) }); angular.module('multiSlotTranscludeExample', []) - .directive('dropDownMenu', function() { + .directive('dropDownMenu', () => { return { transclude: { button: 'button', list: 'ul', }, - link: function(scope, element, attrs, ctrl, transclude) { + link(scope, element, attrs, ctrl, transclude) { // without scope transclude().appendTo(element); transclude(clone => clone.appendTo(element)); @@ -960,52 +1000,52 @@ angular.module('multiSlotTranscludeExample', []) angular.module('componentExample', []) .component('counter', { - require: {'ctrl': '^ctrl'}, + require: {ctrl: '^ctrl'}, bindings: { count: '=' }, controller: 'CounterCtrl', controllerAs: 'counterCtrl', - template: function () { + template() { return ''; }, transclude: { - 'el': 'target' + el: 'target' } }) .component('anotherCounter', { - controller: function(){}, + controller() {}, require: { - 'parent': '^parentCtrl' + parent: '^parentCtrl' }, template: '', transclude: true }); -interface copyExampleUser { +interface ICopyExampleUser { name?: string; email?: string; gender?: string; } -interface copyExampleScope { +interface ICopyExampleScope { - user: copyExampleUser; - master: copyExampleUser; - update: (copyExampleUser: copyExampleUser) => any; + user: ICopyExampleUser; + master: ICopyExampleUser; + update: (copyExampleUser: ICopyExampleUser) => any; reset: () => any; } angular.module('copyExample', []) - .controller('ExampleController', ['$scope', function ($scope: copyExampleScope) { + .controller('ExampleController', ['$scope', ($scope: ICopyExampleScope) => { $scope.master = { }; - $scope.update = function (user) { + $scope.update = user => { // Example with 1 argument $scope.master = angular.copy(user); }; - $scope.reset = function () { + $scope.reset = () => { // Example with 2 arguments angular.copy($scope.master, $scope.user); }; @@ -1022,9 +1062,14 @@ namespace locationTests { */ // given url http://example.com/#/some/path?foo=bar&baz=xoxo - var searchObject = $location.search(); + const searchObject = $location.search(); // => {foo: 'bar', baz: 'xoxo'} + function assert(condition: boolean) { + if (!condition) { + throw new Error(); + } + } // set foo to 'yipee' $location.search('foo', 'yipee'); @@ -1041,29 +1086,29 @@ namespace locationTests { // in browser with HTML5 history support: // open http://example.com/#!/a -> rewrite to http://example.com/a // (replacing the http://example.com/#!/a history record) - $location.path() == '/a' + assert($location.path() === '/a'); $location.path('/foo'); - $location.absUrl() == 'http://example.com/foo' + assert($location.absUrl() === 'http://example.com/foo'); - $location.search() == {} + assert($location.search() === {}); $location.search({ a: 'b', c: true }); - $location.absUrl() == 'http://example.com/foo?a=b&c' + assert($location.absUrl() === 'http://example.com/foo?a=b&c'); $location.path('/new').search('x=y'); - $location.url() == 'new?x=y' - $location.absUrl() == 'http://example.com/new?x=y' + assert($location.url() === 'new?x=y'); + assert($location.absUrl() === 'http://example.com/new?x=y'); // in browser without html5 history support: // open http://example.com/new?x=y -> redirect to http://example.com/#!/new?x=y // (again replacing the http://example.com/new?x=y history item) - $location.path() == '/new' - $location.search() == { x: 'y' } + assert($location.path() === '/new'); + assert($location.search() === { x: 'y' }); $location.path('/foo/bar'); - $location.path() == '/foo/bar' - $location.url() == '/foo/bar?x=y' - $location.absUrl() == 'http://example.com/#!/foo/bar?x=y' + assert($location.path() === '/foo/bar'); + assert($location.url() === '/foo/bar?x=y'); + assert($location.absUrl() === 'http://example.com/#!/foo/bar?x=y'); } // NgModelController @@ -1073,16 +1118,16 @@ function NgModelControllerTyping() { var $q: angular.IQService; // See https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$validators - ngModel.$validators['validCharacters'] = function(modelValue, viewValue) { - var value = modelValue || viewValue; + ngModel.$validators['validCharacters'] = (modelValue, viewValue) => { + const value = modelValue || viewValue; return /[0-9]+/.test(value) && /[a-z]+/.test(value) && /[A-Z]+/.test(value) && /\W+/.test(value); }; - ngModel.$asyncValidators['uniqueUsername'] = function(modelValue, viewValue) { - var value = modelValue || viewValue; + ngModel.$asyncValidators['uniqueUsername'] = (modelValue, viewValue) => { + const value = modelValue || viewValue; return $http.get('/api/users/' + value). then(function resolved() { return $q.reject('exists'); @@ -1092,67 +1137,67 @@ function NgModelControllerTyping() { }; } -var $filter: angular.IFilterService; +let $filter: angular.IFilterService; function testFilter() { var items: string[]; - $filter("filter")(items, "test"); - $filter("filter")(items, {name: "test"}); - $filter("filter")(items, (val, index, array) => { + $filter('filter')(items, 'test'); + $filter('filter')(items, {name: 'test'}); + $filter('filter')(items, (val, index, array) => { return true; }); - $filter("filter")(items, (val, index, array) => { + $filter('filter')(items, (val, index, array) => { return true; }, (actual, expected) => { - return actual == expected; + return actual === expected; }); } function testCurrency() { - $filter("currency")(126); - $filter("currency")(126, "$", 2); + $filter('currency')(126); + $filter('currency')(126, '$', 2); } function testNumber() { - $filter("number")(167); - $filter("number")(167, 2); + $filter('number')(167); + $filter('number')(167, 2); } function testDate() { - $filter("date")(new Date()); - $filter("date")(new Date(), 'yyyyMMdd'); - $filter("date")(new Date(), 'yyyyMMdd', '+0430'); + $filter('date')(new Date()); + $filter('date')(new Date(), 'yyyyMMdd'); + $filter('date')(new Date(), 'yyyyMMdd', '+0430'); } function testJson() { - var json: string = $filter("json")({test:true}, 2); + const json: string = $filter('json')({test: true}, 2); } function testLowercase() { - var lower: string = $filter("lowercase")('test'); + const lower: string = $filter('lowercase')('test'); } function testUppercase() { - var lower: string = $filter("uppercase")('test'); + const lower: string = $filter('uppercase')('test'); } function testLimitTo() { - var limitTo = $filter("limitTo"); - var filtered: number[] = $filter("limitTo")([1,2,3], 5); - filtered = $filter("limitTo")([1,2,3], 5, 2); + const limitTo = $filter('limitTo'); + let filtered: number[] = $filter('limitTo')([1, 2, 3], 5); + filtered = $filter('limitTo')([1, 2, 3], 5, 2); - var filteredString: string = $filter("limitTo")("124", 4); - filteredString = $filter("limitTo")(124, 4); + let filteredString: string = $filter('limitTo')('124', 4); + filteredString = $filter('limitTo')(124, 4); } function testOrderBy() { - var filtered: number[] = $filter("orderBy")([1,2,3], "test"); - filtered = $filter("orderBy")([1,2,3], "test", true); - filtered = $filter("orderBy")([1,2,3], ['prop1', 'prop2']); - filtered = $filter("orderBy")([1,2,3], (val: number) => 1); - var filtered2: string[] = $filter("orderBy")(["1","2","3"], (val: string) => 1); - filtered2 = $filter("orderBy")(["1","2","3"], [ + let filtered: number[] = $filter('orderBy')([1, 2, 3], 'test'); + filtered = $filter('orderBy')([1, 2, 3], 'test', true); + filtered = $filter('orderBy')([1, 2, 3], ['prop1', 'prop2']); + filtered = $filter('orderBy')([1, 2, 3], (val: number) => 1); + let filtered2: string[] = $filter('orderBy')(['1', '2', '3'], (val: string) => 1); + filtered2 = $filter('orderBy')(['1', '2', '3'], [ (val: string) => 1, (val: string) => 2 ]); @@ -1160,28 +1205,26 @@ function testOrderBy() { function testDynamicFilter() { // Test with separate variables - var dateFilter = $filter("date"); - var myDate = new Date(); - dateFilter(myDate , "EEE, MMM d"); + const dateFilter = $filter('date'); + const myDate = new Date(); + dateFilter(myDate , 'EEE, MMM d'); // Test with dynamic name - var filterName = 'date'; - var dynDateFilter = $filter(filterName); + const filterName = 'date'; + const dynDateFilter = $filter(filterName); dynDateFilter(new Date()); } -interface MyCustomFilter { - (value: string): string; -} +type MyCustomFilter = (value: string) => string; function testCustomFilter() { - var filterCustom = $filter('custom'); - var filtered: string = filterCustom("test"); + const filterCustom = $filter('custom'); + const filtered: string = filterCustom('test'); } function parseTyping() { var $parse: angular.IParseService; - var compiledExp = $parse('a.b.c'); + const compiledExp = $parse('a.b.c'); if (compiledExp.constant) { return compiledExp({}); } else if (compiledExp.literal) { @@ -1191,14 +1234,14 @@ function parseTyping() { function parseWithParams() { var $parse: angular.IParseService; - var compiledExp = $parse('a.b.c', () => null); - var compiledExp = $parse('a.b.c', null, false); + const compiledExp1 = $parse('a.b.c', () => null); + const compiledExp2 = $parse('a.b.c', null, false); } function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService { if (mode === 'debug') { - return angular.bootstrap(element, ['main', function($provide: ng.auto.IProvideService) { - $provide.decorator('$rootScope', function($delegate: ng.IRootScopeService) { + return angular.bootstrap(element, ['main', ($provide: ng.auto.IProvideService) => { + $provide.decorator('$rootScope', ($delegate: ng.IRootScopeService) => { $delegate['debug'] = true; }); }, 'debug-helpers'], { @@ -1211,8 +1254,22 @@ function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjector } function testIHttpParamSerializerJQLikeProvider() { - let serializer: angular.IHttpParamSerializer; + var serializer: angular.IHttpParamSerializer; serializer({ - a: "b" + a: 'b' }); } + +function anyOf2(v1: T1, v2: T2) { + return Math.random() < 0.5 ? v1 : v2; +} + +function anyOf3(v1: T1, v2: T2, v3: T3) { + const rnd = Math.random(); + return rnd < 0.33 ? v1 : rnd < 0.66 ? v2 : v3; +} + +function toPromise(val: T): ng.IPromise { + var p: ng.IPromise; + return p; +} diff --git a/angular/index.d.ts b/angular/index.d.ts index f3f9fc87a6..bbbbdb021a 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -27,7 +27,7 @@ import ng = angular; /////////////////////////////////////////////////////////////////////////////// declare namespace angular { - type Injectable = T | (string | T)[]; + type Injectable = T | Array; // not directly implemented, but ensures that constructed class implements $get interface IServiceProviderClass { @@ -64,7 +64,7 @@ declare namespace angular { * @param config an object for defining configuration options for the application. The following keys are supported: * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. */ - bootstrap(element: string|Element|JQuery|Document, modules?: (string|Function|any[])[], config?: IAngularBootstrapConfig): auto.IInjectorService; + bootstrap(element: string|Element|JQuery|Document, modules?: Array, config?: IAngularBootstrapConfig): auto.IInjectorService; /** * Creates a deep copy of source, which should be an object or an array. @@ -122,7 +122,7 @@ declare namespace angular { fromJson(json: string): any; identity(arg?: T): T; injector(modules?: any[], strictDi?: boolean): auto.IInjectorService; - isArray(value: any): value is Array; + isArray(value: any): value is any[]; isDate(value: any): value is Date; isDefined(value: any): boolean; isElement(value: any): boolean; @@ -411,8 +411,8 @@ declare namespace angular { $invalid: boolean; } - //Allows tuning how model updates are done. - //https://docs.angularjs.org/api/ng/directive/ngModelOptions + // Allows tuning how model updates are done. + // https://docs.angularjs.org/api/ng/directive/ngModelOptions interface INgModelOptions { updateOn?: string; debounce?: any; @@ -514,7 +514,7 @@ declare namespace angular { $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; - $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; + $watchGroup(watchExpressions: Array<{ (scope: IScope): any }>, listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; $parent: IScope; $root: IRootScopeService; @@ -662,9 +662,9 @@ declare namespace angular { } interface IFilterOrderByItem { - value: any, - type: string, - index: any + value: any; + type: string; + index: any; } interface IFilterOrderByComparatorFunc { @@ -756,7 +756,7 @@ declare namespace angular { * @param comparator Function used to determine the relative order of value pairs. * @return An array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate. */ - (array: T[], expression: string|((value: T) => any)|(((value: T) => any)|string)[], reverse?: boolean, comparator?: IFilterOrderByComparatorFunc): T[]; + (array: T[], expression: string|((value: T) => any)|Array<((value: T) => any)|string>, reverse?: boolean, comparator?: IFilterOrderByComparatorFunc): T[]; } /** @@ -1023,7 +1023,7 @@ declare namespace angular { all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise ]): IPromise<[T1, T2, T3, T4]>; all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise]): IPromise<[T1, T2, T3]>; all(values: [T1 | IPromise, T2 | IPromise]): IPromise<[T1, T2]>; - all(promises: IPromise[]): IPromise; + all(promises: Array>): IPromise; /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. * @@ -1044,13 +1044,14 @@ declare namespace angular { * * @param reason Constant, message, exception or an object representing the rejection reason. */ - reject(reason?: any): IPromise; + reject(reason?: any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. * * @param value Value or a promise */ resolve(value: IPromise|T): IPromise; + resolve(value: IPromise|T2): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. */ @@ -1061,7 +1062,10 @@ declare namespace angular { * @param value Value or a promise */ when(value: IPromise|T): IPromise; - when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + when(value: IPromise|T2): IPromise; + when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult): IPromise; + when(value: T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: null | undefined | ((reason: any) => any), notifyCallback?: (state: any) => any): IPromise; + when(value: IPromise, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: (reason: any) => TResult2 | IPromise, notifyCallback?: (state: any) => any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. */ @@ -1090,15 +1094,20 @@ declare namespace angular { interface IPromise { /** * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. - * The successCallBack may return IPromise for when a $q.reject() needs to be returned + * The successCallBack may return IPromise for when a $q.reject() needs to be returned * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. */ - then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise; + + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: (reason: any) => IPromise|TCatch, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback: (reason: any) => IPromise|TCatch2, notifyCallback?: (state: any) => any): IPromise; /** * Shorthand for promise.then(null, errorCallback) */ - catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + catch(onRejected: (reason: any) => IPromise|TCatch): IPromise; + catch(onRejected: (reason: any) => IPromise|TCatch2): IPromise; /** * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. @@ -1183,7 +1192,7 @@ declare namespace angular { */ size: number; - //...: any additional properties from the options object when creating the cache. + // ...: any additional properties from the options object when creating the cache. }; /** @@ -1245,6 +1254,16 @@ declare namespace angular { debugInfoEnabled(): boolean; debugInfoEnabled(enabled: boolean): ICompileProvider; + /** + * Call this method to enable/disable whether directive controllers are assigned bindings before calling the controller's constructor. + * If enabled (true), the compiler assigns the value of each of the bindings to the properties of the controller object before the constructor of this object is called. + * If disabled (false), the compiler calls the constructor first before assigning bindings. + * Defaults to false. + * See: https://docs.angularjs.org/api/ng/provider/$compileProvider#preAssignBindingsEnabled + */ + preAssignBindingsEnabled(): boolean; + preAssignBindingsEnabled(enabled: boolean): ICompileProvider; + /** * Sets the number of times $onChanges hooks can trigger new changes before giving up and assuming that the model is unstable. * Increasing the TTL could have performance implications, so you should not change it without proper justification. @@ -1284,11 +1303,11 @@ declare namespace angular { } interface ITemplateLinkingFunctionOptions { - parentBoundTranscludeFn?: ITranscludeFunction, + parentBoundTranscludeFn?: ITranscludeFunction; transcludeControllers?: { [controller: string]: { instance: IController } - }, - futureParentElement?: JQuery + }; + futureParentElement?: JQuery; } /** @@ -1486,18 +1505,6 @@ declare namespace angular { } interface IHttpPromise extends IPromise> { - /** - * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. - * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. - * @deprecated - */ - success?(callback: IHttpPromiseCallback): IHttpPromise; - /** - * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. - * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. - * @deprecated - */ - error?(callback: IHttpPromiseCallback): IHttpPromise; } // See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228 @@ -1510,7 +1517,9 @@ declare namespace angular { (data: any, headersGetter: IHttpHeadersGetter, status: number): any; } - type HttpHeaderType = {[requestType: string]:string|((config:IRequestConfig) => string)}; + interface HttpHeaderType { + [requestType: string]: string|((config: IRequestConfig) => string); + } interface IHttpRequestConfigHeaders { [requestType: string]: any; @@ -1593,7 +1602,7 @@ declare namespace angular { * Register service factories (names or implementations) for interceptors which are called before and after * each request. */ - interceptors: (string | Injectable)[]; + interceptors: Array>; useApplyAsync(): boolean; useApplyAsync(value: boolean): IHttpProvider; @@ -1603,7 +1612,7 @@ declare namespace angular { * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. */ - useLegacyPromiseExtensions(value:boolean) : boolean | IHttpProvider; + useLegacyPromiseExtensions(value: boolean): boolean | IHttpProvider; } /////////////////////////////////////////////////////////////////////////// @@ -1687,16 +1696,15 @@ declare namespace angular { valueOf(value: any): any; } - /////////////////////////////////////////////////////////////////////////// // SCEDelegateProvider // see http://docs.angularjs.org/api/ng.$sceDelegateProvider /////////////////////////////////////////////////////////////////////////// interface ISCEDelegateProvider extends IServiceProvider { - resourceUrlBlacklist(blacklist: any[]): void; - resourceUrlWhitelist(whitelist: any[]): void; resourceUrlBlacklist(): any[]; + resourceUrlBlacklist(blacklist: any[]): void; resourceUrlWhitelist(): any[]; + resourceUrlWhitelist(whitelist: any[]): void; } /** @@ -1936,33 +1944,33 @@ declare namespace angular { annotate(fn: Function, strictDi?: boolean): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string, caller?: string): T; - get(name: '$anchorScroll'): IAnchorScrollService - get(name: '$cacheFactory'): ICacheFactoryService - get(name: '$compile'): ICompileService - get(name: '$controller'): IControllerService - get(name: '$document'): IDocumentService - get(name: '$exceptionHandler'): IExceptionHandlerService - get(name: '$filter'): IFilterService - get(name: '$http'): IHttpService - get(name: '$httpBackend'): IHttpBackendService - get(name: '$httpParamSerializer'): IHttpParamSerializer - get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer - get(name: '$interpolate'): IInterpolateService - get(name: '$interval'): IIntervalService - get(name: '$locale'): ILocaleService - get(name: '$location'): ILocationService - get(name: '$log'): ILogService - get(name: '$parse'): IParseService - get(name: '$q'): IQService - get(name: '$rootElement'): IRootElementService - get(name: '$rootScope'): IRootScopeService - get(name: '$sce'): ISCEService - get(name: '$sceDelegate'): ISCEDelegateService - get(name: '$templateCache'): ITemplateCacheService - get(name: '$templateRequest'): ITemplateRequestService - get(name: '$timeout'): ITimeoutService - get(name: '$window'): IWindowService - get(name: '$xhrFactory'): IXhrFactory + get(name: '$anchorScroll'): IAnchorScrollService; + get(name: '$cacheFactory'): ICacheFactoryService; + get(name: '$compile'): ICompileService; + get(name: '$controller'): IControllerService; + get(name: '$document'): IDocumentService; + get(name: '$exceptionHandler'): IExceptionHandlerService; + get(name: '$filter'): IFilterService; + get(name: '$http'): IHttpService; + get(name: '$httpBackend'): IHttpBackendService; + get(name: '$httpParamSerializer'): IHttpParamSerializer; + get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer; + get(name: '$interpolate'): IInterpolateService; + get(name: '$interval'): IIntervalService; + get(name: '$locale'): ILocaleService; + get(name: '$location'): ILocationService; + get(name: '$log'): ILogService; + get(name: '$parse'): IParseService; + get(name: '$q'): IQService; + get(name: '$rootElement'): IRootElementService; + get(name: '$rootScope'): IRootScopeService; + get(name: '$sce'): ISCEService; + get(name: '$sceDelegate'): ISCEDelegateService; + get(name: '$templateCache'): ITemplateCacheService; + get(name: '$templateRequest'): ITemplateRequestService; + get(name: '$timeout'): ITimeoutService; + get(name: '$window'): IWindowService; + get(name: '$xhrFactory'): IXhrFactory; has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): T; invoke(inlineAnnotatedFunction: any[]): any; @@ -2027,7 +2035,7 @@ declare namespace angular { declare global { interface JQuery { // TODO: events, how to define? - //$destroy + // $destroy find(element: any): JQuery; find(obj: JQuery): JQuery; diff --git a/angular/tslint.json b/angular/tslint.json new file mode 100644 index 0000000000..7ba374959e --- /dev/null +++ b/angular/tslint.json @@ -0,0 +1,33 @@ +{ + "extends": "../tslint.json", + "rules": { + "class-name": true, + "curly": true, + "max-line-length": false, + "no-consecutive-blank-lines": true, + "no-shadowed-variable": true, + "quotemark": [ + true, + "single" + ], + "align": true, + "callable-types": false, + "forbidden-types": false, + "indent": [ + true, + "spaces" + ], + "interface-name": false, + "linebreak-style": [ + true, + "LF" + ], + "no-empty-interface": false, + "unified-signatures": false, + "variable-name": [ + true, + "check-format" + ], + "void-return": false + } +} diff --git a/antd/index.d.ts b/antd/index.d.ts index e2865c6927..f262eda45f 100644 --- a/antd/index.d.ts +++ b/antd/index.d.ts @@ -2,6 +2,7 @@ // Project: http://ant.design // Definitions by: bang88 , Bruce Mitchener // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/apex.js/tslint.json b/apex.js/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/apex.js/tslint.json +++ b/apex.js/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/aphrodite/index.d.ts b/aphrodite/index.d.ts index 2f53e133fd..63eba46927 100644 --- a/aphrodite/index.d.ts +++ b/aphrodite/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Khan/aphrodite // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from "react"; diff --git a/arcgis-rest-api/index.d.ts b/arcgis-rest-api/index.d.ts index 2b28b32fac..65a02a4367 100644 --- a/arcgis-rest-api/index.d.ts +++ b/arcgis-rest-api/index.d.ts @@ -135,7 +135,8 @@ export type esriGeometryType = "esriGeometryPoint" | "esriGeometryMultipoint" | export type Color = [number, number, number, number]; export type SimpleMarkerSymbolStyle = "esriSMSCircle" | "esriSMSCross" | "esriSMSDiamond" | "esriSMSSquare" | "esriSMSX" | "esriSMSTriangle"; export type SimpleLineSymbolStyle = "esriSLSDash" | "esriSLSDashDot" | "esriSLSDashDotDot" | "esriSLSDot" | "esriSLSNull" | "esriSLSSolid"; -export type SimpleFillSymbolStyle = "esriSFSBackwardDiagonal" | "esriSFSCross" | "esriSFSDiagonalCross" | "esriSFSForwardDiagonal" | "esriSFSHorizontal" | "esriSFSNull" | "esriSFSSolid" | "esriSFSVertical"; +export type SimpleFillSymbolStyle = + "esriSFSBackwardDiagonal" | "esriSFSCross" | "esriSFSDiagonalCross" | "esriSFSForwardDiagonal" | "esriSFSHorizontal" | "esriSFSNull" | "esriSFSSolid" | "esriSFSVertical"; export type SymbolType = "esriSLS" | "esriSMS" | "esriSFS" | "esriPMS" | "esriPFS" | "esriTS"; export interface Symbol { @@ -168,12 +169,12 @@ export interface SimpleFillSymbol extends Symbol { "type": "esriSFS"; "style"?: SimpleFillSymbolStyle; "color"?: Color; - "outline"?: SimpleLineSymbol; //if outline has been specified + "outline"?: SimpleLineSymbol; // if outline has been specified } export interface PictureSourced { - "url"?: string; //Relative URL for static layers and full URL for dynamic layers. Access relative URL using http:////images/ - "imageData"?: string; //""; + "url"?: string; // Relative URL for static layers and full URL for dynamic layers. Access relative URL using http:////images/ + "imageData"?: string; // ""; "contentType"?: string; "width"?: number; "height"?: number; @@ -189,14 +190,14 @@ export interface PictureMarkerSymbol extends MarkerSymbol, PictureSourced { export interface PictureFillSymbol extends Symbol, PictureSourced { "type": "esriPFS"; - "outline"?: SimpleLineSymbol; //if outline has been specified + "outline"?: SimpleLineSymbol; // if outline has been specified "xscale"?: number; "yscale"?: number; } export interface Font { - "family"?: string; //""; - "size"?: number; //; + "family"?: string; // ""; + "size"?: number; // ; "style"?: "italic" | "normal" | "oblique"; "weight"?: "bold" | "bolder" | "lighter" | "normal"; "decoration"?: "line-through" | "underline" | "none"; @@ -215,5 +216,5 @@ export interface TextSymbol extends MarkerSymbol { "rightToLeft"?: boolean; "kerning"?: boolean; "font"?: Font; - "text"?: string; //only applicable when specified as a client-side graphic. + "text"?: string; // only applicable when specified as a client-side graphic. } \ No newline at end of file diff --git a/arcgis-rest-api/tslint.json b/arcgis-rest-api/tslint.json index 2149d13884..377cc837d4 100644 --- a/arcgis-rest-api/tslint.json +++ b/arcgis-rest-api/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts b/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts index 48a06fcd02..2e9337793a 100644 --- a/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts +++ b/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts @@ -1,14 +1,14 @@ import utils = require("arcgis-to-geojson-utils"); import arcgisApi = require("arcgis-rest-api"); -let arcgisPoint: arcgisApi.Point = { +const arcgisPoint: arcgisApi.Point = { x: -122.6764, y: 45.5165, spatialReference: { wkid: 4326 } }; -let geojsonPoint: GeoJSON.Point = { +const geojsonPoint: GeoJSON.Point = { type: "Point", coordinates: [45.5165, -122.6764] }; diff --git a/arcgis-to-geojson-utils/tslint.json b/arcgis-to-geojson-utils/tslint.json index 2149d13884..377cc837d4 100644 --- a/arcgis-to-geojson-utils/tslint.json +++ b/arcgis-to-geojson-utils/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/archiver/index.d.ts b/archiver/index.d.ts index ea117239ac..665624143e 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -31,7 +31,6 @@ declare namespace archiver { } export interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; append(source: STREAM.Readable | Buffer | string, name: nameInterface): void; directory(dirpath: string, destpath: nameInterface | string): void; diff --git a/array-find-index/array-find-index-tests.ts b/array-find-index/array-find-index-tests.ts index 1443c50b77..0c7508af5e 100644 --- a/array-find-index/array-find-index-tests.ts +++ b/array-find-index/array-find-index-tests.ts @@ -3,6 +3,6 @@ import arrayFindIndex = require("array-find-index"); arrayFindIndex(['rainbow', 'unicorn', 'pony'], x => x === 'unicorn'); const ctx = {foo: 'rainbow'}; -arrayFindIndex(['rainbow', 'unicorn', 'pony'], function (x) { +arrayFindIndex(['rainbow', 'unicorn', 'pony'], function(x) { return x === this.foo; }, ctx); diff --git a/array-find-index/tslint.json b/array-find-index/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/array-find-index/tslint.json +++ b/array-find-index/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/artyom.js/artyom.js-tests.ts b/artyom.js/artyom.js-tests.ts index e70704ad4e..67e5908883 100644 --- a/artyom.js/artyom.js-tests.ts +++ b/artyom.js/artyom.js-tests.ts @@ -1,7 +1,7 @@ import artyomjs = require('artyom.js'); // Get an unique ArtyomJS instance -let artyom = artyomjs.ArtyomBuilder.getInstance(); +const artyom = artyomjs.ArtyomBuilder.getInstance(); // Add a command (not smart) artyom.addCommands({ diff --git a/artyom.js/index.d.ts b/artyom.js/index.d.ts index d96880395f..0b0f253827 100644 --- a/artyom.js/index.d.ts +++ b/artyom.js/index.d.ts @@ -403,7 +403,7 @@ declare namespace Artyom { /** * Says a random quote and returns it's object. - * @param data + * @param data */ sayRandom(data: any): any; @@ -423,14 +423,14 @@ declare namespace Artyom { artyomHey(): any; /** - * This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some + * This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some * values, do not make changes directly. */ getNativeApi(): any; /** * This function returns a boolean according to the SpeechRecognition status if artyom is listening, will return true. - * Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd + * Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd * events of the SpeechRecognition * @returns {Boolean} */ @@ -438,14 +438,14 @@ declare namespace Artyom { /** * This function returns a boolean according to the speechSynthesis status if artyom is speaking, will return true. - * Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd + * Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd * events of the speechSynthesis. * @returns {Boolean} */ isSpeaking(): boolean; /** - * The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour + * The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour * of artyom.say. Use this method to clear all spoken SpeechSynthesisUtterance unused objects. * @returns {Boolean} */ @@ -487,7 +487,7 @@ declare namespace Artyom { getVersion(): string; /** - * Add commands like an artisan. If you use artyom for simple + * Add commands like an artisan. If you use artyom for simple * tasks then probably you don't like to write a lot to achieve it. * Use the artisan syntax to write less, but with the same accuracy. * @disclaimer Not a promise-based implementation, just syntax. @@ -508,6 +508,6 @@ declare namespace Artyom { } -//tslint:disable-next-line:export-just-namespace +// tslint:disable-next-line:export-just-namespace export = Artyom; export as namespace Artyom; diff --git a/assert-plus/assert-plus-tests.ts b/assert-plus/assert-plus-tests.ts index ec1036e56f..f9f0b2fe3b 100644 --- a/assert-plus/assert-plus-tests.ts +++ b/assert-plus/assert-plus-tests.ts @@ -1,5 +1,5 @@ import * as assert from 'assert-plus'; -let arr = ['one', 'two']; +const arr = ['one', 'two']; assert.array(arr, ''); diff --git a/assert-plus/index.d.ts b/assert-plus/index.d.ts index e2bafe4eae..5de187cb85 100644 --- a/assert-plus/index.d.ts +++ b/assert-plus/index.d.ts @@ -7,262 +7,115 @@ import {Stream} from 'stream'; -/** - * - */ export function array(arr: any[], message ?: string): void; -/** - * - */ export function bool(bool: boolean, message ?: string): void; -/** - * - */ export function buffer(buffer: Buffer, message ?: string): void; -/** - * - */ export function func(func: any, message ?: string): void; -/** - * - */ export function number(number: number, message ?: string): void; -/** - * - */ export function finite(finite: number, message ?: string): void; -/** - * - */ export function object(obj: any, message ?: string): void; -/** - * - */ export function string(str: string, message ?: string): void; -/** - * - */ export function stream(stream: Stream, message ?: string): void; -/** - * - */ export function date(date: Date, message ?: string): void; -/** - * - */ export function regexp(regexp: RegExp, message ?: string): void; -/** - * - */ export function uuid(uuid: string, message ?: string): void; -/** - * - */ export function arrayOfArray(arr: any[][], message ?: string): void; -/** - * - */ export function arrayOfBool(arr: boolean[], message ?: string): void; -/** - * - */ export function arrayOfBuffer(arr: Buffer[], message ?: string): void; -/** - * - */ export function arrayOfFunc(arr: any[], message ?: string): void; -/** - * - */ export function arrayOfNumber(arr: number[], message ?: string): void; -/** - * - */ export function arrayOfFinite(arr: number[], message ?: string): void; -/** - * - */ export function arrayOfObject(arr: any[], message ?: string): void; -/** - * - */ export function arrayOfString(arr: string[], message ?: string): void; -/** - * - */ export function arrayOfStream(arr: Stream[], message ?: string): void; -/** - * - */ export function arrayOfDate(arr: Date[], message ?: string): void; -/** - * - */ export function arrayOfRegexp(arr: RegExp[], message ?: string): void; -/** - * - */ export function arrayOfUuid(arr: string[], message ?: string): void; -/** - * - */ export function optionalArray(arr: any[] | undefined, message ?: string): void; -/** - * - */ export function optionalBool(bool: boolean | undefined, message ?: string): void; -/** - * - */ export function optionalBuffer(buffer: Buffer | undefined, message ?: string): void; -/** - * - */ export function optionalFunc(options: any, message ?: string): void; -/** - * - */ export function optionalNumber(options: number | undefined, message ?: string): void; -/** - * - */ export function optionalFinite(options: number | undefined, message ?: string): void; -/** - * - */ export function optionalObject(options: any, message ?: string): void; -/** - * - */ export function optionalString(options: string | undefined, message ?: string): void; -/** - * - */ export function optionalStream(options: Stream | undefined, message ?: string): void; -/** - * - */ export function optionalDate(options: Date | undefined, message ?: string): void; -/** - * - */ export function optionalRegexp(options: RegExp | undefined, message ?: string): void; -/** - * - */ export function optionalUuid(options: string | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfArray(arr: any[][] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfBool(arr: boolean[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfBuffer(arr: Buffer[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfFunc(arr: any[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfNumber(arr: number[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfFinite(arr: number[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfObject(arr: any[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfString(arr: string[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfStream(arr: Stream[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfDate(arr: Date[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfRegexp(arr: RegExp[] | undefined, message ?: string): void; -/** - * - */ export function optionalArrayOfUuid(arr: string[] | undefined, message ?: string): void; -/** - * - */ export function AssertionError(options: any, message ?: string): void; /** * Throws an `AssertionError`. If `message` is falsy, the error message is set * as the values of `actual` and `expected` separated by the provided `operator`. * Otherwise, the error message is the value of `message`. - * + * * ```js * const assert = require('assert'); - * + * * assert.fail(1, 2, undefined, '>'); * // AssertionError: 1 > 2 - * + * * assert.fail(1, 2, 'whoops', '>'); * // AssertionError: whoops * ``` @@ -272,14 +125,14 @@ export function fail(actual: any, expected: any, message: any, operator: any): v /** * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. - * + * * If `value` is not truthy, an `AssertionError` is thrown with a `message` property * set equal to the value of the `message` parameter. * If the `message` parameter is `undefined`, a default error message is assigned. - * + * * ```js * const assert = require('assert'); - * + * * assert.ok(true); * // OK * assert.ok(1); @@ -297,21 +150,21 @@ export function ok(options: any, message ?: string): void; /** * Tests shallow, coercive equality between the actual and expected parameters * using the equal comparison operator ( `==` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.equal(1, 1); * // OK, 1 == 1 * assert.equal(1, '1'); * // OK, 1 == '1' - * + * * assert.equal(1, 2); * // AssertionError: 1 == 2 * assert.equal({a: {b: 1}}, {a: {b: 1}}); * //AssertionError: { a: { b: 1 } } == { a: { b: 1 } } * ``` - * + * * If the values are not equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -320,20 +173,20 @@ export function equal(actual: any, expected: any, message ?: string): void; /** * Tests shallow, coercive inequality with the not equal comparison operator ( `!=` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.notEqual(1, 2); * // OK - * + * * assert.notEqual(1, 1); * // AssertionError: 1 != 1 - * + * * assert.notEqual(1, '1'); * // AssertionError: 1 != '1' * ``` - * + * * If the values are equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -343,20 +196,20 @@ export function notEqual(actual: any, expected: any, message ?: string): void; /** * Tests for deep equality between the `actual` and `expected` parameters. * Primitive values are compared with the equal comparison operator ( `==` ). - * + * * Only enumerable "own" properties are considered. * The `deepEqual()` implementation does not test object prototypes, attached symbols, * or non-enumerable properties. This can lead to some potentially surprising results. * For example, the following example does not throw an `AssertionError` because * the properties on the Error object are non-enumerable: - * + * * ```js * // WARNING: This does not throw an AssertionError! * assert.deepEqual(Error('a'), Error('b')); * ``` - * + * * "Deep" equality means that the enumerable "own" properties of child objects are evaluated also. - * + * * If the values are not equal, an `AssertionError` is thrown with a `message` property * set equal to the value of the `message` parameter. If the `message` parameter is undefined, * a default error message is assigned. @@ -365,28 +218,28 @@ export function deepEqual(actual: T, expected: T, message ?: string): void; /** * Tests for any deep inequality. Opposite of `assert.deepEqual()`. - * + * * ```js * const assert = require('assert'); - * + * * const obj1 = { a : { b : 1 } }; * const obj2 = { a : { b : 2 } }; * const obj3 = { a : { b : 1 } }; * const obj4 = Object.create(obj1); - * + * * assert.notDeepEqual(obj1, obj1); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } - * + * * assert.notDeepEqual(obj1, obj2); * // OK, obj1 and obj2 are not deeply equal - * + * * assert.notDeepEqual(obj1, obj3); * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } - * + * * assert.notDeepEqual(obj1, obj4); * // OK, obj1 and obj2 are not deeply equal * ``` - * + * * If the values are deeply equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -395,20 +248,20 @@ export function notDeepEqual(actual: any, expected: any, message ?: string): voi /** * Tests strict equality as determined by the strict equality operator ( `===` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.strictEqual(1, 2); * // AssertionError: 1 === 2 - * + * * assert.strictEqual(1, 1); * // OK - * + * * assert.strictEqual(1, '1'); * // AssertionError: 1 === '1' * ``` - * + * * If the values are not strictly equal, an `AssertionError` is thrown with * a `message` property set equal to the value of the `message` parameter. * If the `message` parameter is undefined, a default error message is assigned. @@ -417,40 +270,37 @@ export function strictEqual(actual: T, expected: T, message ?: string): void; /** * Tests strict inequality as determined by the strict not equal operator ( `!==` ). - * + * * ```js * const assert = require('assert'); - * + * * assert.notStrictEqual(1, 2); * // OK - * + * * assert.notStrictEqual(1, 1); * // AssertionError: 1 !== 1 - * + * * assert.notStrictEqual(1, '1'); * // OK * ``` - * + * * If the values are strictly equal, an `AssertionError` is thrown with a `message` property * set equal to the value of the `message` parameter. If the `message` parameter is undefined, * a default error message is assigned. */ export function notStrictEqual(actual: any, expected: any, message ?: string): void; -/** - * - */ export function throws(block: any, error ?: any, message ?: string): void; /** * Asserts that the function `block` does not throw an error. See `assert.throws()` for more details. - * + * * When `assert.doesNotThrow()` is called, it will immediately call the `block` function. - * + * * If an error is thrown and it is the same type as that specified by the `error` parameter, * then an `AssertionError` is thrown. If the error is of a different type, * or if the `error` parameter is undefined, the error is propagated back to the caller. - * + * * The following, for instance, will throw the TypeError because there is no matching error type in the assertion: * ```js * assert.doesNotThrow( @@ -460,7 +310,7 @@ export function throws(block: any, error ?: any, message ?: string): void; * SyntaxError * ); * ``` - * + * * However, the following will result in an `AssertionError` with the message 'Got unwanted exception (TypeError)..': * ```js * assert.doesNotThrow( @@ -470,7 +320,7 @@ export function throws(block: any, error ?: any, message ?: string): void; * TypeError * ); * ``` - * + * * If an `AssertionError` is thrown and a value is provided for the `message` parameter, * the value of `message` will be appended to the `AssertionError` message: * ```js @@ -490,7 +340,7 @@ export function doesNotThrow(block: any, error ?: any, message ?: string): void; * Throws `value` if `value` is truthy. This is useful when testing the `error` argument in callbacks. * ```js * const assert = require('assert'); - * + * * assert.ifError(0); * // OK * assert.ifError(1); diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts index 197256ddd5..7c910d1765 100644 --- a/auth0-js/auth0-js-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,23 +1,151 @@ -/// +import 'auth0-js'; -var auth0 = new Auth0({ +let webAuth = new auth0.WebAuth({ domain: 'mine.auth0.com', - clientID: 'dsa7d77dsa7d7', - callbackURL: 'http://my-app.com/callback', - callbackOnLocationHash: true + clientID: 'dsa7d77dsa7d7' }); -auth0.login({ - connection: 'google-oauth2', - popup: true, - popupOptions: { - width: 450, - height: 800 +webAuth.authorize({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + responseType: 'token', + redirectUri: 'https://example.com/auth/callback' +}); + +webAuth.parseHash(window.location.hash, (err, authResult) => { + if (err) { + return console.log(err); } -}, (err, profile, idToken, accessToken, state) => { - if (err) { - alert("something went wrong: " + err.message); - return; - } - alert('hello ' + profile.name); + + // The contents of authResult depend on which authentication parameters were used. + // It can include the following: + // authResult.accessToken - access token for the API specified by `audience` + // authResult.expiresIn - string with the access token's expiration time in seconds + // authResult.idToken - ID token JWT containing user profile information + + webAuth.client.userInfo(authResult.accessToken, (err, user) => { + // Now you have the user's information }); +}); + +webAuth.renewAuth({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback', + + // this will use postMessage to comunicate between the silent callback + // and the SPA. When false the SDK will attempt to parse the url hash + // should ignore the url hash and no extra behaviour is needed. + usePostMessage: true +}, function (err, authResult) { + // Renewed tokens or error +}); + +webAuth.changePassword({connection: 'the_connection', + email: 'me@example.com', + password: '123456' +}, (err) => {}); + +webAuth.passwordlessStart({ + connection: 'the_connection', + email: 'me@example.com', + send: 'code' +}, (err, data) => {}); + +webAuth.signupAndAuthorize({ + connection: 'the_connection', + email: 'me@example.com', + password: '123456', + scope: 'openid' +}, function (err, data) { + +}); + + + +webAuth.client.login({ + ealm: 'Username-Password-Authentication', //connection name or HRD domain + username: 'info@auth0.com', + password: 'areallystrongpassword', + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', +}, function(err, authResult) { + // Auth tokens in the result or an error +}); + +let authentication = new auth0.Authentication({ + domain: 'me.auth0.com', + clientID: '...', + redirectUri: 'http://page.com/callback', + responseType: 'code', + _sendTelemetry: false +}); + +authentication.buildAuthorizeUrl({state:'1234'}); +authentication.buildAuthorizeUrl({ + responseType: 'token', + redirectUri: 'http://anotherpage.com/callback2', + prompt: 'none', + state: '1234', + connection_scope: 'scope1,scope2' +}); + +authentication.buildLogoutUrl('asdfasdfds'); +authentication.buildLogoutUrl(); +authentication.userInfo('abcd1234', (err, data) => { + //user info retrieved +}); + +authentication.delegation({ + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + refresh_token: 'your_refresh_token', + api_type: 'app' +}, (err, data) => { + +}); + +authentication.loginWithDefaultDirectory({ + username: 'someUsername', + password: '123456' +}, (err, data) => { + +}); + +authentication.oauthToken({ + username: 'someUsername', + password: '123456', + grantType: 'password' +}, (err, data) => { + +}); + +authentication.getUserCountry((err, data) => { + +}); + +authentication.getSSOData(); +authentication.getSSOData(true, (err, data) => {}); + +authentication.dbConnection.signup({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); +authentication.dbConnection.changePassword({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); + +authentication.passwordless.start({ connection: 'bla', send: 'blabla' }, () => {}); +authentication.passwordless.verify({ connection: 'bla', send: 'link', verificationCode: 'asdfasd', email: 'me@example.com' }, () => {}); + +authentication.loginWithResourceOwner({ + username: 'the username', + password: 'the password', + connection: 'the_connection', + scope: 'openid' +}, (err, data) => {}); + +let management = new auth0.Management({ + domain: 'me.auth0.com', + token: 'token' +}); + +management.getUser('asd', (err, user) => {}); + +management.patchUserMetadata('asd', {role: 'admin'}, (err, user) => {}); + +management.linkUser('asd', 'eqwe', (err, user) => {}); diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index bd97fed1cc..11cf16a3ed 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -1,136 +1,456 @@ -// Type definitions for Auth0.js +// Type definitions for Auth0.js 8.1 // Project: https://github.com/auth0/auth0.js -// Definitions by: Robert McLaws +// Definitions by: Adrian Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** Extensions to the browser Window object. */ -interface Window { - /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ - token: string; -} - -/** This is the interface for the main Auth0 client. */ -interface Auth0Static { - - new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; - decodeJwt(jwt: string): any; - login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; - loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - logout(query: string): void; - getConnections(callback?: Function): void; - refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; - parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; - validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; -} - -/** Represents constructor options for the Auth0 client. */ -interface Auth0ClientOptions { - clientID: string; - callbackURL: string; - callbackOnLocationHash?: boolean; - responseType?: string; - domain: string; - forceJSONP?: boolean; -} - -/** Represents a normalized UserProfile. */ -interface Auth0UserProfile { - email: string; - email_verified: boolean; - family_name: string; - gender: string; - given_name: string; - locale: string; - name: string; - nickname: string; - picture: string; - user_id: string; - /** Represents one or more Identities that may be associated with the User. */ - identities: Auth0Identity[]; - user_metadata?: any; - app_metadata?: any; -} - -/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ -interface MicrosoftUserProfile extends Auth0UserProfile { - emails: string[]; -} - -/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ -interface Office365UserProfile extends Auth0UserProfile { - tenantid: string; - upn: string; -} - -/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ -interface AdfsUserProfile extends Auth0UserProfile { - issuer: string; -} - -/** Represents multiple identities assigned to a user. */ -interface Auth0Identity { - access_token: string; - connection: string; - isSocial: boolean; - provider: string; - user_id: string; -} - -interface Auth0DecodedHash { - access_token: string; - idToken: string; - profile: Auth0UserProfile; - state: any; - error: string; -} - -interface Auth0PopupOptions { - width: number; - height: number; -} - -interface Auth0LoginOptions { - auto_login?: boolean; - responseType?: string; - connection?: string; - email?: string; - username?: string; - password?: string; - popup?: boolean; - popupOptions?: Auth0PopupOptions; -} - -interface Auth0SignupOptions extends Auth0LoginOptions { - auto_login: boolean; -} - -interface Auth0Error { - code: any; - details: any; - name: string; - message: string; - status: any; -} - -/** Represents the response from an API Token Delegation request. */ -interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - expires_in: string; - /** The JWT for delegated access. */ - id_token: string; - /** The type of token being returned. Possible values: "Bearer" */ - token_type: string; -} - -declare const Auth0: Auth0Static; - -declare module "auth0-js" { - export = Auth0 +declare namespace auth0 { + + export class Authentication { + constructor(options: AuthOptions); + + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; + + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; + + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; + + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + * @deprecated `delegation` will be soon deprecated. + */ + delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; + } + + export class PasswordlessAuthentication { + constructor(request: any, option: any); + + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; + + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: any): void; + } + + export class DBConnection { + constructor(request: any, option: any); + + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: any): void; + + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: any): void; + } + + export class Management { + constructor(options: ManagementOptions); + + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; + } + + export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; + + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; + + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: any): void; + + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: any): void; + + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; + + passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; + + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + } + + export class Redirect { + constructor(client: any, options: any); + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + export class Popup { + constructor(client: any, options: any); + + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; + + /** + * Internal use. + * + * @method getPopupHandler + */ + getPopupHandler(options: any, preload: boolean): any; + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: any): void; + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; + } + + interface Auth0Error { + error: any; + errorDescription: string; + } + + interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; + } + + /** Represents the response from an API Token Delegation request. */ + interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + ExpiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; + } + + interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; + } + + interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string; + authParams?: any; + } + + interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; + } + } diff --git a/auth0-js/tsconfig.json b/auth0-js/tsconfig.json index a2e16e19e0..62bab1e208 100644 --- a/auth0-js/tsconfig.json +++ b/auth0-js/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "auth0-js-tests.ts" ] -} \ No newline at end of file +} diff --git a/auth0-js/v7/auth0-js-tests.ts b/auth0-js/v7/auth0-js-tests.ts new file mode 100644 index 0000000000..a68b17cb69 --- /dev/null +++ b/auth0-js/v7/auth0-js-tests.ts @@ -0,0 +1,23 @@ +import 'auth0-js'; + +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0-js/v7/index.d.ts b/auth0-js/v7/index.d.ts new file mode 100644 index 0000000000..a93e979f2b --- /dev/null +++ b/auth0-js/v7/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for Auth0.js 7.0 +// Project: https://github.com/auth0/auth0.js +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: (error?: Auth0Error, valid?: any) => void): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: (error?: Auth0Error, valid?: any) => void): void; + refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: (error?: Auth0Error, valid?: any) => void): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: (error?: Auth0Error, valid?: any) => void): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: (error?: Auth0Error, valid?: any) => void): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLocationHash?: boolean; + responseType?: string; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + email_verified: boolean; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + idToken: string; + profile: Auth0UserProfile; + state: any; + error: string; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + responseType?: string; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare const Auth0: Auth0Static; + +declare module "auth0-js" { + export = Auth0; +} diff --git a/auth0-js/v7/tsconfig.json b/auth0-js/v7/tsconfig.json new file mode 100644 index 0000000000..bdabf7ef7f --- /dev/null +++ b/auth0-js/v7/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "auth0-js": ["auth0-js/v7"], + "auth0-js/*": ["auth0-js/v7/*"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "auth0-js-tests.ts" + ] +} diff --git a/auth0-lock/auth0-lock-tests.ts b/auth0-lock/auth0-lock-tests.ts index deb046f3e7..8045386586 100644 --- a/auth0-lock/auth0-lock-tests.ts +++ b/auth0-lock/auth0-lock-tests.ts @@ -1,5 +1,5 @@ -/// -/// +import 'auth0-js/v7'; +import Auth0Lock from 'auth0-lock'; const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; const DOMAIN = "YOUR_DOMAIN_AT.auth0.com"; diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts index fc9a047115..09c3f4fedd 100644 --- a/auth0-lock/index.d.ts +++ b/auth0-lock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; diff --git a/auth0-lock/package.json b/auth0-lock/package.json new file mode 100644 index 0000000000..2d730992af --- /dev/null +++ b/auth0-lock/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/auth0-js": "latest" + } +} diff --git a/auth0-lock/tsconfig.json b/auth0-lock/tsconfig.json index 367445041e..09c9f8233c 100644 --- a/auth0-lock/tsconfig.json +++ b/auth0-lock/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "auth0-lock-tests.ts" ] -} \ No newline at end of file +} diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index ec5502ca7e..f2ddda2146 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,5 +1,4 @@ -/// - +import 'auth0-js/v7'; var widget: Auth0WidgetStatic = new Auth0Widget({ domain: 'mine.auth0.com', diff --git a/auth0.widget/index.d.ts b/auth0.widget/index.d.ts index 1c30d83b6f..36d99c9009 100644 --- a/auth0.widget/index.d.ts +++ b/auth0.widget/index.d.ts @@ -3,8 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - +/// interface Auth0WidgetStatic { new(params: Auth0Constructor): Auth0WidgetStatic; diff --git a/auth0.widget/package.json b/auth0.widget/package.json new file mode 100644 index 0000000000..2d730992af --- /dev/null +++ b/auth0.widget/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/auth0-js": "latest" + } +} diff --git a/auth0.widget/tsconfig.json b/auth0.widget/tsconfig.json index 7bba7e763f..8ceb7b3d73 100644 --- a/auth0.widget/tsconfig.json +++ b/auth0.widget/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "auth0.widget-tests.ts" ] -} \ No newline at end of file +} diff --git a/auth0/index.d.ts b/auth0/index.d.ts index b24b808529..a8a6242bb4 100644 --- a/auth0/index.d.ts +++ b/auth0/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for auth0 v2.3.1 +// Type definitions for auth0 2.4 // Project: https://github.com/auth0/node-auth0 -// Definitions by: Seth Westphal +// Definitions by: Wilson Hobbs , Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Promise from 'bluebird'; @@ -10,8 +10,8 @@ export interface ManagementClientOptions { domain?: string; } -export type UserMetadata = {}; -export type AppMetadata = {}; +export interface UserMetadata { } +export interface AppMetadata { } export interface UserData { connection: string; @@ -71,34 +71,353 @@ export interface UpdateUserParameters { id: string; } -export class ManagementClient { - constructor(options: ManagementClientOptions); - - getUsers(params?: GetUsersData): Promise; - getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; - createUser(data: UserData): Promise; - createUser(data: UserData, cb: (err: Error, data: User) => void): void; - updateUser(params: UpdateUserParameters, data: User): Promise; - updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void; - updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise; - updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void - updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise; - updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void -} - export interface AuthenticationClientOptions { clientId?: string; domain: string; } -export interface RequestChangePasswordEmailData { +interface Environment { + name: string; + version: string; +} + +export interface ClientInfo { + name: string; + version: string; + dependencies: any[]; + environment: Environment[]; +} + +export interface RequestEmailOptions { + email: string; + authParams: {}; +} + +export interface RequestSMSOptions { + phone_number: string; +} + +export interface VerifyOptions { + username: string; + password: string; +} + +export interface DelegationTokenOptions { + id_token: string; + api_type: string; + scope: string; + target: string; + grant_type: string; +} + +export interface ResetPasswordOptions { connection: string; email: string; + password: string; } +export interface ResetPasswordEmailOptions { + email: string; + connection: string; +} + +export interface ObjectWithId { + id: string; +} + +export interface Data { + name?: string; + [propName: string]: any; +} + +export interface ClientParams { + client_id: string; +} + +export interface DeleteMultifactorParams { + id: string; + provider: string; +} + +export interface LinkAccountsParams { + id: string; + provider: string; + user_id: string; +} + +export interface LinkAccountsData { + user_id: string; + connection_id: string; +} + +export interface Token { + aud: string; + jti: string; +} + +export interface StatsParams { + from: string; + to: string; +} + +export interface ImportUsersOptions { + connection_id: string; + users: string; +} + +export interface UserIdParams { + user_id: string; +} + +export interface PasswordChangeTicketParams { + result_url: string; + user_id: string; + email: string; + new_password: string; +} + +export interface EmailVerificationTicketOptions { + user_id: string; + result_url: string; +} + + + export class AuthenticationClient { constructor(options: AuthenticationClientOptions); + getClientInfo(): ClientInfo; + + requestMagicLink(data: RequestEmailOptions): Promise; + requestMagicLink(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void; + + requestEmailCode(data: RequestEmailOptions): Promise; + requestEmailCode(data: RequestEmailOptions, cb: (err: Error, message: string) => void): void; + + requestSMSCode(data: RequestSMSOptions): Promise; + requestSMSCode(data: RequestSMSOptions, cb: (err: Error, message: string) => void): void; + + verifyEmailCode(data: VerifyOptions): Promise; + verifyEmailCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void; + + verifySMSCode(data: VerifyOptions): Promise; + verifySMSCode(data: VerifyOptions, cb: (err: Error, message: string) => void): void; + + getDelegationToken(data: DelegationTokenOptions): Promise; + getDelegationToken(data: DelegationTokenOptions, cb: (err: Error, message: string) => void): void; + + changePassword(data: ResetPasswordOptions): Promise; + changePassword(data: ResetPasswordOptions, cb: (err: Error, message: string) => void): void; + + requestChangePasswordEmail(data: ResetPasswordEmailOptions): Promise; + requestChangePasswordEmail(data: ResetPasswordEmailOptions, cb: (err: Error, message: string) => void): void; + + getProfile(accessToken: string): Promise; + getProfile(accessToken: string, cb: (err: Error, message: string) => void): void; + + getCredentialsGrant(scope: string): Promise; + getCredentialsGrant(scope: string, cb: (err: Error, message: string) => void): void; + +} + + +export class ManagementClient { + constructor(options: ManagementClientOptions); + + getClientInfo(): ClientInfo; + + // Connections + getConnections(): Promise; + getConnections(cb: (err: Error, data: any) => void): void; + + createConnection(data: ObjectWithId): Promise; + createConnection(data: ObjectWithId, cb: (err: Error, data: any) => void): void; + + getConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + getConnection(params: ObjectWithId): Promise; + + deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + deleteConnection(params: ObjectWithId): Promise; + + deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + deleteConnection(params: ObjectWithId): Promise; + + updateConnection(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void; + updateConnection(params: ObjectWithId, data: Data): Promise; + + + // Clients + getClients(): Promise; + getClients(cb: (err: Error, data: any) => void): void; + + getClient(params: ClientParams): Promise; + getClient(params: ClientParams, cb: (err: Error, data: any) => void): void; + + createClient(data: Data): Promise; + createClient(data: Data, cb: (err: Error, data: any) => void): void; + + updateClient(params: ClientParams, data: Data): Promise; + updateClient(params: ClientParams, data: Data, cb: (err: Error, data: any) => void): void; + + deleteClient(params: ClientParams): Promise; + deleteClient(params: ClientParams, cb: (err: Error, data: any) => void): void; + + // Client Grants + getClientGrants(): Promise; + getClientGrants(cb: (err: Error, data: any) => void): void; + + createClientGrant(data: Data): Promise; + createClientGrant(data: Data, cb: (err: Error, data: any) => void): void; + + updateClientGrant(params: ObjectWithId, data: Data): Promise; + updateClientGrant(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void; + + deleteClientGrant(params: ObjectWithId): Promise; + deleteClientGrant(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + + + // Device Keys + getDeviceCredentials(): Promise; + getDeviceCredentials(cb: (err: Error, data: any) => void): void; + + createDevicePublicKey(data: Data): Promise; + createDevicePublicKey(data: Data, cb: (err: Error, data: any) => void): void; + + deleteDeviceCredential(params: ClientParams): Promise; + deleteDeviceCredential(params: ClientParams, cb: (err: Error, data: any) => void): void; + + + // Rules + getRules(): Promise; + getRules(cb: (err: Error, data: any) => void): void; + + getRule(params: ClientParams): Promise; + getRule(params: ClientParams, cb: (err: Error, data: any) => void): void; + + createRules(data: Data): Promise; + createRules(data: Data, cb: (err: Error, data: any) => void): void; + + updateRule(params: ObjectWithId, data: Data): Promise; + updateRule(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void; + + deleteRule(params: ObjectWithId): Promise; + deleteRule(params: ObjectWithId, cb: (err: Error, data: any) => void): void; + + + // Users + getUsers(params?: GetUsersData): Promise; + getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; + + getUser(params?: ObjectWithId): Promise; + getUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void; + + createUser(data: UserData): Promise; + createUser(data: UserData, cb: (err: Error, data: User) => void): void; + + updateUser(params: UpdateUserParameters, data: User): Promise; + updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void; + + updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise; + updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void; + + deleteAllUsers(): Promise; + deleteAllUsers(cb: (err: Error, data: any) => void): void; + + deleteUser(params?: ObjectWithId): Promise; + deleteUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void; + + updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise; + updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void; + + deleteUserMultifactor(params: DeleteMultifactorParams): Promise; + deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error, data: any) => void): void; + + unlinkUsers(params: LinkAccountsParams): Promise; + unlinkUsers(params: LinkAccountsParams, cb: (err: Error, data: any) => void): void; + + linkUsers(params: ObjectWithId, data: LinkAccountsData): Promise; + linkUsers(params: ObjectWithId, data: LinkAccountsData, cb: (err: Error, data: any) => void): void; + + + // Tokens + getBlacklistedTokens(): Promise; + getBlacklistedTokens(cb?: (err: Error, data: any) => void): void; + + blacklistToken(token: Token): Promise; + blacklistToken(token: Token, cb: (err: Error, data: any) => void): void; + + + // Providers + getEmailProvider(): Promise; + getEmailProvider(cb?: (err: Error, data: any) => void): void; + + configureEmailProvider(data: Data): Promise; + configureEmailProvider(data: Data, cb: (err: Error, data: any) => void): void; + + deleteEmailProvider(): Promise; + deleteEmailProvider(cb?: (err: Error, data: any) => void): void; + + updateEmailProvider(data: Data): Promise; + updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void; + + + // Statistics + getActiveUsersCount(): Promise; + getActiveUsersCount(cb?: (err: Error, data: any) => void): void; + + getDailyStats(data: StatsParams): Promise; + getDailyStats(data: StatsParams, cb: (err: Error, data: any) => void): void; + + + // Tenant + getTenantSettings(): Promise; + getTenantSettings(cb?: (err: Error, data: any) => void): void; + + updateTenantSettings(data: Data): Promise; + updateTenantSettings(data: Data, cb?: (err: Error, data: any) => void): void; + + + // Jobs + getJob(params: ObjectWithId): Promise; + getJob(params: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + importUsers(data: ImportUsersOptions): Promise; + importUsers(data: ImportUsersOptions, cb?: (err: Error, data: any) => void): void; + + sendEmailVerification(data: UserIdParams): Promise; + sendEmailVerification(data: UserIdParams, cb?: (err: Error, data: any) => void): void; + + // Tickets + createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise; + createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: any) => void): void; + + createEmailVerificationTicket(data: EmailVerificationTicketOptions): Promise; + createEmailVerificationTicket(data: EmailVerificationTicketOptions, cb?: (err: Error, data: any) => void): void; + + // Logs + getLog(params: ObjectWithId): Promise; + getLog(params: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + getLogs(): Promise; + getLogs(cb?: (err: Error, data: any) => void): void; + + + // Resource Server + createResourceServer(data: Data): Promise; + createResourceServer(data: Data, cb?: (err: Error, data: any) => void): void; + + getResourceServers(): Promise; + getResourceServers(cb?: (err: Error, data: any) => void): void; + + getResourceServer(data: ObjectWithId): Promise; + getResourceServer(data: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + deleteResourceServer(params: ObjectWithId): Promise; + deleteResourceServer(params: ObjectWithId, cb?: (err: Error, data: any) => void): void; + + updateResourceServer(params: ObjectWithId, data: Data): Promise; + updateResourceServer(params: ObjectWithId, data: Data, cb?: (err: Error, data: any) => void): void; + + + - requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise; - requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void; } diff --git a/autosize/autosize-tests.ts b/autosize/autosize-tests.ts index 74be703a94..a7eea57a62 100644 --- a/autosize/autosize-tests.ts +++ b/autosize/autosize-tests.ts @@ -8,3 +8,21 @@ autosize(document.querySelector('textarea')); // from a single element autosize(document.getElementById('my-textarea')); + +// update a NodeList +autosize.update(document.querySelectorAll('textarea')); + +// update a single Node +autosize.update(document.querySelector('textarea')); + +// update a single element +autosize.update(document.getElementById('my-textarea')); + +// destroy a NodeList +autosize.destroy(document.querySelectorAll('textarea')); + +// destroy a single Node +autosize.destroy(document.querySelector('textarea')); + +// destroy a single element +autosize.destroy(document.getElementById('my-textarea')); diff --git a/autosize/index.d.ts b/autosize/index.d.ts index 5ea76d0472..0886904e3f 100644 --- a/autosize/index.d.ts +++ b/autosize/index.d.ts @@ -1,12 +1,16 @@ // Type definitions for jquery.autosize 3.0.7 // Project: http://www.jacklmoore.com/autosize/ -// Definitions by: Aaron T. King +// Definitions by: Aaron T. King , keika299 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace autosize { interface AutosizeStatic { (el: Element): void; (el: NodeList): void; + update(el: Element): void; + update(el: NodeList): void; + destroy(el: Element): void; + destroy(el: NodeList): void; } } diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index 0d8d9bd47f..fb09beda8a 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -6,11 +6,48 @@ var anyObj: any = { abc: 123 }; var num: number = 5; var error: Error = new Error(); var b: boolean = true; +var apiGwEvt: AWSLambda.APIGatewayEvent; var clientCtx: AWSLambda.ClientContext; var clientContextEnv: AWSLambda.ClientContextEnv; var clientContextClient: AWSLambda.ClientContextClient; var context: AWSLambda.Context; var identity: AWSLambda.CognitoIdentity; +var proxyResult: AWSLambda.ProxyResult; + +/* API Gateway Event */ +str = apiGwEvt.body; +str = apiGwEvt.headers["example"]; +str = apiGwEvt.httpMethod; +b = apiGwEvt.isBase64Encoded; +str = apiGwEvt.path; +str = apiGwEvt.pathParameters["example"]; +str = apiGwEvt.queryStringParameters["example"]; +str = apiGwEvt.stageVariables["example"]; +str = apiGwEvt.requestContext.accountId; +str = apiGwEvt.requestContext.apiId; +str = apiGwEvt.requestContext.httpMethod; +str = apiGwEvt.requestContext.identity.accessKey; +str = apiGwEvt.requestContext.identity.accountId; +str = apiGwEvt.requestContext.identity.apiKey; +str = apiGwEvt.requestContext.identity.caller; +str = apiGwEvt.requestContext.identity.cognitoAuthenticationProvider; +str = apiGwEvt.requestContext.identity.cognitoAuthenticationType; +str = apiGwEvt.requestContext.identity.cognitoIdentityId; +str = apiGwEvt.requestContext.identity.cognitoIdentityPoolId; +str = apiGwEvt.requestContext.identity.sourceIp; +str = apiGwEvt.requestContext.identity.user; +str = apiGwEvt.requestContext.identity.userAgent; +str = apiGwEvt.requestContext.identity.userArn; +str = apiGwEvt.requestContext.stage; +str = apiGwEvt.requestContext.requestId; +str = apiGwEvt.requestContext.resourceId; +str = apiGwEvt.requestContext.resourcePath; +str = apiGwEvt.resource; + +/* Lambda Proxy Result */ +num = proxyResult.statusCode; +str = proxyResult.headers["example"]; +str = proxyResult.body /* Context */ b = context.callbackWaitsForEmptyEventLoop; @@ -54,6 +91,15 @@ function callback(cb: AWSLambda.Callback) { cb(error); cb(null, anyObj); } + +/* Proxy Callback */ +function proxyCallback(cb: AWSLambda.ProxyCallback) { + cb(); + cb(null); + cb(error); + cb(null, proxyResult); +} + /* Compatibility functions */ context.done(); context.done(error); @@ -66,3 +112,4 @@ context.fail(str); /* Handler */ let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => {}; diff --git a/aws-lambda/index.d.ts b/aws-lambda/index.d.ts index 1aa41b9e62..e8b70db7bd 100644 --- a/aws-lambda/index.d.ts +++ b/aws-lambda/index.d.ts @@ -1,8 +1,44 @@ // Type definitions for AWS Lambda // Project: http://docs.aws.amazon.com/lambda -// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath , Toby Hede +// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath , Toby Hede , Rich Buggy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// API Gateway "event" +interface APIGatewayEvent { + body: string | null; + headers: { [name: string]: string }; + httpMethod: string; + isBase64Encoded: boolean; + path: string; + pathParameters: { [name: string]: string } | null; + queryStringParameters: { [name: string]: string } | null; + stageVariables: { [name: string]: string } | null; + requestContext: { + accountId: string; + apiId: string; + httpMethod: string; + identity: { + accessKey: string | null; + accountId: string | null; + apiKey: string | null; + caller: string | null; + cognitoAuthenticationProvider: string | null; + cognitoAuthenticationType: string | null; + cognitoIdentityId: string | null; + cognitoIdentityPoolId: string | null; + sourceIp: string; + user: string | null; + userAgent: string | null; + userArn: string | null; + }, + stage: string; + requestId: string; + resourceId: string; + resourcePath: string; + }; + resource: string; +} + // Context // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html interface Context { @@ -58,6 +94,14 @@ interface ClientContextEnv { locale: string; } +interface ProxyResult { + statusCode: number; + headers?: { + [header: string]: string; + }, + body: string; +} + /** * AWS Lambda handler function. * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html @@ -67,6 +111,7 @@ interface ClientContextEnv { * @param callback – optional callback to return information to the caller, otherwise return value is null. */ export type Handler = (event: any, context: Context, callback?: Callback) => void; +export type ProxyHandler = (event: APIGatewayEvent, context: Context, callback?: ProxyCallback) => void; /** * Optional callback parameter. @@ -76,5 +121,6 @@ export type Handler = (event: any, context: Context, callback?: Callback) => vo * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. */ export type Callback = (error?: Error, result?: any) => void; +export type ProxyCallback = (error?: Error, result?: ProxyResult) => void; export as namespace AWSLambda; diff --git a/axios/axios-tests.ts b/axios/axios-tests.ts deleted file mode 100644 index eb98e2710c..0000000000 --- a/axios/axios-tests.ts +++ /dev/null @@ -1,107 +0,0 @@ - - -enum HttpMethod { GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH } -enum ResponseType { arraybuffer, blob, document, json, text } - -interface Repository { - id: number; - name: string; -} - -interface Issue { - id: number; - title: string; -} - -axios.interceptors.request.use(config => { - console.log("Method:" + config.method + " Url:" +config.url); - return config; -}); - - -const requestId: number = axios.interceptors.request.use( - (config) => { - console.log("Method:" + config.method + " Url:" +config.url); - return config; - }, - (error: any) => error); - - -axios.interceptors.request.eject(requestId); -axios.interceptors.request.eject(7); - - -axios.interceptors.response.use(config => { - console.log("Status:" + config.status); - return config; -}); - -const responseId: number = axios.interceptors.response.use( - config => { - console.log("Status:" + config.status); - return config; - }, - (error: any) => error); - -axios.interceptors.response.eject(responseId); - -axios.get("https://api.github.com/repos/mzabriskie/axios") - .then(r => console.log(r.config.method)); - -var getRepoDetails = axios({ - url: "https://api.github.com/repos/mzabriskie/axios", - method: HttpMethod[HttpMethod.GET], - headers: {}, -}).then(r => { - console.log("ID:" + r.data.id + " Name: " + r.data.name); - return r; -}); - -axios.post("http://example.com/", {}, { - transformRequest: (data: any) => data -}); - -axios.post("http://example.com/", { - headers: {'X-Custom-Header': 'foobar'} -}, { - transformRequest: [ - (data: any) => data - ] -}); - -var config: Axios.AxiosXHRConfigBase = {headers: {}}; -config.headers['X-Custom-Header'] = 'baz'; -axios.post("http://example.com/", config); - -var getRepoIssue = axios.get("https://api.github.com/repos/mzabriskie/axios/issues/1"); - -var axiosInstance = axios.create({ - baseURL: "https://api.github.com/repos/mzabriskie/axios/", - timeout: 1000 -}); - -axiosInstance.request({url: "issues/1"}).then(res => { - if (res.headers['content-type'].startsWith('application/json')) { - throw new Error('Unexpected content-type'); - } -}); - -axios.all([getRepoDetails, getRepoDetails]).then(([repo1, repo2]) => { - var sumIds = repo1.data.id + repo2.data.id; - console.log("Sum ID:" + sumIds); - return sumIds; -}); - -var repoSum = (repo1: Axios.AxiosXHR, repo2: Axios.AxiosXHR) => { - var sumIds = repo1.data.id + repo2.data.id; - console.log("Sum ID:" + sumIds); - return sumIds; -}; - -axios.all([getRepoDetails, getRepoDetails]).then(axios.spread(repoSum)); - -axios.defaults.baseURL = 'https://api.example.com'; -axios.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; -axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; - -axiosInstance.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; \ No newline at end of file diff --git a/axios/index.d.ts b/axios/index.d.ts deleted file mode 100644 index 681fefc806..0000000000 --- a/axios/index.d.ts +++ /dev/null @@ -1,316 +0,0 @@ -// Type definitions for axios 0.9.1 -// Project: https://github.com/mzabriskie/axios -// Definitions by: Marcel Buesing -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Axios { - - interface IThenable { - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IThenable; - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IThenable; - } - - interface IPromise extends IThenable { - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => U | IThenable): IPromise; - then(onFulfilled?: (value: R) => U | IThenable, onRejected?: (error: any) => void): IPromise; - catch(onRejected?: (error: any) => U | IThenable): IPromise; - } - - /** - * HTTP Basic auth details - */ - interface AxiosHttpBasicAuth { - username: string; - password: string; - } - - /** - * Common axios XHR config interface - * - request body data type - */ - interface AxiosXHRConfigBase { - /** - * will be prepended to `url` unless `url` is absolute. - * It can be convenient to set `baseURL` for an instance - * of axios to pass relative URLs to methods of that instance. - */ - baseURL?: string; - - /** - * custom headers to be sent - */ - headers?: {[key: string]: any}; - - /** - * URL parameters to be sent with the request - */ - params?: Object; - - /** - * optional function in charge of serializing `params` - * (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) - */ - paramsSerializer?: (params: Object) => string; - - /** - * specifies the number of milliseconds before the request times out. - * If the request takes longer than `timeout`, the request will be aborted. - */ - timeout?: number; - - /** - * indicates whether or not cross-site Access-Control requests - * should be made using credentials - */ - withCredentials?: boolean; - - /** - * indicates that HTTP Basic auth should be used, and supplies - * credentials. This will set an `Authorization` header, - * overwriting any existing `Authorization` custom headers you have - * set using `headers`. - */ - auth?: AxiosHttpBasicAuth; - - /** - * indicates the type of data that the server will respond with - * options are 'arraybuffer', 'blob', 'document', 'json', 'text' - */ - responseType?: string; - - /** - * name of the cookie to use as a value for xsrf token - */ - xsrfCookieName?: string; - - /** - * name of the http header that carries the xsrf token value - */ - xsrfHeaderName?: string; - - /** - * Change the request data before it is sent to the server. - * This is only applicable for request methods 'PUT', 'POST', and 'PATCH' - * The last function in the array must return a string or an ArrayBuffer - */ - transformRequest?: ((data: T) => U) | [(data: T) => U]; - - /** - * change the response data to be made before it is passed to then/catch - */ - transformResponse?: (data: T) => U; - - /** - * defines whether to resolve or reject the promise for a given HTTP response status code. - * If returns `true` (or is set to `null` or `undefined`), the promise will be resolved; - * otherwise, the promise will be rejected - */ - validateStatus?: (status: number) => boolean | undefined; - } - - /** - * - request body data type - */ - interface AxiosXHRConfig extends AxiosXHRConfigBase { - /** - * server URL that will be used for the request, options are: - * GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH - */ - url: string; - - /** - * request method to be used when making the request - */ - method?: string; - - /** - * data to be sent as the request body - * Only applicable for request methods 'PUT', 'POST', and 'PATCH' - * When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash - */ - data?: T; - } - - interface AxiosXHRConfigDefaults extends AxiosXHRConfigBase { - /** - * custom headers to be sent - */ - headers: { - common: {[index: string]: string}; - patch: {[index: string]: string}; - post: {[index: string]: string}; - put: {[index: string]: string}; - }; - } - - /** - * - expected response type, - * - request body data type - */ - interface AxiosXHR { - /** - * Response that was provided by the server - */ - data: T; - - /** - * HTTP status code from the server response - */ - status: number; - - /** - * HTTP status message from the server response - */ - statusText: string; - - /** - * headers that the server responded with - */ - headers: {[index: string]: any}; - - /** - * config that was provided to `axios` for the request - */ - config: AxiosXHRConfig; - } - - interface Interceptor { - /** - * intercept request before it is sent - */ - request: RequestInterceptor; - - /** - * intercept response of request when it is received. - */ - response: ResponseInterceptor - } - - type InterceptorId = number; - - interface RequestInterceptor { - /** - * - request body data type - */ - - use(fulfilledFn: (config: AxiosXHRConfig) => AxiosXHRConfig): InterceptorId; - - use(fulfilledFn: (config: AxiosXHRConfig) => AxiosXHRConfig, - rejectedFn: (error: any) => any) - : InterceptorId; - - eject(interceptorId: InterceptorId): void; - } - - interface ResponseInterceptor { - /** - * - expected response type - */ - - use(fulfilledFn: (config: Axios.AxiosXHR) => Axios.AxiosXHR): InterceptorId; - - use(fulfilledFn: (config: Axios.AxiosXHR) => Axios.AxiosXHR, - rejectedFn: (error: any) => any) - : InterceptorId; - - eject(interceptorId: InterceptorId): void; - } - - /** - * - expected response type, - * - request body data type - */ - interface AxiosInstance { - - /** - * Send request as configured - */ - (config: AxiosXHRConfig): IPromise>; - - /** - * Send request as configured - */ - new (config: AxiosXHRConfig): IPromise>; - - /** - * Send request as configured - */ - request(config: AxiosXHRConfig): IPromise>; - - /** - * intercept requests or responses before they are handled by then or catch - */ - interceptors: Interceptor; - - /** - * Config defaults - */ - defaults: AxiosXHRConfigDefaults; - - /** - * equivalent to `Promise.all` - */ - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>, T4 | IPromise>, T5 | IPromise>, T6 | IPromise>, T7 | IPromise>, T8 | IPromise>, T9 | IPromise>, T10 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>, T4 | IPromise>, T5 | IPromise>, T6 | IPromise>, T7 | IPromise>, T8 | IPromise>, T9 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>, T4 | IPromise>, T5 | IPromise>, T6 | IPromise>, T7 | IPromise>, T8 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>, T4 | IPromise>, T5 | IPromise>, T6 | IPromise>, T7 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>, T4 | IPromise>, T5 | IPromise>, T6 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>, T4 | IPromise>, T5 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>, T4 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>, T3 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR, AxiosXHR]>; - all(values: [T1 | IPromise>, T2 | IPromise>]): IPromise<[AxiosXHR, AxiosXHR]>; - - /** - * spread array parameter to `fn`. - * note: alternative to `spread`, destructuring assignment. - */ - spread(fn: (t1: T1, t2: T2) => U): (arr: ([T1, T2])) => U; - - /** - * convenience alias, method = GET - */ - get(url: string, config?: AxiosXHRConfigBase): IPromise>; - - - /** - * convenience alias, method = DELETE - */ - delete(url: string, config?: AxiosXHRConfigBase): IPromise>; - - /** - * convenience alias, method = HEAD - */ - head(url: string, config?: AxiosXHRConfigBase): IPromise>; - - /** - * convenience alias, method = POST - */ - post(url: string, data?: any, config?: AxiosXHRConfigBase): IPromise>; - - /** - * convenience alias, method = PUT - */ - put(url: string, data?: any, config?: AxiosXHRConfigBase): IPromise>; - - /** - * convenience alias, method = PATCH - */ - patch(url: string, data?: any, config?: AxiosXHRConfigBase): IPromise>; - } - - /** - * - expected response type, - */ - interface AxiosStatic extends AxiosInstance { - /** - * create a new instance of axios with a custom config - */ - create(config: AxiosXHRConfigBase): AxiosInstance; - } -} - -declare var axios: Axios.AxiosStatic; - -declare module "axios" { - export = axios; -} diff --git a/babel-code-frame/tslint.json b/babel-code-frame/tslint.json index ec365f164b..377cc837d4 100644 --- a/babel-code-frame/tslint.json +++ b/babel-code-frame/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/babel-traverse/babel-traverse-tests.ts b/babel-traverse/babel-traverse-tests.ts index c02efe44ad..3779852c5f 100644 --- a/babel-traverse/babel-traverse-tests.ts +++ b/babel-traverse/babel-traverse-tests.ts @@ -109,3 +109,16 @@ const v1: Visitor = { path.scope.rename("n"); } }; + +// Binding.kind +const BindingKindTest: Visitor = { + Identifier(path) { + const kind = path.scope.getBinding("str").kind; + kind === 'module'; + kind === 'const'; + kind === 'let'; + kind === 'var'; + // The following should fail when uncommented + // kind === 'anythingElse'; + }, +}; diff --git a/babel-traverse/index.d.ts b/babel-traverse/index.d.ts index 67dd119e91..e307cd664d 100644 --- a/babel-traverse/index.d.ts +++ b/babel-traverse/index.d.ts @@ -126,7 +126,7 @@ export class Binding { identifier: t.Identifier; scope: Scope; path: NodePath; - kind: 'var' | 'let' | 'const'; + kind: 'var' | 'let' | 'const' | 'module'; referenced: boolean; references: number; referencePaths: NodePath[]; diff --git a/backlog-js/index.d.ts b/backlog-js/index.d.ts index b548241e2f..d06f764baa 100644 --- a/backlog-js/index.d.ts +++ b/backlog-js/index.d.ts @@ -23,9 +23,9 @@ declare class Request { method: string; path: string; params?: Params | FormData; - }): Promise; - checkStatus(response: ResponseInterface): Promise; - parseJSON(response: ResponseInterface): Promise; + }): Promise; + checkStatus(response: Response): Promise; + parseJSON(response: Response): Promise; private toFormData(params); private toQueryString(params); webAppBaseURL: string; @@ -49,7 +49,7 @@ export class Backlog extends Request { putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise; getSpaceDiskUsage(): Promise; getSpaceIcon(): Promise; - postSpaceAttachment(form: FormData): Promise; + postSpaceAttachment(form: FormData): Promise; getUsers(): Promise; getUser(userId: number): Promise; postUser(params: Option.User.PostUserParams): Promise; @@ -656,7 +656,7 @@ export namespace Error { private _status; private _body; private _response; - constructor(name: BacklogErrorNameType, response: ResponseInterface, body?: { + constructor(name: BacklogErrorNameType, response: Response, body?: { errors: BacklogErrorMessage[]; }); name: BacklogErrorNameType; @@ -665,20 +665,20 @@ export namespace Error { body: { errors: BacklogErrorMessage[]; }; - response: ResponseInterface; + response: Response; } export class BacklogApiError extends BacklogError { - constructor(response: ResponseInterface, body?: { + constructor(response: Response, body?: { errors: BacklogErrorMessage[]; }); } export class BacklogAuthError extends BacklogError { - constructor(response: ResponseInterface, body?: { + constructor(response: Response, body?: { errors: BacklogErrorMessage[]; }); } export class UnexpectedError extends BacklogError { - constructor(response: ResponseInterface); + constructor(response: Response); } export interface BacklogErrorMessage { message: string; diff --git a/base-64/base-64-tests.ts b/base-64/base-64-tests.ts index a0f85f09aa..3435ae8265 100644 --- a/base-64/base-64-tests.ts +++ b/base-64/base-64-tests.ts @@ -1,13 +1,13 @@ import * as base64 from 'base-64'; import * as utf8 from 'utf8'; - + let text = 'foo © bar 𝌆 baz'; let bytes = utf8.encode(text); let encoded = base64.encode(bytes); -// → 'Zm9vIMKpIGJhciDwnYyGIGJheg==' +// → 'Zm9vIMKpIGJhciDwnYyGIGJheg==' encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg=='; bytes = base64.decode(encoded); text = utf8.decode(bytes); -let version = base64.version; +const version = base64.version; diff --git a/base-64/index.d.ts b/base-64/index.d.ts index 3d6fd885d2..ddd10db17b 100644 --- a/base-64/index.d.ts +++ b/base-64/index.d.ts @@ -6,19 +6,19 @@ export const version: string; /** - * This function takes a byte string (the input parameter) and encodes it according to base64. - * The input data must be in the form of a string containing only characters - * in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. - * The base64.encode() function is designed to be fully compatible + * This function takes a byte string (the input parameter) and encodes it according to base64. + * The input data must be in the form of a string containing only characters + * in the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. + * The base64.encode() function is designed to be fully compatible * with btoa() as described in the HTML Standard. * see: https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-btoa */ export function encode(input: string): string; /** - * This function takes a base64-encoded string (the input parameter) and decodes it. - * The return value is in the form of a string containing only characters in - * the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. - * The base64.decode() function is designed to be fully compatible + * This function takes a base64-encoded string (the input parameter) and decodes it. + * The return value is in the form of a string containing only characters in + * the range from U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF. + * The base64.decode() function is designed to be fully compatible * with atob() as described in the HTML Standard. * see: https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-atob */ diff --git a/base-64/tslint.json b/base-64/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/base-64/tslint.json +++ b/base-64/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/base64-js/tslint.json b/base64-js/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/base64-js/tslint.json +++ b/base64-js/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/basic-auth/index.d.ts b/basic-auth/index.d.ts index 3dc19b3046..51ada3b0c7 100644 --- a/basic-auth/index.d.ts +++ b/basic-auth/index.d.ts @@ -3,9 +3,11 @@ // Definitions by: Clément Bourgeois // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import * as Express from 'express'; +/// -declare function auth(req: Express.Request): auth.BasicAuthResult; +import * as http from 'http'; + +declare function auth(req: http.IncomingMessage): auth.BasicAuthResult; declare namespace auth { interface BasicAuthResult { diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts index 5776ffd307..f5fba4d947 100644 --- a/bezier-js/bezier-js-tests.ts +++ b/bezier-js/bezier-js-tests.ts @@ -10,7 +10,7 @@ function test() { var utils = bezier.getUtils(); var line: BezierJs.Line = { p1: { x: 0, y: 0 }, p2: { x: 1, y: 1 } }; var abc: BezierJs.ABC = { A: null, B: null, C: null }; - var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 }; + var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1, interval:{ start: 0, end: 1 } }; var bbox: BezierJs.BBox = bezier.bbox(); var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z: [0] }; @@ -95,4 +95,4 @@ function test() { utils.round(.999, .001); utils.shapeintersections(shape, bbox, shape, bbox); -} \ No newline at end of file +} diff --git a/bezier-js/index.d.ts b/bezier-js/index.d.ts index ff07e67f16..7706a46472 100644 --- a/bezier-js/index.d.ts +++ b/bezier-js/index.d.ts @@ -51,6 +51,7 @@ declare namespace BezierJs { e: number; r: number; s: number; + interval: { start: number; end: number; }; } interface Shape { startcap: BezierCap; diff --git a/bigi/bigi-tests.ts b/bigi/bigi-tests.ts index 82ba89fb18..70569bb919 100644 --- a/bigi/bigi-tests.ts +++ b/bigi/bigi-tests.ts @@ -1,9 +1,9 @@ -import BigInteger = require('bigi') +import BigInteger = require('bigi'); -var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012") -var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811") +var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"); +var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); -var b3 = b1.multiply(b2) +var b3 = b1.multiply(b2); -console.log(b3.toHex()) +console.log(b3.toHex()); // => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132 \ No newline at end of file diff --git a/bintrees/index.d.ts b/bintrees/index.d.ts index 9853be67dc..7a7b2c233e 100644 --- a/bintrees/index.d.ts +++ b/bintrees/index.d.ts @@ -5,7 +5,7 @@ declare module 'bintrees' { - type Callback = (err: Error, item: T) => void; + type Callback = (item: T) => void; type Comparator = (a: T, b: T) => number; class Iterator { diff --git a/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/bitcoinjs-lib/bitcoinjs-lib-tests.ts index 9341d60c66..bdaee3ee83 100644 --- a/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -1,63 +1,64 @@ /// -import bigi = require('bigi') +import bigi = require('bigi'); import bitcoin = require('bitcoinjs-lib'); declare var it: any; declare var describe: any; declare var assert: any; -describe('bitcoinjs-lib (basic)', function () { - it('can generate a random bitcoin address', function () { +describe('bitcoinjs-lib (basic)', () => { + it('can generate a random bitcoin address', () => { // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') } + function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } // generate random keyPair - var keyPair = bitcoin.ECPair.makeRandom({ rng: rng }) - var address = keyPair.getAddress() + var keyPair = bitcoin.ECPair.makeRandom({ rng }); + var address = keyPair.getAddress(); - assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64') - }) + assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64'); + }); - it('can generate an address from a SHA256 hash', function () { - var hash = bitcoin.crypto.sha256('correct horse battery staple') - var d = bigi.fromBuffer(hash) + it('can generate an address from a SHA256 hash', () => { + var hash = bitcoin.crypto.sha256('correct horse battery staple'); + var d = bigi.fromBuffer(hash); - var keyPair = new bitcoin.ECPair(d) - var address = keyPair.getAddress() + var keyPair = new bitcoin.ECPair(d); + var address = keyPair.getAddress(); - assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8') - }) + assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8'); + }); - it('can generate a random keypair for alternative networks', function () { + it('can generate a random keypair for alternative networks', () => { // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') } + function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } - var litecoin = bitcoin.networks.litecoin + var litecoin = bitcoin.networks.litecoin; - var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng: rng }) - var wif = keyPair.toWIF() - var address = keyPair.getAddress() + var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); + var wif = keyPair.toWIF(); + var address = keyPair.getAddress(); - assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn') - assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS') - }) + assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn'); + assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS'); + }); - it('can import an address via WIF', function () { - var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct') - var address = keyPair.getAddress() + it('can import an address via WIF', () => { + var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct'); + var address = keyPair.getAddress(); - assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31') - }) + assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31'); + }); - it('can create a Transaction', function () { - var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy') - var tx = new bitcoin.TransactionBuilder() + it('can create a Transaction', () => { + var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'); + var tx = new bitcoin.TransactionBuilder(); - tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0) - tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000) - tx.sign(0, keyPair) + tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0); + tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000); + tx.sign(0, keyPair); - assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000') - }) -}) \ No newline at end of file + // tslint:disable-next-line:max-line-length + assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000'); + }); +}); diff --git a/bittorrent-protocol/bittorrent-protocol-tests.ts b/bittorrent-protocol/bittorrent-protocol-tests.ts index 1d73154565..1d0d17793a 100644 --- a/bittorrent-protocol/bittorrent-protocol-tests.ts +++ b/bittorrent-protocol/bittorrent-protocol-tests.ts @@ -1,20 +1,20 @@ import * as Protocol from 'bittorrent-protocol'; import * as net from 'net'; -net.createServer(function(socket) { +net.createServer(socket => { var wire = new Protocol(); // pipe to and from the protocol socket.pipe(wire).pipe(socket); - wire.on('handshake', function(infoHash, peerId) { + wire.on('handshake', (infoHash, peerId) => { // receive a handshake (infoHash and peerId are hex strings) // lets emit a handshake of our own as well wire.handshake('my info hash (hex)', 'my peer id (hex)'); }); - wire.on('unchoke', function() { + wire.on('unchoke', () => { console.log('peer is no longer choking us: ' + wire.peerChoking); }); }).listen(6881); diff --git a/bittorrent-protocol/tsconfig.json b/bittorrent-protocol/tsconfig.json index 65222bf056..9258205ba7 100644 --- a/bittorrent-protocol/tsconfig.json +++ b/bittorrent-protocol/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "bittorrent-protocol-tests.ts" - ] -} + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bittorrent-protocol-tests.ts" + ] +} \ No newline at end of file diff --git a/bittorrent-protocol/tslint.json b/bittorrent-protocol/tslint.json index ec365f164b..3c4a3237e8 100644 --- a/bittorrent-protocol/tslint.json +++ b/bittorrent-protocol/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" + "extends": "../tslint.json", + "rules": { + "no-misused-new": false + } } diff --git a/blacklist/blacklist-tests.ts b/blacklist/blacklist-tests.ts index daff924403..0f465dd62a 100644 --- a/blacklist/blacklist-tests.ts +++ b/blacklist/blacklist-tests.ts @@ -1,13 +1,13 @@ -var someInput = { a: 1, b: 2, c: 3 } +var someInput = { a: 1, b: 2, c: 3 }; -import blacklist = require('blacklist') +import blacklist = require('blacklist'); -blacklist(someInput, 'b', 'c') +blacklist(someInput, 'b', 'c'); // => { a: 1 } blacklist(someInput, { a: true, // a will not be in the result b: false, // b will be in the result c: 1 > 2 // false, therefore c will be in the result -}) +}); // => { b: 2, c: 3 } \ No newline at end of file diff --git a/bluebird-global/tslint.json b/bluebird-global/tslint.json index eaffa3152c..b03221674a 100644 --- a/bluebird-global/tslint.json +++ b/bluebird-global/tslint.json @@ -1,9 +1,10 @@ { - "extends": "../tslint.json", - "rules": { - "no-empty-interface": false, - "array-type": false, - "unified-signatures": false, - "forbidden-types": false - } + "extends": "../tslint.json", + "rules": { + "max-line-length": false, + "no-empty-interface": false, + "array-type": false, + "unified-signatures": false, + "forbidden-types": false + } } diff --git a/body-parser/index.d.ts b/body-parser/index.d.ts index b8a1b0dc86..4627c2c5b3 100644 --- a/body-parser/index.d.ts +++ b/body-parser/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser // Project: http://expressjs.com -// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle +// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle , Gevik Babakhani // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -41,7 +41,14 @@ declare function bodyParser(options?: { }): express.RequestHandler; declare namespace bodyParser { - export function json(options?: { + + /** + * Interface for defining the options for the json() middleware + * + * @export + * @interface JsonOptions + */ + export interface JsonOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -66,9 +73,15 @@ declare namespace bodyParser { * passed to JSON.parse(). */ reviver?: (key: string, value: any) => any; - }): express.RequestHandler; + } - export function raw(options?: { + /** + * Interface for defining the options the raw() middleware + * + * @export + * @interface RawOptions + */ + export interface RawOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -85,9 +98,15 @@ declare namespace bodyParser { * function to verify body content, the parsing can be aborted by throwing an error. */ verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - }): express.RequestHandler; + } - export function text(options?: { + /** + * Interface for defining the options for the text() middleware + * + * @export + * @interface TextOptions + */ + export interface TextOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -108,9 +127,15 @@ declare namespace bodyParser { * the default charset to parse as, if not specified in content-type. (default: 'utf-8') */ defaultCharset?: string; - }): express.RequestHandler; + } - export function urlencoded(options: { + /** + * Interface for defining the options for the urlencoded() middleware + * + * @export + * @interface UrlEncodedOptions + */ + export interface UrlEncodedOptions { /** * if deflated bodies will be inflated. (default: true) */ @@ -131,7 +156,47 @@ declare namespace bodyParser { * parse extended syntax with the qs module. */ extended: boolean; - }): express.RequestHandler; + } + + /** + * Returns middleware that only parses json. This parser accepts any Unicode encoding + * of the body and supports automatic inflation of gzip and deflate encodings. + * + * @export + * @param {JsonOptions} [options] + * @returns {express.RequestHandler} + */ + export function json(options?: JsonOptions): express.RequestHandler; + + /** + * Returns middleware that parses all bodies as a Buffer. This parser supports automatic + * inflation of gzip and deflate encodings. + * + * @export + * @param {RawOptions} [options] + * @returns {express.RequestHandler} + */ + export function raw(options?: RawOptions): express.RequestHandler; + + /** + * Returns middleware that parses all bodies as a string. This parser supports + * automatic inflation of gzip and deflate encodings. + * + * @export + * @param {TextOptions} [options] + * @returns {express.RequestHandler} + */ + export function text(options?: TextOptions): express.RequestHandler; + + /** + * Returns middleware that only parses urlencoded bodies. This parser accepts only + * UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings. + * + * @export + * @param {UrlEncodedOptions} [options] + * @returns {express.RequestHandler} + */ + export function urlencoded(options?: UrlEncodedOptions): express.RequestHandler; } export = bodyParser; diff --git a/bookshelf/index.d.ts b/bookshelf/index.d.ts index 3895ef95a1..56472a3213 100644 --- a/bookshelf/index.d.ts +++ b/bookshelf/index.d.ts @@ -2,6 +2,7 @@ // Project: http://bookshelfjs.org/ // Definitions by: Andrew Schurman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import Knex = require('knex'); import knex = require('knex'); diff --git a/browser-bunyan/browser-bunyan-tests.ts b/browser-bunyan/browser-bunyan-tests.ts index 656a8eb002..ffb2ebf7a7 100644 --- a/browser-bunyan/browser-bunyan-tests.ts +++ b/browser-bunyan/browser-bunyan-tests.ts @@ -4,5 +4,5 @@ var log = bunyan.createLogger({ name: 'play', serializers: bunyan.stdSerializers }); -log.debug({foo: 'bar'}, 'hi at debug') -log.trace('hi at trace') +log.debug({foo: 'bar'}, 'hi at debug'); +log.trace('hi at trace'); diff --git a/bufferstream/bufferstream-tests.ts b/bufferstream/bufferstream-tests.ts index 5d2bcbd4c7..06cbd43e28 100644 --- a/bufferstream/bufferstream-tests.ts +++ b/bufferstream/bufferstream-tests.ts @@ -1,13 +1,13 @@ -import BufferStream = require('bufferstream') +import BufferStream = require('bufferstream'); -var stream = new BufferStream({encoding:'utf8', size:'flexible'}); +var stream = new BufferStream({encoding: 'utf8', size: 'flexible'}); stream.enable(); stream.disable(); stream.split('//', ':'); stream.on('split', (chunk: any, token: any) => { - console.log("got '%s' by '%s'", chunk.toString(), token.toString()) + console.log("got '%s' by '%s'", chunk.toString(), token.toString()); }); stream.write("buffer:stream//23"); console.log(stream.toString()); diff --git a/bufferstream/index.d.ts b/bufferstream/index.d.ts index ab048e437f..1d1ffcdb10 100644 --- a/bufferstream/index.d.ts +++ b/bufferstream/index.d.ts @@ -58,7 +58,7 @@ declare class BufferStream extends stream.Duplex { shortcut for buffer.length */ length: number; -} +} // https://github.com/dodo/node-bufferstream/blob/master/src/buffer-stream.coffee#L28 declare namespace BufferStream { export interface Opts { diff --git a/bufferstream/tslint.json b/bufferstream/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/bufferstream/tslint.json +++ b/bufferstream/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/c3/index.d.ts b/c3/index.d.ts index aa960b0b60..5edb096395 100644 --- a/c3/index.d.ts +++ b/c3/index.d.ts @@ -248,6 +248,15 @@ declare namespace c3 { */ width?: number; }; + + spline?: { + interpolation?: { + /** + * Set custom spline interpolation + */ + type?: 'linear' | 'linear-closed' | 'basis' | 'basis-open' | 'basis-closed' | 'bundle' | 'cardinal' | 'cardinal-open' | 'cardinal-closed' | 'monotone'; + }; + }; } interface Data { diff --git a/camelcase-keys/camelcase-keys-tests.ts b/camelcase-keys/camelcase-keys-tests.ts index 2e8d7ab2d7..ed2865e9ce 100644 --- a/camelcase-keys/camelcase-keys-tests.ts +++ b/camelcase-keys/camelcase-keys-tests.ts @@ -1,10 +1,10 @@ import camelcaseKeys = require('camelcase-keys'); camelcaseKeys({'foo-bar': true}); -//=> {fooBar: true} +// => {fooBar: true} -camelcaseKeys({'foo-bar': true, nested: {unicorn_rainbow: true}}, {deep: true}); -//=> {fooBar: true, nested: {unicornRainbow: true}} +camelcaseKeys({'foo-bar': true, 'nested': {unicorn_rainbow: true}}, {deep: true}); +// => {fooBar: true, nested: {unicornRainbow: true}} -camelcaseKeys({_: [], 'foo-bar': true}); -//=> {_: [], fooBar: true} \ No newline at end of file +camelcaseKeys({'_': [], 'foo-bar': true}); +// => {_: [], fooBar: true} \ No newline at end of file diff --git a/cannon/cannon-tests.ts b/cannon/cannon-tests.ts new file mode 100644 index 0000000000..79ae76a6d8 --- /dev/null +++ b/cannon/cannon-tests.ts @@ -0,0 +1,6 @@ +import cannon = require("cannon"); + +var aabb = new cannon.AABB() + +aabb.setFromPoints([new cannon.Vec3(1,2,3)]); + diff --git a/cannon/index.d.ts b/cannon/index.d.ts new file mode 100644 index 0000000000..45e005d53d --- /dev/null +++ b/cannon/index.d.ts @@ -0,0 +1,1000 @@ +// Type definitions for cannon 0.1 +// Project: https://github.com/clark-stevenson/cannon.d.ts +// Definitions by: Clark Stevenson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module CANNON { + + export interface IAABBOptions { + + upperBound?: Vec3; + lowerBound?: Vec3; + + } + + export class AABB { + + lowerBound: Vec3; + upperBound: Vec3; + + constructor(options?: IAABBOptions); + + setFromPoints(points: Vec3[], position?: Vec3, quaternion?: Quaternion, skinSize?: number): void; + copy(aabb: AABB): void; + extend(aabb: AABB): void; + overlaps(aabb: AABB): boolean; + + } + + export class ArrayCollisionMatrix { + + matrix: Mat3[]; + + get(i: number, j: number): number; + set(i: number, j: number, value?: number): void; + reset(): void; + setNumObjects(n: number): void; + + } + + export class BroadPhase { + + world: World; + useBoundingBoxes: boolean; + dirty: boolean; + + collisionPairs(world: World, p1: Body[], p2: Body[]): void; + needBroadphaseCollision(bodyA: Body, bodyB: Body): boolean; + intersectionTest(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; + doBoundingSphereBroadphase(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; + doBoundingBoxBroadphase(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; + makePairsUnique(pairs1: Body[], pairs2: Body[]): void; + setWorld(world: World): void; + boundingSphereCheck(bodyA: Body, bodyB: Body): boolean; + aabbQuery(world: World, aabb: AABB, result: Body[]): Body[]; + + } + + export class GridBroadphase extends BroadPhase { + + nx: number; + ny: number; + nz: number; + aabbMin: Vec3; + aabbMax: Vec3; + bins: any[]; + + constructor(aabbMin?: Vec3, aabbMax?: Vec3, nx?: number, ny?: number, nz?: number); + + } + + export class NaiveBroadphase extends BroadPhase { + } + + export class ObjectCollisionMatrix { + + matrix: number[]; + + get(i: number, j: number): number; + set(i: number, j: number, value: number): void; + reset(): void; + setNumObjects(n: number): void; + + } + + export class Ray { + + from: Vec3; + to: Vec3; + precision: number; + checkCollisionResponse: boolean; + + constructor(from?: Vec3, to?: Vec3); + + getAABB(result: RaycastResult): void; + + } + + export class RaycastResult { + + rayFromWorld: Vec3; + rayToWorld: Vec3; + hitNormalWorld: Vec3; + hitPointWorld: Vec3; + hasHit: boolean; + shape: Shape; + body: Body; + distance: number; + + reset(): void; + set(rayFromWorld: Vec3, rayToWorld: Vec3, hitNormalWorld: Vec3, hitPointWorld: Vec3, shape: Shape, body: Body, distance: number): void; + + } + + export class SAPBroadphase extends BroadPhase { + + static insertionSortX(a: any[]): any[]; + static insertionSortY(a: any[]): any[]; + static insertionSortZ(a: any[]): any[]; + static checkBounds(bi: Body, bj: Body, axisIndex?: number): boolean; + + axisList: any[]; + world: World; + axisIndex: number; + + constructor(world?: World); + + autoDetectAxis(): void; + aabbQuery(world: World, aabb: AABB, result?: Body[]): Body[]; + + } + + export interface IConstraintOptions { + + collideConnected?: boolean; + wakeUpBodies?: boolean; + + } + + export class Constraint { + + equations: any[]; + bodyA: Body; + bodyB: Body; + id: number; + collideConnected: boolean; + + constructor(bodyA: Body, bodyB: Body, options?: IConstraintOptions); + + update(): void; + + } + + export class DistanceConstraint extends Constraint { + + constructor(bodyA: Body, bodyB: Body, distance: number, maxForce?: number); + + } + + export interface IHingeConstraintOptions { + + pivotA?: Vec3; + axisA?: Vec3; + pivotB?: Vec3; + axisB?: Vec3; + maxForce?: number; + + } + + export class HingeConstraint extends Constraint { + + motorEnabled: boolean; + motorTargetVelocity: number; + motorMinForce: number; + motorMaxForce: number; + motorEquation: RotationalMotorEquation; + + constructor(bodyA: Body, bodyB: Body, options?: IHingeConstraintOptions); + + enableMotor(): void; + disableMotor(): void; + + } + + export class PointToPointConstraint extends Constraint { + + constructor(bodyA: Body, pivotA: Vec3, bodyB: Body, pivotB: Vec3, maxForce?: number); + + } + + + export class LockConstraint extends Constraint { + constructor(bodyA: Body, bodyB: Body, options?:any); + } + + + + export class Equation { + + id: number; + minForce: number; + maxForce: number; + bi: Body; + bj: Body; + a: number; + b: number; + eps: number; + jacobianElementA: JacobianElement; + jacobianElementB: JacobianElement; + enabled: boolean; + + constructor(bi: Body, bj: Body, minForce?: number, maxForce?: number); + + setSpookParams(stiffness: number, relaxation: number, timeStep: number): void; + computeB(a: number, b: number, h: number): number; + computeGq(): number; + computeGW(): number; + computeGWlamda(): number; + computeGiMf(): number; + computeGiMGt(): number; + addToWlamda(deltalambda: number): number; + computeC(): number; + + } + + export class FrictionEquation extends Equation { + + constructor(bi: Body, bj: Body, slipForce: number); + + } + + export class RotationalEquation extends Equation { + + ni: Vec3; + nj: Vec3; + nixnj: Vec3; + njxni: Vec3; + invIi: Mat3; + invIj: Mat3; + relVel: Vec3; + relForce: Vec3; + + constructor(bodyA: Body, bodyB: Body); + + } + + export class RotationalMotorEquation extends Equation { + + axisA: Vec3; + axisB: Vec3; + invLi: Mat3; + invIj: Mat3; + targetVelocity: number; + + constructor(bodyA: Body, bodyB: Body, maxForce?: number); + + } + + export class ContactEquation extends Equation { + + restitution: number; + ri: Vec3; + rj: Vec3; + penetrationVec: Vec3; + ni: Vec3; + rixn: Vec3; + rjxn: Vec3; + invIi: Mat3; + invIj: Mat3; + biInvInertiaTimesRixn: Vec3; + bjInvInertiaTimesRjxn: Vec3; + + constructor(bi: Body, bj: Body); + + } + + export interface IContactMaterialOptions { + + friction?: number; + restitution?: number; + contactEquationStiffness?: number; + contactEquationRelaxation?: number; + frictionEquationStiffness?: number; + frictionEquationRelaxation?: number; + + } + + export class ContactMaterial { + + id: number; + materials: Material[]; + friction: number; + restitution: number; + contactEquationStiffness: number; + contactEquationRelaxation: number; + frictionEquationStiffness: number; + frictionEquationRelaxation: number; + + constructor(m1: Material, m2: Material, options?: IContactMaterialOptions); + + } + + export class Material { + + name: string; + id: number; + friction:number; + restitution:number; + + constructor(name: string); + + } + + export class JacobianElement { + + spatial: Vec3; + rotational: Vec3; + + multiplyElement(element: JacobianElement): number; + multiplyVectors(spacial: Vec3, rotational: Vec3): number; + + } + + export class Mat3 { + + constructor(elements?: number[]); + + identity(): void; + setZero(): void; + setTrace(vec3: Vec3): void; + getTrace(target: Vec3): void; + vmult(v: Vec3, target?: Vec3): Vec3; + smult(s: number): void; + mmult(m: Mat3): Mat3; + scale(v: Vec3, target?: Mat3): Mat3; + solve(b: Vec3, target?: Vec3): Vec3; + e(row: number, column: number, value?: number): number; + copy(source: Mat3): Mat3; + toString(): string; + reverse(target?: Mat3): Mat3; + setRotationFromQuaternion(q: Quaternion): Mat3; + transpose(target?: Mat3): Mat3; + + } + + export class Quaternion { + + x: number; + y: number; + z: number; + w: number; + + constructor(x?: number, y?: number, z?: number, w?: number); + + set(x: number, y: number, z: number, w: number): void; + toString(): string; + toArray(): number[]; + setFromAxisAngle(axis: Vec3, angle: number): void; + toAxisAngle(targetAxis?: Vec3): any[]; + setFromVectors(u: Vec3, v: Vec3): void; + mult(q: Quaternion, target?: Quaternion): Quaternion; + inverse(target?: Quaternion): Quaternion; + conjugate(target?: Quaternion): Quaternion; + normalize(): void; + normalizeFast(): void; + vmult(v: Vec3, target?: Vec3): Vec3; + copy(source: Quaternion): Quaternion; + toEuler(target: Vec3, order?: string): void; + setFromEuler(x: number, y: number, z: number, order?: string): Quaternion; + clone(): Quaternion; + + } + + export class Transform { + + static pointToLocalFrame(position: Vec3, quaternion: Quaternion, worldPoint: Vec3, result?: Vec3): Vec3; + static pointToWorldFrame(position: Vec3, quaternion: Quaternion, localPoint: Vec3, result?: Vec3): Vec3; + + position: Vec3; + quaternion: Quaternion; + + vectorToWorldFrame(localVector: Vec3, result?: Vec3): Vec3; + vectorToLocalFrame(position: Vec3, quaternion: Quaternion, worldVector: Vec3, result?: Vec3): Vec3; + + } + + export class Vec3 { + + static ZERO: Vec3; + + x: number; + y: number; + z: number; + + constructor(x?: number, y?: number, z?: number); + + cross(v: Vec3, target?: Vec3): Vec3; + set(x: number, y: number, z: number): Vec3; + setZero(): void; + vadd(v: Vec3, target?: Vec3): Vec3; + vsub(v: Vec3, target?: Vec3): Vec3; + crossmat(): Mat3; + normalize(): number; + unit(target?: Vec3): Vec3; + norm(): number; + norm2(): number; + distanceTo(p: Vec3): number; + mult(scalar: number, target?: Vec3): Vec3; + scale(scalar: number, target?: Vec3): Vec3; + dot(v: Vec3): number; + isZero(): boolean; + negate(target?: Vec3): Vec3; + tangents(t1: Vec3, t2: Vec3): void; + toString(): string; + toArray(): number[]; + copy(source: Vec3): Vec3; + lerp(v: Vec3, t: number, target?: Vec3): void; + almostEquals(v: Vec3, precision?: number): boolean; + almostZero(precision?: number): boolean; + isAntiparallelTo(v: Vec3, prescision?: number): boolean; + clone(): Vec3; + + } + + export interface IBodyOptions { + position?: Vec3; + velocity?: Vec3; + angularVelocity?: Vec3; + quaternion?: Quaternion; + mass?: number; + material?: number; + type?: number; + linearDamping?: number; + angularDamping?: number; + } + + export class Body extends EventTarget { + + static DYNAMIC: number; + static STATIC: number; + static KINEMATIC: number; + static AWAKE: number; + static SLEEPY: number; + static SLEEPING: number; + static sleepyEvent: IEvent; + static sleepEvent: IEvent; + + id: number; + world: World; + preStep: Function; + postStep: Function; + vlambda: Vec3; + collisionFilterGroup: number; + collisionFilterMask: number; + collisionResponse: boolean; + position: Vec3; + previousPosition: Vec3; + initPosition: Vec3; + velocity: Vec3; + initVelocity: Vec3; + force: Vec3; + mass: number; + invMass: number; + material: Material; + linearDamping: number; + type: number; + allowSleep: boolean; + sleepState: number; + sleepSpeedLimit: number; + sleepTimeLimit: number; + timeLastSleepy: number; + torque: Vec3; + quaternion: Quaternion; + initQuaternion: Quaternion; + angularVelocity: Vec3; + initAngularVelocity: Vec3; + interpolatedPosition: Vec3; + interpolatedQuaternion: Quaternion; + shapes: Shape[]; + shapeOffsets: any[]; + shapeOrentiations: any[]; + inertia: Vec3; + invInertia: Vec3; + invInertiaWorld: Mat3; + invMassSolve: number; + invInertiaSolve: Vec3; + invInteriaWorldSolve: Mat3; + fixedRotation: boolean; + angularDamping: number; + aabb: AABB; + aabbNeedsUpdate: boolean; + wlambda: Vec3; + + constructor(options?: IBodyOptions); + + wakeUp(): void; + sleep(): void; + sleepTick(time: number): void; + updateSolveMassProperties(): void; + pointToLocalFrame(worldPoint: Vec3, result?: Vec3): Vec3; + pointToWorldFrame(localPoint: Vec3, result?: Vec3): Vec3; + vectorToWorldFrame(localVector: Vec3, result?: Vec3): Vec3; + addShape(shape: Shape, offset?: Vec3, orientation?: Quaternion): void; + updateBoundingRadius(): void; + computeAABB(): void; + updateInertiaWorld(force: Vec3): void; + applyForce(force: Vec3, worldPoint: Vec3): void; + applyImpulse(impulse: Vec3, worldPoint: Vec3): void; + updateMassProperties(): void; + getVelocityAtWorldPoint(worldPoint: Vec3, result: Vec3): Vec3; + + } + + export interface IRaycastVehicleOptions { + + chassisBody?: Body; + indexRightAxis?: number; + indexLeftAxis?: number; + indexUpAxis?: number; + + } + + export interface IWheelInfoOptions { + + chassisConnectionPointLocal?: Vec3; + chassisConnectionPointWorld?: Vec3; + directionLocal?: Vec3; + directionWorld?: Vec3; + axleLocal?: Vec3; + axleWorld?: Vec3; + suspensionRestLength?: number; + suspensionMaxLength?: number; + radius?: number; + suspensionStiffness?: number; + dampingCompression?: number; + dampingRelaxation?: number; + frictionSlip?: number; + steering?: number; + rotation?: number; + deltaRotation?: number; + rollInfluence?: number; + maxSuspensionForce?: number; + isFronmtWheel?: boolean; + clippedInvContactDotSuspension?: number; + suspensionRelativeVelocity?: number; + suspensionForce?: number; + skidInfo?: number; + suspensionLength?: number; + maxSuspensionTravel?: number; + useCustomSlidingRotationalSpeed?: boolean; + customSlidingRotationalSpeed?: number; + + position?: Vec3; + direction?: Vec3; + axis?: Vec3; + body?: Body; + + } + + export class WheelInfo { + + maxSuspensionTravbel: number; + customSlidingRotationalSpeed: number; + useCustomSlidingRotationalSpeed: boolean; + sliding: boolean; + chassisConnectionPointLocal: Vec3; + chassisConnectionPointWorld: Vec3; + directionLocal: Vec3; + directionWorld: Vec3; + axleLocal: Vec3; + axleWorld: Vec3; + suspensionRestLength: number; + suspensionMaxLength: number; + radius: number; + suspensionStiffness: number; + dampingCompression: number; + dampingRelaxation: number; + frictionSlip: number; + steering: number; + rotation: number; + deltaRotation: number; + rollInfluence: number; + maxSuspensionForce: number; + engineForce: number; + brake: number; + isFrontWheel: boolean; + clippedInvContactDotSuspension: number; + suspensionRelativeVelocity: number; + suspensionForce: number; + skidInfo: number; + suspensionLength: number; + sideImpulse: number; + forwardImpulse: number; + raycastResult: RaycastResult; + worldTransform: Transform; + isInContact: boolean; + + constructor(options?: IWheelInfoOptions); + + } + + export class RaycastVehicle { + + chassisBody: Body; + wheelInfos: IWheelInfoOptions[]; + sliding: boolean; + world: World; + iindexRightAxis: number; + indexForwardAxis: number; + indexUpAxis: number; + + constructor(options?: IRaycastVehicleOptions); + + addWheel(options?: IWheelInfoOptions): void; + setSteeringValue(value: number, wheelIndex: number): void; + applyEngineForce(value: number, wheelIndex: number): void; + setBrake(brake: number, wheelIndex: number): void; + addToWorld(world: World): void; + getVehicleAxisWorld(axisIndex: number, result: Vec3): Vec3; + updateVehicle(timeStep: number): void; + updateSuspension(deltaTime: number): void; + removeFromWorld(world: World): void; + getWheelTransformWorld(wheelIndex: number): Transform; + + } + + export interface IRigidVehicleOptions { + + chassisBody: Body; + + } + + export class RigidVehicle { + + wheelBodies: Body[]; + coordinateSystem: Vec3; + chassisBody: Body; + constraints: Constraint[]; + wheelAxes: Vec3[]; + wheelForces: Vec3[]; + + constructor(options?: IRigidVehicleOptions); + + addWheel(options?: IWheelInfoOptions): Body; + setSteeringValue(value: number, wheelIndex: number): void; + setMotorSpeed(value: number, wheelIndex: number): void; + disableMotor(wheelIndex: number): void; + setWheelForce(value: number, wheelIndex: number): void; + applyWheelForce(value: number, wheelIndex: number): void; + addToWorld(world: World): void; + removeFromWorld(world: World): void; + getWheelSpeed(wheelIndex: number): number; + + } + + export class SPHSystem { + + particles: Particle[]; + density: number; + smoothingRadius: number; + speedOfSound: number; + viscosity: number; + eps: number; + pressures: number[]; + densities: number[]; + neighbors: number[]; + + add(particle: Particle): void; + remove(particle: Particle): void; + getNeighbors(particle: Particle, neighbors: Particle[]): void; + update(): void; + w(r: number): number; + gradw(rVec: Vec3, resultVec: Vec3): void; + nablaw(r: number): number; + + } + + export interface ISpringOptions { + + restLength?: number; + stiffness?: number; + damping?: number; + worldAnchorA?: Vec3; + worldAnchorB?: Vec3; + localAnchorA?: Vec3; + localAnchorB?: Vec3; + + } + + export class Spring { + + restLength: number; + stffness: number; + damping: number; + bodyA: Body; + bodyB: Body; + localAnchorA: Vec3; + localAnchorB: Vec3; + + constructor(options?: ISpringOptions); + + setWorldAnchorA(worldAnchorA: Vec3): void; + setWorldAnchorB(worldAnchorB: Vec3): void; + getWorldAnchorA(result: Vec3): void; + getWorldAnchorB(result: Vec3): void; + applyForce(): void; + + } + + export class Box extends Shape { + + static calculateIntertia(halfExtents: Vec3, mass: number, target: Vec3): void; + + boundingSphereRadius: number; + collisionResponse: boolean; + halfExtents: Vec3; + convexPolyhedronRepresentation: ConvexPolyhedron; + + constructor(halfExtents: Vec3); + + updateConvexPolyhedronRepresentation(): void; + calculateLocalInertia(mass: number, target?: Vec3): Vec3; + getSideNormals(sixTargetVectors: boolean, quat?: Quaternion): Vec3[]; + updateBoundingSphereRadius(): number; + volume(): number; + forEachWorldCorner(pos: Vec3, quat: Quaternion, callback: Function): void; + + } + + export class ConvexPolyhedron extends Shape { + + static computeNormal(va: Vec3, vb: Vec3, vc: Vec3, target: Vec3): void; + static project(hull: ConvexPolyhedron, axis: Vec3, pos: Vec3, quat: Quaternion, result: number[]): void; + + vertices: Vec3[]; + worldVertices: Vec3[]; + worldVerticesNeedsUpdate: boolean; + faces: number[]; + faceNormals: Vec3[]; + uniqueEdges: Vec3[]; + + constructor(points?: Vec3[], faces?: number[]); + + computeEdges(): void; + computeNormals(): void; + getFaceNormal(i: number, target: Vec3): Vec3; + clipAgainstHull(posA: Vec3, quatA: Quaternion, hullB: Vec3, quatB: Quaternion, separatingNormal: Vec3, minDist: number, maxDist: number, result: any[]): void; + findSaparatingAxis(hullB: ConvexPolyhedron, posA: Vec3, quatA: Quaternion, posB: Vec3, quatB: Quaternion, target: Vec3, faceListA: any[], faceListB: any[]): boolean; + testSepAxis(axis: Vec3, hullB: ConvexPolyhedron, posA: Vec3, quatA: Quaternion, posB: Vec3, quatB: Quaternion): number; + getPlaneConstantOfFace(face_i: number): number; + clipFaceAgainstHull(separatingNormal: Vec3, posA: Vec3, quatA: Quaternion, worldVertsB1: Vec3[], minDist: number, maxDist: number, result: any[]): void; + clipFaceAgainstPlane(inVertices: Vec3[], outVertices: Vec3[], planeNormal: Vec3, planeConstant: number): Vec3; + computeWorldVertices(position: Vec3, quat: Quaternion): void; + computeLocalAABB(aabbmin: Vec3, aabbmax: Vec3): void; + computeWorldFaceNormals(quat: Quaternion): void; + calculateWorldAABB(pos: Vec3, quat: Quaternion, min: Vec3, max: Vec3): void; + getAveragePointLocal(target: Vec3): Vec3; + transformAllPoints(offset: Vec3, quat: Quaternion): void; + pointIsInside(p: Vec3): boolean; + + } + + export class Cylinder extends Shape { + + constructor(radiusTop: number, radiusBottom: number, height: number, numSegments: number); + + } + + export interface IHightfield { + + minValue?: number; + maxValue?: number; + elementSize: number; + + } + + export class Heightfield extends Shape { + + data: number[]; + maxValue: number; + minValue: number; + elementSize: number; + cacheEnabled: boolean; + pillarConvex: ConvexPolyhedron; + pillarOffset: Vec3; + type: number; + + constructor(data: number[], options?: IHightfield); + + update(): void; + updateMinValue(): void; + updateMaxValue(): void; + setHeightValueAtIndex(xi: number, yi: number, value: number): void; + getRectMinMax(iMinX: number, iMinY: number, iMaxX: number, iMaxY: number, result: any[]): void; + getIndexOfPosition(x: number, y: number, result: any[], clamp: boolean): boolean; + getConvexTrianglePillar(xi: number, yi: number, getUpperTriangle: boolean): void; + + } + + export class Particle extends Shape { + + } + + export class Plane extends Shape { + + worldNormal: Vec3; + worldNormalNeedsUpdate: boolean; + boundingSphereRadius: number; + + computeWorldNormal(quat: Quaternion): void; + calculateWorldAABB(pos: Vec3, quat: Quaternion, min: number, max: number): void; + + } + + export class Shape { + + static types: { + + SPHERE: number; + PLANE: number; + BOX: number; + COMPOUND: number; + CONVEXPOLYHEDRON: number; + HEIGHTFIELD: number; + PARTICLE: number; + CYLINDER: number; + + } + + type: number; + boundingSphereRadius: number; + collisionResponse: boolean; + + updateBoundingSphereRadius(): number; + volume(): number; + calculateLocalInertia(mass: number, target: Vec3): Vec3; + + } + + export class Sphere extends Shape { + + radius: number; + + constructor(radius: number); + + } + + export class GSSolver extends Solver { + + iterations: number; + tolerance: number; + + solve(dy: number, world: World): number; + + + } + + export class Solver { + iterations: number; + equations: Equation[]; + + solve(dy: number, world: World): number; + addEquation(eq: Equation): void; + removeEquation(eq: Equation): void; + removeAllEquations(): void; + + } + + export class SplitSolver extends Solver { + + subsolver: Solver; + + constructor(subsolver: Solver); + + solve(dy: number, world: World): number; + + } + + export class EventTarget { + + addEventListener(type: string, listener: Function): EventTarget; + hasEventListener(type: string, listener: Function): boolean; + removeEventListener(type: string, listener: Function): EventTarget; + dispatchEvent(event: IEvent): IEvent; + + } + + export class Pool { + + objects: any[]; + type: any[]; + + release(): any; + get(): any; + constructObject(): any; + + } + + export class TupleDictionary { + + data: { + keys: any[]; + }; + + get(i: number, j: number): number; + set(i: number, j: number, value: number): void; + reset(): void; + + } + + export class Utils { + + static defaults(options?: any, defaults?: any): any; + + } + + export class Vec3Pool extends Pool { + + type: any; + + constructObject(): Vec3; + + } + + export class NarrowPhase { + + contactPointPool: Pool[]; + v3pool: Vec3Pool; + + } + + export class World extends EventTarget { + + dt: number; + allowSleep: boolean; + contacts: ContactEquation[]; + frictionEquations: FrictionEquation[]; + quatNormalizeSkip: number; + quatNormalizeFast: boolean; + time: number; + stepnumber: number; + default_dt: number; + nextId: number; + gravity: Vec3; + broadphase: NaiveBroadphase; + bodies: Body[]; + solver: Solver; + constraints: Constraint[]; + narrowPhase: NarrowPhase; + collisionMatrix: ArrayCollisionMatrix; + collisionMatrixPrevious: ArrayCollisionMatrix; + materials: Material[]; + contactmaterials: ContactMaterial[]; + contactMaterialTable: TupleDictionary; + defaultMaterial: Material; + defaultContactMaterial: ContactMaterial; + doProfiling: boolean; + profile: { + solve: number; + makeContactConstraints: number; + broadphaser: number; + integrate: number; + narrowphase: number; + }; + subsystems: any[]; + addBodyEvent: IBodyEvent; + removeBodyEvent: IBodyEvent; + + getContactMaterial(m1: Material, m2: Material): ContactMaterial; + numObjects(): number; + collisionMatrixTick(): void; + addBody(body: Body): void; + addConstraint(c: Constraint): void; + removeConstraint(c: Constraint): void; + rayTest(from: Vec3, to: Vec3, result: RaycastResult): void; + remove(body: Body): void; + addMaterial(m: Material): void; + addContactMaterial(cmat: ContactMaterial): void; + step(dy: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; + + } + + export interface IEvent { + + type: string; + + } + + export interface IBodyEvent extends IEvent { + + body: Body; + + } + +} + + +declare module "cannon" { + export = CANNON; +} diff --git a/cannon/tsconfig.json b/cannon/tsconfig.json new file mode 100644 index 0000000000..a59be4d465 --- /dev/null +++ b/cannon/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", + "cannon-tests.ts" + ] +} \ No newline at end of file diff --git a/cassandra-driver/index.d.ts b/cassandra-driver/index.d.ts index 16466316f4..1f7f2fe33d 100644 --- a/cassandra-driver/index.d.ts +++ b/cassandra-driver/index.d.ts @@ -147,7 +147,7 @@ export namespace types { three, quorum, all, - localQuorm, + localQuorum, eachQuorum, serial, localSerial, diff --git a/chai-enzyme/index.d.ts b/chai-enzyme/index.d.ts index 72842332ad..6997abd5fe 100644 --- a/chai-enzyme/index.d.ts +++ b/chai-enzyme/index.d.ts @@ -2,11 +2,13 @@ // Project: https://github.com/producthunt/chai-enzyme // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// /// +/// declare namespace Chai { type EnzymeSelector = string | React.StatelessComponent | React.ComponentClass | { [key: string]: any }; @@ -142,9 +144,9 @@ declare namespace Chai { } declare module "chai-enzyme" { - import { ShallowWrapper, ReactWrapper, CheerioWrapper } from "enzyme"; + import { ShallowWrapper, ReactWrapper } from "enzyme"; - type DebugWrapper = ShallowWrapper | CheerioWrapper | ReactWrapper; + type DebugWrapper = ShallowWrapper | Cheerio | ReactWrapper; function chaiEnzyMe(wrapper?: (debugWrapper: DebugWrapper) => string): (chai: any) => void; module chaiEnzyMe { diff --git a/chai-http/index.d.ts b/chai-http/index.d.ts index 567f13e4e7..2e619b6166 100644 --- a/chai-http/index.d.ts +++ b/chai-http/index.d.ts @@ -55,6 +55,7 @@ declare namespace ChaiHttp { send(data: Object): Request; auth(user: string, name: string): Request; field(name: string, val: string): Request; + buffer(): Request; end(callback?: (err: any, res: Response) => void): FinishedRequest; } diff --git a/chai-json-schema/chai-json-schema-tests.ts b/chai-json-schema/chai-json-schema-tests.ts index 8559d3caae..5d4715a76e 100644 --- a/chai-json-schema/chai-json-schema-tests.ts +++ b/chai-json-schema/chai-json-schema-tests.ts @@ -1,5 +1,3 @@ -/// - import { expect } from 'chai'; import { assert } from 'chai'; @@ -9,19 +7,19 @@ import ChaiJsonSchema = require('chai-json-schema'); chai.use(ChaiJsonSchema); chai.should(); -let goodApple = { +const goodApple = { skin: 'thin', colors: ['red', 'green', 'yellow'], taste: 10 }; -let badApple = { +const badApple = { colors: ['brown'], taste: 0, worms: 2 }; -let fruitSchema = { +const fruitSchema = { title: 'fresh fruit schema v1', type: 'object', required: ['skin', 'colors', 'taste'], @@ -44,13 +42,27 @@ let fruitSchema = { } }; -//bdd style +// bdd style expect(goodApple).to.be.jsonSchema(fruitSchema); expect(badApple).to.not.be.jsonSchema(fruitSchema); goodApple.should.be.jsonSchema(fruitSchema); badApple.should.not.be.jsonSchema(fruitSchema); -//tdd style +// tdd style assert.jsonSchema(goodApple, fruitSchema); assert.notJsonSchema(badApple, fruitSchema); + +// tv4 +const schema = { + items: { + type: 'boolean' + } +}; + +const data1 = [true, false]; +const data2 = [true, 123]; + +expect(chai.tv4.validate(data1, schema)).to.be.true; +expect(chai.tv4.validate(data2, schema)).to.be.false; + diff --git a/chai-json-schema/index.d.ts b/chai-json-schema/index.d.ts index e66e2c96af..1498510f9f 100644 --- a/chai-json-schema/index.d.ts +++ b/chai-json-schema/index.d.ts @@ -5,6 +5,7 @@ // // +import tv4 = require('tv4'); declare global { namespace Chai { @@ -16,6 +17,10 @@ declare global { export interface LanguageChains { jsonSchema(schema: any, msg?: string): void; } + + export interface ChaiStatic { + tv4: tv4.TV4; + } } } diff --git a/chai-oequal/tslint.json b/chai-oequal/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/chai-oequal/tslint.json +++ b/chai-oequal/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/chai-subset/chai-subset-tests.ts b/chai-subset/chai-subset-tests.ts index ded911ed19..33cf036cf8 100644 --- a/chai-subset/chai-subset-tests.ts +++ b/chai-subset/chai-subset-tests.ts @@ -8,7 +8,7 @@ var expect = chai.expect; var assert = chai.assert; function test_containSubset() { - var obj: Object = { + var obj = { a: 'b', c: 'd', e: { @@ -34,7 +34,7 @@ function test_containSubset() { } function test_notContainSubset() { - var obj: Object = { + var obj = { a: 'b', c: 'd', e: { @@ -50,16 +50,16 @@ function test_notContainSubset() { } function test_arrayContainSubset() { - var list: Array = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; + var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; - expect(list).to.containSubset([{a:'a', b: 'b'}]); - list.should.containSubset([{a:'a', b: 'b'}]); - assert.containSubset(list, [{a:'a', b: 'b'}]); + expect(list).to.containSubset([{a: 'a', b: 'b'}]); + list.should.containSubset([{a: 'a', b: 'b'}]); + assert.containSubset(list, [{a: 'a', b: 'b'}]); } function test_arrayNotContainSubset() { - var list: Array = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; + var list = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; - expect(list).not.to.containSubset([{a:'a', b: 'bd'}]); - list.should.not.containSubset([{a:'a', b: 'bd'}]); + expect(list).not.to.containSubset([{a: 'a', b: 'bd'}]); + list.should.not.containSubset([{a: 'a', b: 'bd'}]); } diff --git a/chai-subset/tslint.json b/chai-subset/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/chai-subset/tslint.json +++ b/chai-subset/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/chai-xml/chai-xml-tests.ts b/chai-xml/chai-xml-tests.ts index 492e671bbe..c217662316 100644 --- a/chai-xml/chai-xml-tests.ts +++ b/chai-xml/chai-xml-tests.ts @@ -2,10 +2,10 @@ import * as chai from 'chai'; import chaiXml = require('chai-xml'); chai.use(chaiXml); -let expect = chai.expect; +const expect = chai.expect; function test_chaiXml() { - let testXml = 'test'; + const testXml = 'test'; expect('nope').xml.not.to.be.valid(); expect(testXml).xml.to.be.valid(); expect(testXml).xml.to.equal('\ntest\n'); diff --git a/chai/index.d.ts b/chai/index.d.ts index 44750136c8..532aa3b579 100644 --- a/chai/index.d.ts +++ b/chai/index.d.ts @@ -358,6 +358,7 @@ declare namespace Chai { sameMembers(set1: any[], set2: any[], msg?: string): void; sameDeepMembers(set1: any[], set2: any[], msg?: string): void; includeMembers(superset: any[], subset: any[], msg?: string): void; + includeDeepMembers(superset: any[], subset: any[], msg?: string): void; ifError(val: any, msg?: string): void; diff --git a/charm/charm-tests.ts b/charm/charm-tests.ts index 0cdbdc8055..afc8cbc3b6 100644 --- a/charm/charm-tests.ts +++ b/charm/charm-tests.ts @@ -7,7 +7,7 @@ var colors: getCharm.CharmColor[] = [ 'red', 'cyan', 'yellow', 'green', 'blue' ] var text = 'Always after me lucky charms.'; var offset = 0; -var iv = setInterval(function () { +var iv = setInterval(() => { var y = 0, dy = 1; for (var i = 0; i < 40; i++) { var color = colors[(i + offset) % colors.length]; diff --git a/chart.js/index.d.ts b/chart.js/index.d.ts index 7a7b05c714..08781f4463 100644 --- a/chart.js/index.d.ts +++ b/chart.js/index.d.ts @@ -71,7 +71,7 @@ declare namespace Chart { } export interface ChartPoint { - x?: number; + x?: number | string | Date; y?: number; } @@ -103,6 +103,7 @@ declare namespace Chart { animation?: ChartAnimationOptions; elements?: ChartElementsOptions; scales?: ChartScales; + cutoutPercentage?: number; } export interface ChartFontOptions { @@ -430,4 +431,4 @@ declare namespace Chart { } export = Chart; -export as namespace Chart; \ No newline at end of file +export as namespace Chart; diff --git a/chrome/index.d.ts b/chrome/index.d.ts index 2822dd421e..211375a3fe 100644 --- a/chrome/index.d.ts +++ b/chrome/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome extension development // Project: http://developer.chrome.com/extensions/ -// Definitions by: Matthew Kimber , otiai10 , couven92 , RReverser +// Definitions by: Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -7062,13 +7062,12 @@ declare namespace chrome.webNavigation { transitionQualifiers: string[]; } - interface WebNavigationEventFilter { - /** Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event. */ - url: chrome.events.UrlFilter[]; + interface WebNavigationRequestFilter extends chrome.webRequest.RequestFilter { + /** fulfills the webRequest.RequestFilter interface even though it is under web navigation **/ } interface WebNavigationEvent extends chrome.events.Event<(details: T) => void> { - addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void; + addListener(callback: (details: T) => void, filters?: WebNavigationRequestFilter): void; } interface WebNavigationFramedEvent extends WebNavigationEvent {} @@ -7178,7 +7177,8 @@ declare namespace chrome.webRequest { */ types?: string[]; /** A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out. */ - urls: string[]; + urls: string[] | RegExp[] | ""; + /** Optional. */ windowId?: number; } @@ -7267,6 +7267,7 @@ declare namespace chrome.webRequest { interface WebResponseHeadersDetails extends WebResponseDetails { /** Optional. The HTTP response headers that have been received with this response. */ responseHeaders?: HttpHeader[]; + method: string; /** standard HTTP method i.e. GET, POST, PUT, etc. */ } interface WebResponseCacheDetails extends WebResponseHeadersDetails { diff --git a/chrome/test/index.ts b/chrome/test/index.ts index 7788397a4c..3074b8a0c3 100644 --- a/chrome/test/index.ts +++ b/chrome/test/index.ts @@ -171,6 +171,29 @@ function catBlock () { ["blocking"]); } +// webNavigation.onBeforeNavigate.addListener example similar api to onBeforeRequest but without extra spec +function beforeRedditNavigation() { + chrome.webNavigation.onBeforeNavigate.addListener(function (requestDetails) { + console.log("URL we want to redirect to: " + requestDetails.url); + // NOTE: This will search for top level frames with the value -1. + if (requestDetails.parentFrameId != -1) { + return; + } + + let url = new URL(requestDetails.url); + let splitUrl = url.hostname.split('.'); + //` Note: Does not cover the XX.co.uk type edge case + let host = (splitUrl[(splitUrl.length -1) - 1]); + + if (host === null) { + return; + } else if (host === "reddit") { + alert("Were you trying to go on reddit, during working hours? :(") + return; + } + },{urls: ["http://*/*"], types: ["image"]}); +} + // contrived settings example function proxySettings() { chrome.proxy.settings.get({ incognito: true }, (details) => { diff --git a/chunked-dc/chunked-dc-tests.ts b/chunked-dc/chunked-dc-tests.ts index 8e1ee9f00f..1bedf11c5a 100644 --- a/chunked-dc/chunked-dc-tests.ts +++ b/chunked-dc/chunked-dc-tests.ts @@ -1,11 +1,11 @@ // Chunker -let chunker = new Chunker(1337, Uint8Array.of(1,2,3), 2); -for (let chunk of chunker) { +let chunker = new Chunker(1337, Uint8Array.of(1, 2, 3), 2); +for (const chunk of chunker) { // Do smoething with chunk } while (chunker.hasNext) { - let chunk = chunker.next().value; + const chunk = chunker.next().value; } // Unchunker @@ -14,6 +14,6 @@ let unchunker = new Unchunker(); unchunker.onMessage = (message: Uint8Array, context: any[]) => { // Do something with the received message }; -let chunk = Uint8Array.of(1,2).buffer; +let chunk = Uint8Array.of(1, 2).buffer; unchunker.add(chunk); unchunker.gc(1024); diff --git a/chunked-dc/index.d.ts b/chunked-dc/index.d.ts index 2b38bef438..ab3acd6901 100644 --- a/chunked-dc/index.d.ts +++ b/chunked-dc/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chunked-dc v0.1.2 +// Type definitions for chunked-dc 0.1 // Project: https://github.com/saltyrtc/chunked-dc-js // Definitions by: Danilo Bargen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,7 @@ declare namespace chunkedDc { } interface ChunkerStatic { - new(id: number, message: Uint8Array, chunkSize: number): Chunker + new(id: number, message: Uint8Array, chunkSize: number): Chunker; } /** unchunker.ts **/ @@ -35,14 +35,14 @@ declare namespace chunkedDc { } interface UnchunkerStatic { - new(): Unchunker + new(): Unchunker; } /** main.ts **/ interface Standalone { - Chunker: ChunkerStatic, - Unchunker: UnchunkerStatic, + Chunker: ChunkerStatic; + Unchunker: UnchunkerStatic; } } diff --git a/chunked-dc/tsconfig.json b/chunked-dc/tsconfig.json index 0adf199b05..55832d5160 100644 --- a/chunked-dc/tsconfig.json +++ b/chunked-dc/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/chunked-dc/tslint.json b/chunked-dc/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/chunked-dc/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/clipboard/clipboard-tests.ts b/clipboard/clipboard-tests.ts index 7521c651dd..5af2671671 100644 --- a/clipboard/clipboard-tests.ts +++ b/clipboard/clipboard-tests.ts @@ -17,12 +17,12 @@ var cb5 = new Clipboard('.btn', { cb1.destroy(); -cb2.on('success', function(e) { +cb2.on('success', e => { console.info('Action:', e.action); console.info('Text:', e.text); console.info('Trigger:', e.trigger); e.clearSelection(); }); -cb2.on('error', function(e) { }); +cb2.on('error', e => { }); diff --git a/clndr/clndr-tests.ts b/clndr/clndr-tests.ts index ca904f13b2..018d9a6000 100644 --- a/clndr/clndr-tests.ts +++ b/clndr/clndr-tests.ts @@ -1,6 +1,6 @@ import * as Clndr from 'clndr'; -let options: Clndr.ClndrOptions = { +const options: Clndr.ClndrOptions = { template: '', startWithMonth: "YYYY-MM-DD", weekOffset: 0, @@ -25,21 +25,21 @@ let options: Clndr.ClndrOptions = { adjacentMonth: "adjacent-month", }, clickEvents: { - click: function (target) { }, - today: function (month) { }, - nextMonth: function (month) { }, - previousMonth: function (month) { }, - onMonthChange: function (month) { }, - nextYear: function (month) { }, - previousYear: function (month) { }, - onYearChange: function (month) { }, - nextInterval: function (start, end) { }, - previousInterval: function (start, end) { }, - onIntervalChange: function (start, end) { } + click(target) { }, + today(month) { }, + nextMonth(month) { }, + previousMonth(month) { }, + onMonthChange(month) { }, + nextYear(month) { }, + previousYear(month) { }, + onYearChange(month) { }, + nextInterval(start, end) { }, + previousInterval(start, end) { }, + onIntervalChange(start, end) { } }, useTouchEvents: false, - ready: function () { }, - doneRendering: function () { }, + ready() { }, + doneRendering() { }, events: [], dateParameter: 'date', multiDayEvents: { @@ -59,7 +59,7 @@ let options: Clndr.ClndrOptions = { interval: 1 }, extras: { }, - render: function (data) { + render(data) { return '
'; }, constraints: { @@ -69,7 +69,13 @@ let options: Clndr.ClndrOptions = { moment: null }; -let myCalendar = $('.parent-element').clndr(options); +const myCalendar = $('.parent-element').clndr(options); + +myCalendar.options.constraints = { + startDate: '2017-12-22', + endDate: '2018-01-09' +}; +myCalendar.render(); myCalendar .forward() @@ -82,5 +88,5 @@ myCalendar .today() .setEvents([]) .addEvents([]) - .removeEvents(event => { return event.id === 'idToRemove'; }) + .removeEvents(event => event.id === 'idToRemove') .destroy(); \ No newline at end of file diff --git a/clndr/index.d.ts b/clndr/index.d.ts index 12d84a6088..3e9fbbb09c 100644 --- a/clndr/index.d.ts +++ b/clndr/index.d.ts @@ -13,6 +13,10 @@ export as namespace Clndr; * The clndr instance */ export interface ClndrInstance { + /** + * Get clndr options + */ + options: ClndrOptions; /** * Go to the next month */ @@ -55,6 +59,10 @@ export interface ClndrInstance { * calendar. */ removeEvents(filter: (event: any) => boolean): this; + /** + * Re-render of the calendar. + */ + render(): void; /** * Destroy the clndr instance. This will empty the DOM node containing the * calendar. diff --git a/co-views/co-views-tests.ts b/co-views/co-views-tests.ts index ec5f53ae7c..35f12bbe99 100644 --- a/co-views/co-views-tests.ts +++ b/co-views/co-views-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as views from 'co-views'; const render = views('views', { @@ -15,7 +12,6 @@ const locals = {}; // template locals data async function test() { const html = await render(fileName, locals); - console.log(html); } // or use generator diff --git a/co-views/index.d.ts b/co-views/index.d.ts index f5b8c3d3e0..5df2238c12 100644 --- a/co-views/index.d.ts +++ b/co-views/index.d.ts @@ -1,50 +1,44 @@ -// Type definitions for co-views v2.1 +// Type definitions for co-views 2.1 // Project: https://github.com/tj/co-views/ // Definitions by: devlee , Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CoViews { - - /** - * Pass views `dir` and `opts` to return a render function. - */ - export interface Views { - (dir?: string, opts?: CoViewsOptions): { (view: string, locals?: Object): any } - } - - export interface CoViewsOptions { + export interface Options { + /** + * default extname + */ + ext?: string; /** * default extname */ - ext?: string, - - /** - * default extname - */ - default?: string, + default?: string; /** * engine map */ - map?: Object, + map?: Object; /** * proxy partials */ - partials?: Object, + partials?: Object; /** * cache compiled templates */ - cache?: boolean, + cache?: boolean; /** * common locals data */ - locals?: Object + locals?: Object; } } -declare var CoViews: CoViews.Views; +/** + * Pass views `dir` and `opts` to return a render function. + */ +declare function CoViews(dir?: string, opts?: CoViews.Options): (view: string, locals?: Object) => any; export = CoViews; diff --git a/co-views/tsconfig.json b/co-views/tsconfig.json index a3aec989e0..5a319edbcf 100644 --- a/co-views/tsconfig.json +++ b/co-views/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/co-views/tslint.json b/co-views/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/co-views/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/code/code-tests.ts b/code/code-tests.ts index f90d2c9eb7..c3455577d9 100644 --- a/code/code-tests.ts +++ b/code/code-tests.ts @@ -16,7 +16,7 @@ expect([1, 2, 3]).to.part.include([1, 4]); expect(10, "Age").to.be.above(5); -const func = function () { return arguments; }; +const func = function() { return arguments; }; expect(func()).to.be.arguments(); expect([1, 2]).to.be.an.array(); @@ -136,8 +136,7 @@ class CustomError extends Error { call: (message: string) => Error; } -const throws = function () { - +const throws = () => { throw new CustomError("Oh no!"); }; diff --git a/code/tslint.json b/code/tslint.json index 192203ab54..377cc837d4 100644 --- a/code/tslint.json +++ b/code/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/codemirror/codemirror-showhint.d.ts b/codemirror/codemirror-showhint.d.ts index 72c34b6007..55a3d6012b 100644 --- a/codemirror/codemirror-showhint.d.ts +++ b/codemirror/codemirror-showhint.d.ts @@ -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?: (doc: CodeMirror.Doc) => Hints, options?: ShowHintOptions): void; + function showHint(cm: CodeMirror.Doc, hinter?: HintFunction, options?: ShowHintOptions): void; interface Hints { from: Position; @@ -47,9 +47,18 @@ declare module "codemirror" { showHint: (options: ShowHintOptions) => void; } + interface HintFunction { + (doc: CodeMirror.Doc): Hints; + } + + interface AsyncHintFunction { + (doc: CodeMirror.Doc, callback: (hints: Hints) => any): any; + async?: boolean; + } + interface ShowHintOptions { completeSingle: boolean; - hint: (doc: CodeMirror.Doc) => Hints; + hint: HintFunction | AsyncHintFunction; } /** The Handle used to interact with the autocomplete dialog box.*/ diff --git a/codemirror/index.d.ts b/codemirror/index.d.ts index 4af27f5f12..d0b2dd6511 100644 --- a/codemirror/index.d.ts +++ b/codemirror/index.d.ts @@ -118,6 +118,8 @@ declare namespace CodeMirror { The other arguments and the returned value have the same interpretation as they have in findPosH. */ findPosV(start: CodeMirror.Position, amount: number, unit: string): { line: number; ch: number; hitSide?: boolean; }; + /** Returns the start and end of the 'word' (the stretch of letters, whitespace, or punctuation) at the given position. */ + findWordAt(pos: CodeMirror.Position): CodeMirror.Range; /** Change the configuration of the editor. option should the name of an option, and value should be a valid value for that option. */ setOption(option: string, value: any): void; @@ -672,9 +674,11 @@ declare namespace CodeMirror { (line: number, ch?: number): Position; } - interface Range{ - from: CodeMirror.Position; - to: CodeMirror.Position; + interface Range { + anchor: CodeMirror.Position; + head: CodeMirror.Position; + from(): CodeMirror.Position; + to(): CodeMirror.Position; } interface Position { diff --git a/codemirror/test/index.ts b/codemirror/test/index.ts index b46604b1bb..41b7170fd1 100644 --- a/codemirror/test/index.ts +++ b/codemirror/test/index.ts @@ -7,6 +7,12 @@ var myCodeMirror2: CodeMirror.Editor = CodeMirror(document.body, { mode: "javascript" }); +var range = myCodeMirror2.findWordAt(CodeMirror.Pos(0, 2)); +var anchor = range.anchor; +var head = range.head; +var from = range.from(); +var to = range.to(); + var myTextArea: HTMLTextAreaElement; var myCodeMirror3: CodeMirror.Editor = CodeMirror(function (elt) { myTextArea.parentNode.replaceChild(elt, myTextArea); diff --git a/codemirror/test/showhint.ts b/codemirror/test/showhint.ts index 59521ed440..00dbe6bed4 100644 --- a/codemirror/test/showhint.ts +++ b/codemirror/test/showhint.ts @@ -31,3 +31,17 @@ CodeMirror.showHint(doc, function (cm) { to: pos }; }); +var asyncHintFunc : CodeMirror.AsyncHintFunction = + (doc: CodeMirror.Doc, callback: (hints: CodeMirror.Hints) => any) => { + callback({ + from: pos, + list: ["one", "two"], + to: pos + }); + }; +asyncHintFunc.async = true; + +doc.showHint({ + completeSingle: false, + hint: asyncHintFunc +}) diff --git a/codependency/codependency-tests.ts b/codependency/codependency-tests.ts index 46f2db8d6d..e0f8a793a6 100644 --- a/codependency/codependency-tests.ts +++ b/codependency/codependency-tests.ts @@ -1,6 +1,3 @@ -/// -/// - let requirePeer = codependency.register(module), package: any; requirePeer = codependency.register(module, {index: ["dependencies", "devDependencies"]}); requirePeer = codependency.get("some-middleware"); diff --git a/codependency/tslint.json b/codependency/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/codependency/tslint.json +++ b/codependency/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/coinstring/coinstring-tests.ts b/coinstring/coinstring-tests.ts index ad1312d652..ab11a44fb7 100644 --- a/coinstring/coinstring-tests.ts +++ b/coinstring/coinstring-tests.ts @@ -1,69 +1,69 @@ /// -import cs = require('coinstring') +import cs = require('coinstring'); -var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd" -var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex') -var version = 0x80; //Bitcoin private key +var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; +var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); +var version = 0x80; // Bitcoin private key -console.log(cs.encode(privateKeyHexBuf, version)) +console.log(cs.encode(privateKeyHexBuf, version)); // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed -var hash160Buf = new Buffer(hash160, 'hex') -var version = 0x00; //Bitcoin public address +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed +var hash160Buf = new Buffer(hash160, 'hex'); +var version = 0x00; // Bitcoin public address console.log(cs.encode(hash160Buf, version)); // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS -var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd" +var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; -//for compressed, append "01" -privateKeyHex += '01' +// for compressed, append "01" +privateKeyHex += '01'; -var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex') -var version = 0x80 //Bitcoin private key +var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); +var version = 0x80; // Bitcoin private key -console.log(cs.encode(privateKeyHexBuf, version)) +console.log(cs.encode(privateKeyHexBuf, version)); // => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5auC2qc3 -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed -var hash160Buf = new Buffer(hash160, 'hex') -var version = 0x1E //Dogecoin public address +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed +var hash160Buf = new Buffer(hash160, 'hex'); +var version = 0x1E; // Dogecoin public address -console.log(cs.encode(hash160Buf, version)) +console.log(cs.encode(hash160Buf, version)); // => DAcq9oJpZZAjr56RmF7Y5zmWboZWQ4HAsW -var data = "000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35" -var buffer = new Buffer(data, 'hex') -var versionBuffer = new Buffer('0488ade4', 'hex') //0488ade4 is a consant listed in the aforementioned bip32 wiki. +var data = "000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35"; +var buffer = new Buffer(data, 'hex'); +var versionBuffer = new Buffer('0488ade4', 'hex'); // 0488ade4 is a consant listed in the aforementioned bip32 wiki. -console.log(cs.encode(buffer, versionBuffer)) +console.log(cs.encode(buffer, versionBuffer)); // => xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; -var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex') -var version = 0x80 //Bitcoin private key +var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); +var version = 0x80; // Bitcoin private key -var toBtcWif = cs.createEncoder(version) +var toBtcWif = cs.createEncoder(version); -//later in your program -console.log(toBtcWif(privateKeyHexBuf)) +// later in your program +console.log(toBtcWif(privateKeyHexBuf)); // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD -var wif = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD" -var version = 0x80 //Bitcoin private key +var wif = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD"; +var version = 0x80; // Bitcoin private key -var fromBtcWif = cs.createDecoder(version) +var fromBtcWif = cs.createDecoder(version); -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8" //hash representing uncompressed -var hash160Buf = new Buffer(hash160, 'hex') -var version = 0x6F //Bitcoin Testnet Address +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed +var hash160Buf = new Buffer(hash160, 'hex'); +var version = 0x6F; // Bitcoin Testnet Address -var testnetAddressValidator = cs.createValidator(version) -console.log(testnetAddressValidator("mkzgubTA5Ahi6BPSkE6MN9pEafRutznkMe")) // => true \ No newline at end of file +var testnetAddressValidator = cs.createValidator(version); +console.log(testnetAddressValidator("mkzgubTA5Ahi6BPSkE6MN9pEafRutznkMe")); // => true \ No newline at end of file diff --git a/colors/tslint.json b/colors/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/colors/tslint.json +++ b/colors/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/comment-json/comment-json-tests.ts b/comment-json/comment-json-tests.ts new file mode 100644 index 0000000000..af91ff422f --- /dev/null +++ b/comment-json/comment-json-tests.ts @@ -0,0 +1,16 @@ +import * as commentJson from 'comment-json'; + +const result = commentJson.parse(` +/** + block comment at the top + */ +// comment at the top +{ + // comment for a + // comment line 2 for a + /* block comment */ + "a": 1 // comment at right +} +// comment at the bottom +`); +const str = commentJson.stringify(result); diff --git a/comment-json/index.d.ts b/comment-json/index.d.ts new file mode 100644 index 0000000000..9c2652f34e --- /dev/null +++ b/comment-json/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for comment-json 1.1 +// Project: https://github.com/kaelzhang/node-comment-json +// Definitions by: Jason Dent +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Reviver = (k: number | string, v: any) => any; +export function parse(json: string, reviver?: Reviver, removes_comments?: boolean): any; +export function stringify(value: any, replacer?: any, space?: string | number): string; diff --git a/comment-json/tsconfig.json b/comment-json/tsconfig.json new file mode 100644 index 0000000000..314e9c0143 --- /dev/null +++ b/comment-json/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", + "comment-json-tests.ts" + ] +} \ No newline at end of file diff --git a/comment-json/tslint.json b/comment-json/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/comment-json/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/concat-stream/concat-stream-tests.ts b/concat-stream/concat-stream-tests.ts index 6dac3129f0..4f3bf839e0 100644 --- a/concat-stream/concat-stream-tests.ts +++ b/concat-stream/concat-stream-tests.ts @@ -1,4 +1,4 @@ -import concat = require("concat-stream") +import concat = require("concat-stream"); import { Readable } from "stream"; @@ -14,7 +14,7 @@ class MyReadable extends Readable { } } -let myReadable = new MyReadable(); +const myReadable = new MyReadable(); myReadable.pipe(concat((buf) => console.log(buf.toString()))); myReadable.pipe(concat({}, (buf) => console.log(buf.toString()))); diff --git a/conf/tsconfig.json b/conf/tsconfig.json index 8bb74358fa..8ef2367ca4 100644 --- a/conf/tsconfig.json +++ b/conf/tsconfig.json @@ -5,6 +5,7 @@ "es6", "dom" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, diff --git a/config/config-tests.ts b/config/config-tests.ts index 1dab917d84..507ecc463c 100644 --- a/config/config-tests.ts +++ b/config/config-tests.ts @@ -29,3 +29,8 @@ var hidden1: any = config.util.makeHidden({}, ""); var hidden2: any = config.util.makeHidden({}, "", ""); var env: string = config.util.getEnv(""); + +var configSources: config.IConfigSource[] = config.util.getConfigSources(); +var configSource: config.IConfigSource = configSources[0]; +var configSourceName: string = configSource.name; +var configSourceOriginal: string | undefined = configSource.original; diff --git a/config/index.d.ts b/config/index.d.ts index 98dda3448a..2f7ee3eaf1 100644 --- a/config/index.d.ts +++ b/config/index.d.ts @@ -34,6 +34,9 @@ declare namespace c { // Return the config for the project based on directory param if not directory then return default one (config). loadFileConfigs(configDir: string): any; + + // Return the sources for the configurations + getConfigSources(): IConfigSource[]; } interface IConfig { @@ -41,6 +44,12 @@ declare namespace c { has(setting: string): boolean; util: IUtil; } + + interface IConfigSource { + name: string; + original?: string; + parsed: any; + } } export = c; diff --git a/configstore/configstore-tests.ts b/configstore/configstore-tests.ts index 0d8e777fe0..724dbe9a38 100644 --- a/configstore/configstore-tests.ts +++ b/configstore/configstore-tests.ts @@ -6,7 +6,7 @@ var value: any; var key: string; var num: number; var bool: any; -var object:Object; +var object: any; cs.set(key, value); value = cs.get(key); diff --git a/configstore/tslint.json b/configstore/tslint.json index f9e30021f4..377cc837d4 100644 --- a/configstore/tslint.json +++ b/configstore/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/connect-ensure-login/tslint.json b/connect-ensure-login/tslint.json index f9e30021f4..377cc837d4 100644 --- a/connect-ensure-login/tslint.json +++ b/connect-ensure-login/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/consul/index.d.ts b/consul/index.d.ts index b154eeccb3..4d577cd2a1 100644 --- a/consul/index.d.ts +++ b/consul/index.d.ts @@ -951,10 +951,14 @@ declare namespace Consul { } namespace Watch { + + interface WatchOptions { + key?: string; + } interface Options { method: Function; - options?: CommonOptions; + options?: CommonOptions & WatchOptions; } } diff --git a/convert-source-map/convert-source-map-tests.ts b/convert-source-map/convert-source-map-tests.ts index 1a6df7df10..96a638ca93 100644 --- a/convert-source-map/convert-source-map-tests.ts +++ b/convert-source-map/convert-source-map-tests.ts @@ -1,6 +1,7 @@ - import convert = require("convert-source-map"); +// tslint:disable:max-line-length + var json = convert .fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') .toJSON(); diff --git a/convert-source-map/tslint.json b/convert-source-map/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/convert-source-map/tslint.json +++ b/convert-source-map/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/cookie-signature/cookie-signature-tests.ts b/cookie-signature/cookie-signature-tests.ts new file mode 100644 index 0000000000..f76d6dcb59 --- /dev/null +++ b/cookie-signature/cookie-signature-tests.ts @@ -0,0 +1,7 @@ +import * as cookie from "cookie-signature"; + +let val = cookie.sign('hello', 'tobiiscool'); + +val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool'); +cookie.unsign(val, 'luna'); diff --git a/cookie-signature/index.d.ts b/cookie-signature/index.d.ts new file mode 100644 index 0000000000..b9b29911a6 --- /dev/null +++ b/cookie-signature/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for cookie-signature 1.0 +// Project: https://github.com/tj/node-cookie-signature +// Definitions by: François Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Sign the given `val` with `secret`. + * @param {string} val + * @param {string} secret + * @return {string} + */ +export function sign(value: string, secret: string): string; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * @param {string} val + * @param {string} secret + * @return {string|boolean} + */ +export function unsign(value: string, secret: string): string | boolean; diff --git a/cookie-signature/tsconfig.json b/cookie-signature/tsconfig.json new file mode 100644 index 0000000000..57344e816a --- /dev/null +++ b/cookie-signature/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", + "cookie-signature-tests.ts" + ] +} diff --git a/cookie-signature/tslint.json b/cookie-signature/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/cookie-signature/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/cookies/cookies-tests.ts b/cookies/cookies-tests.ts index 21e81b49de..30e07d3000 100644 --- a/cookies/cookies-tests.ts +++ b/cookies/cookies-tests.ts @@ -7,29 +7,29 @@ const server = http.createServer((req, res) => { const cookies = new Cookies(req, res); let unsigned: string, signed: string, - tampered: string + tampered: string; - if (req.url == "/set") { + if (req.url === "/set") { cookies // set a regular cookie .set("unsigned", "foo", { httpOnly: false }) - - // set a signed cookie - .set("signed", "bar", { signed: true }) - - // mimic a signed cookie, but with a bogus signature - .set("tampered", "baz") - .set("tampered.sig", "bogus") - res.writeHead(302, { "Location": "/" }) - return res.end("Now let's check.") + // set a signed cookie + .set("signed", "bar", { signed: true }) + + // mimic a signed cookie, but with a bogus signature + .set("tampered", "baz") + .set("tampered.sig", "bogus"); + + res.writeHead(302, { Location: "/" }); + return res.end("Now let's check."); } - unsigned = cookies.get("unsigned") - signed = cookies.get("signed", { signed: true }) - tampered = cookies.get("tampered", { signed: true }) + unsigned = cookies.get("unsigned"); + signed = cookies.get("signed", { signed: true }); + tampered = cookies.get("tampered", { signed: true }); - res.writeHead(200, { "Content-Type": "text/plain" }) + res.writeHead(200, { "Content-Type": "text/plain" }); res.end( "unsigned expected: foo\n\n" + "unsigned actual: " + unsigned + "\n\n" + @@ -37,5 +37,5 @@ const server = http.createServer((req, res) => { "signed actual: " + signed + "\n\n" + "tampered expected: undefined\n\n" + "tampered: " + tampered + "\n\n" - ) -}) \ No newline at end of file + ); +}); \ No newline at end of file diff --git a/cordova-plugin-app-version/tsconfig.json b/cordova-plugin-app-version/tsconfig.json index 935b5b77de..1c9f396113 100644 --- a/cordova-plugin-app-version/tsconfig.json +++ b/cordova-plugin-app-version/tsconfig.json @@ -1,23 +1,23 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "cordova-plugin-app-version-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-app-version-tests.ts" + ] } \ No newline at end of file diff --git a/cordova-plugin-device-name/README.md b/cordova-plugin-device-name/README.md new file mode 100644 index 0000000000..6826b06c32 --- /dev/null +++ b/cordova-plugin-device-name/README.md @@ -0,0 +1,8 @@ +# Installation +> `npm install --save @types/cordova-plugin-device-name` + +# Summary +This package contains type definitions for cordova-plugin-device-name (https://www.npmjs.com/package/cordova-plugin-device-name) + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/cordova-plugin-device-name diff --git a/cordova-plugin-device-name/cordova-plugin-device-name-tests.ts b/cordova-plugin-device-name/cordova-plugin-device-name-tests.ts new file mode 100644 index 0000000000..c101f14d97 --- /dev/null +++ b/cordova-plugin-device-name/cordova-plugin-device-name-tests.ts @@ -0,0 +1,4 @@ +/// + +var deviceName = cordova.plugins.deviceName; +console.log(deviceName.name) // e.g: Becvert's iPad diff --git a/cordova-plugin-device-name/index.d.ts b/cordova-plugin-device-name/index.d.ts new file mode 100644 index 0000000000..479f443cfd --- /dev/null +++ b/cordova-plugin-device-name/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for cordova-plugin-device-name v1.1.0 +// Project: https://www.npmjs.com/package/cordova-plugin-device-name +// Definitions by: Larry Bahr +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// +// Licensed under the MIT license. + +interface CordovaPlugins { + /** + * cordova-plugin-device-name interface + */ + deviceName: CordovaPluginDeviceName.CordovaPluginDeviceName; +} + +/** + * Keep the type global namespace clean by using a module + */ +declare module CordovaPluginDeviceName { + interface CordovaPluginDeviceName { + /** + * User-friendly name of the device. + * @example cordova.plugins.deviceName.name // e.g: Larry's Android + */ + name: string; + } +} \ No newline at end of file diff --git a/axios/tsconfig.json b/cordova-plugin-device-name/tsconfig.json similarity index 90% rename from axios/tsconfig.json rename to cordova-plugin-device-name/tsconfig.json index 4300cfb925..5012f628be 100644 --- a/axios/tsconfig.json +++ b/cordova-plugin-device-name/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "axios-tests.ts" + "cordova-plugin-device-name-tests.ts" ] } \ No newline at end of file diff --git a/cordova-plugin-inappbrowser/index.d.ts b/cordova-plugin-inappbrowser/index.d.ts index d5e221ba42..ea3d3adba8 100644 --- a/cordova-plugin-inappbrowser/index.d.ts +++ b/cordova-plugin-inappbrowser/index.d.ts @@ -168,6 +168,8 @@ interface InAppBrowser extends Window { removeEventListener(type: string, callback: (event: Event) => void): void; /** Closes the InAppBrowser window. */ close(): void; + /** Hides the InAppBrowser window. Calling this has no effect if the InAppBrowser was already hidden. */ + hide(): void; /** * Displays an InAppBrowser window that was opened hidden. Calling this has no effect * if the InAppBrowser was already visible. diff --git a/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts b/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts index 31c334afca..bb5a768bf8 100644 --- a/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts +++ b/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts @@ -1,5 +1,3 @@ -/// - // examples taken from https://github.com/litehelpers/Cordova-sqlite-storage function echoTestFunction() { function successCallback(value: string) { @@ -33,26 +31,26 @@ function openingDatabase() { } function openingDatabase2() { - window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, function(db) { - db.transaction(function(tx) { + window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, db => { + db.transaction(tx => { // ... - }, function(err) { + }, err => { console.log('Open database ERROR: ' + JSON.stringify(err)); }); }); } function singleStatementTransactions(db: SQLitePlugin.Database) { - db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function (resultSet) { + db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], resultSet => { console.log('resultSet.insertId: ' + resultSet.insertId); console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected); - }, function(error) { + }, error => { console.log('SELECT error: ' + error.message); }); - db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (resultSet) { + db.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], resultSet => { console.log('got stringlength: ' + resultSet.rows.item(0).stringlength); - }, function(error) { + }, error => { console.log('SELECT error: ' + error.message); }); } @@ -62,40 +60,40 @@ function sqlBatchTransactions(db: SQLitePlugin.Database) { 'DROP TABLE IF EXISTS MyTable', 'CREATE TABLE MyTable (SampleColumn)', [ 'INSERT INTO MyTable VALUES (?)', ['test-value'] ], - ], function() { - db.executeSql('SELECT * FROM MyTable', [], function (resultSet) { + ], () => { + db.executeSql('SELECT * FROM MyTable', [], resultSet => { console.log('Sample column value: ' + resultSet.rows.item(0).SampleColumn); }); - }, function(error) { + }, error => { console.log('Populate table error: ' + error.message); }); } function asynchronousTransaction(db: SQLitePlugin.Database) { - db.transaction(function(tx) { + db.transaction(tx => { tx.executeSql('DROP TABLE IF EXISTS MyTable'); tx.executeSql('CREATE TABLE MyTable (SampleColumn)'); - tx.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function(tx, resultSet) { + tx.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], (tx, resultSet) => { console.log('resultSet.insertId: ' + resultSet.insertId); console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected); - }, function(tx, error) { + }, (tx, error) => { console.log('INSERT error: ' + error.message); }); - }, function(error) { + }, error => { console.log('transaction error: ' + error.message); - }, function() { + }, () => { console.log('transaction ok'); }); - db.readTransaction(function(tx) { - tx.executeSql("SELECT UPPER('Some US-ASCII text') AS uppertext", [], function(tx, resultSet) { + db.readTransaction(tx => { + tx.executeSql("SELECT UPPER('Some US-ASCII text') AS uppertext", [], (tx, resultSet) => { console.log("resultSet.rows.item(0).uppertext: " + resultSet.rows.item(0).uppertext); - }, function(tx, error) { + }, (tx, error) => { console.log('SELECT error: ' + error.message); }); - }, function(error) { + }, error => { console.log('transaction error: ' + error.message); - }, function() { + }, () => { console.log('transaction ok'); }); } @@ -108,28 +106,28 @@ function sampleWithPRAGMA() { function onDeviceReady() { var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}); - db.transaction(function(tx) { + db.transaction(tx => { tx.executeSql('DROP TABLE IF EXISTS test_table'); tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)'); // demonstrate PRAGMA: - db.executeSql("pragma table_info (test_table);", [], function(res) { + db.executeSql("pragma table_info (test_table);", [], res => { console.log("PRAGMA res: " + JSON.stringify(res)); }); - tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) { + tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => { console.log("insertId: " + res.insertId + " -- probably 1"); console.log("rowsAffected: " + res.rowsAffected + " -- should be 1"); - db.transaction(function(tx) { - tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) { + db.transaction(tx => { + tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => { console.log("res.rows.length: " + res.rows.length + " -- should be 1"); console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1"); }); }); // }, function(e) { // probably example in https://github.com/litehelpers/Cordova-sqlite-storage is broken - }, function(_tx, e) { + }, (_tx, e) => { console.log("ERROR: " + e.message); }); }); @@ -145,20 +143,20 @@ function sampleWithTransactionLevelNesting() { function onDeviceReady() { var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}); - db.transaction(function(tx) { + db.transaction(tx => { tx.executeSql('DROP TABLE IF EXISTS test_table'); tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)'); - tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) { + tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => { console.log("insertId: " + res.insertId + " -- probably 1"); console.log("rowsAffected: " + res.rowsAffected + " -- should be 1"); - tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) { + tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => { console.log("res.rows.length: " + res.rows.length + " -- should be 1"); console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1"); }); - }, function(tx, e) { + }, (tx, e) => { console.log("ERROR: " + e.message); }); }); @@ -177,18 +175,18 @@ function dbClose(db: SQLitePlugin.Database) { db.close(successcb, errorcb); - db.transaction(function (tx) { - tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], function (tx, res) { + db.transaction(tx => { + tx.executeSql("SELECT LENGTH('tenletters') AS stringlength", [], (tx, res) => { console.log('got stringlength: ' + res.rows.item(0).stringlength); }); - }, function (error) { + }, error => { // OK to close here: console.log('transaction error: ' + error.message); db.close(); - }, function () { + }, () => { // OK to close here: console.log('transaction ok'); - db.close(function () { + db.close(() => { console.log('database is closed ok'); }); }); @@ -207,11 +205,11 @@ function deleteDatabase() { function quickInstallationTest() { - window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, function (db) { - db.executeSql("select length('tenletters') as stringlength", [], function (res) { + window.sqlitePlugin.openDatabase({ name: 'hello-world.db', location: 'default' }, db => { + db.executeSql("select length('tenletters') as stringlength", [], res => { var stringlength = res.rows.item(0).stringlength; console.log('got stringlength: ' + stringlength); - //document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength; + // document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength; }); }); } diff --git a/cordova-sqlite-storage/tslint.json b/cordova-sqlite-storage/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/cordova-sqlite-storage/tslint.json +++ b/cordova-sqlite-storage/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts b/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts index 29451c4753..35c1e03d58 100644 --- a/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts +++ b/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts @@ -529,4 +529,56 @@ cordova.plugins.diagnostic.requestAndCheckMotionAuthorization(function(status){ console.log("Motion authorization is " +status); }, function(error){ console.error(error); +}); + +cordova.plugins.diagnostic.isExternalStorageAuthorized(function(authorized){ + console.log("Location authorization is " + (authorized ? "authorized" : "unauthorized")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getExternalStorageAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("External storage authorization allowed"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestExternalStorageAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("External storage authorization allowed"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.getExternalSdCardDetails(function(details){ + console.log("External SD card details: " + JSON.stringify(details)); +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isNFCPresent(function(present){ + console.log("NFC hardware is " + (present ? "present" : "absent")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isNFCEnabled(function(enabled){ + console.log("NFC is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isNFCAvailable(function(available){ + console.log("NFC is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.registerNFCStateChangeHandler(function(state){ + if(state === cordova.plugins.diagnostic.NFCState.POWERED_ON){ + console.log("NFC is ready to use"); + } }); \ No newline at end of file diff --git a/cordova.plugins.diagnostic/index.d.ts b/cordova.plugins.diagnostic/index.d.ts index 381b61562e..5952b41851 100644 --- a/cordova.plugins.diagnostic/index.d.ts +++ b/cordova.plugins.diagnostic/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cordova.plugins.diagnostic v3.3.0 +// Type definitions for cordova.plugins.diagnostic v3.4.x // Project: https://github.com/dpa99c/cordova-diagnostic-plugin // Definitions by: Dave Alden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -56,6 +56,14 @@ interface Diagnostic { bluetoothState?: any; + /** + * ANDROID ONLY + * Constants for the various NFC power states. + * @type {Object} + */ + NFCState?: any; + + /** * Checks if app is able to access device location. * @param successCallback @@ -164,8 +172,8 @@ interface Diagnostic { /** * ANDROID and iOS ONLY - * Returns true if the device setting for location is on. - * On Android this returns true if Location Mode is switched on. + * Returns true if the device setting for location is on. + * On Android this returns true if Location Mode is switched on. * On iOS this returns true if Location Services is switched on. * @param successCallback * @param errorCallback @@ -567,6 +575,93 @@ interface Diagnostic { errorCallback: (error: string) => void ) => void; + /** + * ANDROID ONLY + * Checks if the application is authorized to use external storage. + * @param successCallback + * @param errorCallback + */ + isExternalStorageAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Returns the authorisation status for runtime permission to use the external storage. + * @param successCallback + * @param errorCallback + */ + getExternalStorageAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Requests authorisation for runtime permission to use the external storage. + * @param successCallback + * @param errorCallback + */ + requestExternalStorageAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Returns details of external SD card(s): absolute path, is writable, free space + * @param successCallback + * @param errorCallback + */ + getExternalSdCardDetails?: ( + successCallback: (status: any) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if NFC hardware is present on device. + * @param successCallback + * @param errorCallback + */ + isNFCPresent?: ( + successCallback: (present: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device setting for NFC is switched on. + * @param successCallback + * @param errorCallback + */ + isNFCEnabled?: ( + successCallback: (present: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if NFC is available to the app. + * @param successCallback + * @param errorCallback + */ + isNFCAvailable?: ( + successCallback: (present: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Registers a function to be called when a change in NFC state occurs. + * Pass in a falsey value to de-register the currently registered function. + * @param successCallback + */ + registerNFCStateChangeHandler?: ( + successCallback: (state: string) => void + ) => void; + /** * iOS ONLY * Checks if the application is authorized to use the Camera Roll in Photos app. diff --git a/cordova_app_version_plugin/README.md b/cordova_app_version_plugin/README.md new file mode 100644 index 0000000000..a12ccb5267 --- /dev/null +++ b/cordova_app_version_plugin/README.md @@ -0,0 +1,8 @@ +# Installation +> `npm install --save-dev @types/cordova_app_version_plugin` + +# Summary +This package contains type definitions for cordova_app_version_plugin (https://www.npmjs.com/package/cordova_app_version_plugin) + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/cordova_app_version_plugin diff --git a/cordova_app_version_plugin/cordova_app_version_plugin-tests.ts b/cordova_app_version_plugin/cordova_app_version_plugin-tests.ts new file mode 100644 index 0000000000..5e4eb16e66 --- /dev/null +++ b/cordova_app_version_plugin/cordova_app_version_plugin-tests.ts @@ -0,0 +1,3 @@ +/// + +var appVersion = window.cordova.plugins.version.getAppVersion(); // e.g. "1.5.0" diff --git a/cordova_app_version_plugin/index.d.ts b/cordova_app_version_plugin/index.d.ts new file mode 100644 index 0000000000..b8a70216a6 --- /dev/null +++ b/cordova_app_version_plugin/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for cordova_app_version_plugin v0.2.6 +// Project: https://www.npmjs.com/package/cordova_app_version_plugin +// Definitions by: Larry Bahr +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// +// Licensed under the MIT license. + +interface CordovaPlugins { + /** + * cordova_app_version_plugin interface + */ + version: CordovaAppVersionPlugin.CordovaAppVersionPlugin; +} + +/** + * Keep the type global namespace clean by using a module + */ +declare module CordovaAppVersionPlugin { + interface CordovaAppVersionPlugin { + /** + * App version from config.xml's version (e.g. ) + * @example window.cordova.plugins.version.getAppVersion() // e.g: "1.5.0" + */ + getAppVersion(): string; + } +} \ No newline at end of file diff --git a/cordova_app_version_plugin/tsconfig.json b/cordova_app_version_plugin/tsconfig.json new file mode 100644 index 0000000000..62f656037c --- /dev/null +++ b/cordova_app_version_plugin/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", + "cordova_app_version_plugin-tests.ts" + ] +} \ No newline at end of file diff --git a/core-decorators/core-decorators-tests.ts b/core-decorators/core-decorators-tests.ts index 86df21fc6d..04a22c19cf 100644 --- a/core-decorators/core-decorators-tests.ts +++ b/core-decorators/core-decorators-tests.ts @@ -17,8 +17,8 @@ class Person { } } -let person = new Person(); -let { getPerson, getPersonAgain } = person; +const person = new Person(); +const { getPerson, getPersonAgain } = person; getPerson() === person; @@ -81,7 +81,7 @@ class Person2 { facepalmHarder() {} } -let person2 = new Person2(); +const person2 = new Person2(); person2.facepalm(); // DEPRECATION Person#facepalm: This function will be removed in future versions. @@ -144,7 +144,7 @@ class Person3 { } } -let person3 = new Person3(); +const person3 = new Person3(); person3.facepalmWithoutWarning(); // no warning is logged @@ -242,7 +242,7 @@ editor.hugeBuffer; // already initialized and equals our buffer, so // createHugeBuffer() is not called again -//TODO: For @mixin, I don't know how we can make it work for TypeScript... +// TODO: For @mixin, I don't know how we can make it work for TypeScript... // // @mixin (alias: @mixins) // @@ -265,7 +265,7 @@ const FlyMixin = { @mixin(SingerMixin, FlyMixin) class Bird { singMatingCall() { - //TODO: For @mixin, I don't know how we can make it work for TypeScript... + // TODO: For @mixin, I don't know how we can make it work for TypeScript... // this.sing('tweet tweet'); } } @@ -280,10 +280,10 @@ bird.singMatingCall(); import { time } from 'core-decorators'; -let myConsole = { - time: function(label: string) { /* custom time() method */ }, - timeEnd: function(label: string) { /* custom timeEnd method */ }, - log: function(str: any) { /* custom log method */ } +const myConsole = { + time(label: string) { /* custom time() method */ }, + timeEnd(label: string) { /* custom timeEnd method */ }, + log(str: any) { /* custom log method */ } }; class Bird2 { diff --git a/core-decorators/index.d.ts b/core-decorators/index.d.ts index 18fcc95a27..d0a51009eb 100644 --- a/core-decorators/index.d.ts +++ b/core-decorators/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for core-decorators.js v0.10 +// Type definitions for core-decorators.js 0.10 // Project: https://github.com/jayphelps/core-decorators.js // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 export interface ClassDecorator { (target: TFunction): TFunction | void; diff --git a/core-decorators/tsconfig.json b/core-decorators/tsconfig.json index dee0784eed..1c0b389c96 100644 --- a/core-decorators/tsconfig.json +++ b/core-decorators/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/core-decorators/tslint.json b/core-decorators/tslint.json new file mode 100644 index 0000000000..0332a8383e --- /dev/null +++ b/core-decorators/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "forbidden-types": false + } +} diff --git a/crc/crc-tests.ts b/crc/crc-tests.ts index b279bc6fad..36f5c023b6 100644 --- a/crc/crc-tests.ts +++ b/crc/crc-tests.ts @@ -1,5 +1,5 @@ -import * as crc from "crc" -import * as fs from "fs" +import * as crc from "crc"; +import * as fs from "fs"; // tests move from the readme of the module diff --git a/credit-card-type/index.d.ts b/credit-card-type/index.d.ts index 59886b5e60..8625e5e5f8 100644 --- a/credit-card-type/index.d.ts +++ b/credit-card-type/index.d.ts @@ -10,7 +10,8 @@ declare namespace creditCardType { interface CreditCardTypeInfo { niceType?: string type?: CardBrand - pattern?: RegExp + prefixPattern?: RegExp + exactPattern?: RegExp gaps?: Array lengths?: Array code?: { diff --git a/cron/index.d.ts b/cron/index.d.ts index e962a9eb27..d4fa027c93 100644 --- a/cron/index.d.ts +++ b/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.0.9 +// Type definitions for cron 1.2 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,9 +6,9 @@ interface CronJobStatic { - new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob; + new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean): CronJob; new (options: { - cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any + cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any; runOnInit?: boolean }): CronJob; } interface CronJob { diff --git a/crypto-js/aes/index.d.ts b/crypto-js/aes/index.d.ts new file mode 100644 index 0000000000..4f435688c5 --- /dev/null +++ b/crypto-js/aes/index.d.ts @@ -0,0 +1,3 @@ +import { AES } from '../index'; + +export = AES; diff --git a/crypto-js/core/index.d.ts b/crypto-js/core/index.d.ts new file mode 100644 index 0000000000..c5d6e00410 --- /dev/null +++ b/crypto-js/core/index.d.ts @@ -0,0 +1,3 @@ +import * as Core from '../index'; + +export = Core; diff --git a/crypto-js/enc-base64/index.d.ts b/crypto-js/enc-base64/index.d.ts new file mode 100644 index 0000000000..55001a7115 --- /dev/null +++ b/crypto-js/enc-base64/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Base64: typeof enc.Base64; +export = Base64; diff --git a/crypto-js/enc-hex/index.d.ts b/crypto-js/enc-hex/index.d.ts new file mode 100644 index 0000000000..3718860123 --- /dev/null +++ b/crypto-js/enc-hex/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Hex: typeof enc.Hex; +export = Hex; diff --git a/crypto-js/enc-latin1/index.d.ts b/crypto-js/enc-latin1/index.d.ts new file mode 100644 index 0000000000..7f27822daf --- /dev/null +++ b/crypto-js/enc-latin1/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Latin1: typeof enc.Latin1; +export = Latin1; diff --git a/crypto-js/enc-utf16/index.d.ts b/crypto-js/enc-utf16/index.d.ts new file mode 100644 index 0000000000..76fa98774a --- /dev/null +++ b/crypto-js/enc-utf16/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Utf16: typeof enc.Utf16; +export = Utf16; diff --git a/crypto-js/enc-utf8/index.d.ts b/crypto-js/enc-utf8/index.d.ts new file mode 100644 index 0000000000..828dcb9391 --- /dev/null +++ b/crypto-js/enc-utf8/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Utf8: typeof enc.Utf8; +export = Utf8; diff --git a/crypto-js/evpkdf/index.d.ts b/crypto-js/evpkdf/index.d.ts new file mode 100644 index 0000000000..8946b9d3a1 --- /dev/null +++ b/crypto-js/evpkdf/index.d.ts @@ -0,0 +1,3 @@ +import { EvpKDF } from '../index'; + +export = EvpKDF; diff --git a/crypto-js/format-hex/index.d.ts b/crypto-js/format-hex/index.d.ts new file mode 100644 index 0000000000..1b0f573824 --- /dev/null +++ b/crypto-js/format-hex/index.d.ts @@ -0,0 +1,4 @@ +import { format } from '../index'; + +declare const Hex: typeof format.Hex; +export = Hex; diff --git a/crypto-js/format-openssl/index.d.ts b/crypto-js/format-openssl/index.d.ts new file mode 100644 index 0000000000..02c35a3688 --- /dev/null +++ b/crypto-js/format-openssl/index.d.ts @@ -0,0 +1,4 @@ +import { format } from '../index'; + +declare const OpenSSL: typeof format.OpenSSL; +export = OpenSSL; diff --git a/crypto-js/hmac-md5/index.d.ts b/crypto-js/hmac-md5/index.d.ts new file mode 100644 index 0000000000..7240576710 --- /dev/null +++ b/crypto-js/hmac-md5/index.d.ts @@ -0,0 +1,3 @@ +import { HmacMD5 } from '../index'; + +export = HmacMD5; diff --git a/crypto-js/hmac-ripemd160/index.d.ts b/crypto-js/hmac-ripemd160/index.d.ts new file mode 100644 index 0000000000..6c371e9435 --- /dev/null +++ b/crypto-js/hmac-ripemd160/index.d.ts @@ -0,0 +1,3 @@ +import { HmacRIPEMD160 } from '../index'; + +export = HmacRIPEMD160; diff --git a/crypto-js/hmac-sha1/index.d.ts b/crypto-js/hmac-sha1/index.d.ts new file mode 100644 index 0000000000..1995cf87f6 --- /dev/null +++ b/crypto-js/hmac-sha1/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA1 } from '../index'; + +export = HmacSHA1; diff --git a/crypto-js/hmac-sha224/index.d.ts b/crypto-js/hmac-sha224/index.d.ts new file mode 100644 index 0000000000..f25334c64c --- /dev/null +++ b/crypto-js/hmac-sha224/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA224 } from '../index'; + +export = HmacSHA224; diff --git a/crypto-js/hmac-sha256/index.d.ts b/crypto-js/hmac-sha256/index.d.ts new file mode 100644 index 0000000000..ca1a1ca267 --- /dev/null +++ b/crypto-js/hmac-sha256/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA256 } from '../index'; + +export = HmacSHA256; diff --git a/crypto-js/hmac-sha3/index.d.ts b/crypto-js/hmac-sha3/index.d.ts new file mode 100644 index 0000000000..0fa0db9321 --- /dev/null +++ b/crypto-js/hmac-sha3/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA3 } from '../index'; + +export = HmacSHA3; diff --git a/crypto-js/hmac-sha384/index.d.ts b/crypto-js/hmac-sha384/index.d.ts new file mode 100644 index 0000000000..2e17420c1b --- /dev/null +++ b/crypto-js/hmac-sha384/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA384 } from '../index'; + +export = HmacSHA384; diff --git a/crypto-js/hmac-sha512/index.d.ts b/crypto-js/hmac-sha512/index.d.ts new file mode 100644 index 0000000000..439b2ffd5e --- /dev/null +++ b/crypto-js/hmac-sha512/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA512 } from '../index'; + +export = HmacSHA512; diff --git a/crypto-js/index.d.ts b/crypto-js/index.d.ts index 5fdf193254..07a8d18dfc 100644 --- a/crypto-js/index.d.ts +++ b/crypto-js/index.d.ts @@ -114,4 +114,3 @@ declare namespace CryptoJS { }; } } - diff --git a/crypto-js/lib-typedarrays/index.d.ts b/crypto-js/lib-typedarrays/index.d.ts new file mode 100644 index 0000000000..761e38b1cd --- /dev/null +++ b/crypto-js/lib-typedarrays/index.d.ts @@ -0,0 +1,2 @@ +declare const LibTypedarrays: any; +export = LibTypedarrays; diff --git a/crypto-js/md5/index.d.ts b/crypto-js/md5/index.d.ts new file mode 100644 index 0000000000..faa064511e --- /dev/null +++ b/crypto-js/md5/index.d.ts @@ -0,0 +1,3 @@ +import { MD5 } from '../index'; + +export = MD5; diff --git a/crypto-js/mode-cfb/index.d.ts b/crypto-js/mode-cfb/index.d.ts new file mode 100644 index 0000000000..74c5c6e3d1 --- /dev/null +++ b/crypto-js/mode-cfb/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const CFB: typeof mode.CFB; +export = CFB; diff --git a/crypto-js/mode-ctr-gladman/index.d.ts b/crypto-js/mode-ctr-gladman/index.d.ts new file mode 100644 index 0000000000..3ca8f8b367 --- /dev/null +++ b/crypto-js/mode-ctr-gladman/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const CTRGladman: typeof mode.CTRGladman; +export = CTRGladman; diff --git a/crypto-js/mode-ctr/index.d.ts b/crypto-js/mode-ctr/index.d.ts new file mode 100644 index 0000000000..6007a4ca88 --- /dev/null +++ b/crypto-js/mode-ctr/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const CTR: typeof mode.CTR; +export = CTR; diff --git a/crypto-js/mode-ecb/index.d.ts b/crypto-js/mode-ecb/index.d.ts new file mode 100644 index 0000000000..569d2b2286 --- /dev/null +++ b/crypto-js/mode-ecb/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const ECB: typeof mode.ECB; +export = ECB; diff --git a/crypto-js/mode-ofb/index.d.ts b/crypto-js/mode-ofb/index.d.ts new file mode 100644 index 0000000000..484406979d --- /dev/null +++ b/crypto-js/mode-ofb/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const OFB: typeof mode.OFB; +export = OFB; diff --git a/crypto-js/pad-ansix923/index.d.ts b/crypto-js/pad-ansix923/index.d.ts new file mode 100644 index 0000000000..2bb6c2dffb --- /dev/null +++ b/crypto-js/pad-ansix923/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const AnsiX923: typeof pad.AnsiX923; +export = AnsiX923; diff --git a/crypto-js/pad-iso10126/index.d.ts b/crypto-js/pad-iso10126/index.d.ts new file mode 100644 index 0000000000..6e52e96197 --- /dev/null +++ b/crypto-js/pad-iso10126/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const Iso10126: typeof pad.Iso10126; +export = Iso10126; diff --git a/crypto-js/pad-iso97971/index.d.ts b/crypto-js/pad-iso97971/index.d.ts new file mode 100644 index 0000000000..0ab1cecbfb --- /dev/null +++ b/crypto-js/pad-iso97971/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const Iso97971: typeof pad.Iso97971; +export = Iso97971; diff --git a/crypto-js/pad-nopadding/index.d.ts b/crypto-js/pad-nopadding/index.d.ts new file mode 100644 index 0000000000..f71bb2de73 --- /dev/null +++ b/crypto-js/pad-nopadding/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const NoPadding: typeof pad.NoPadding; +export = NoPadding; diff --git a/crypto-js/pad-pkcs7/index.d.ts b/crypto-js/pad-pkcs7/index.d.ts new file mode 100644 index 0000000000..1b194673a2 --- /dev/null +++ b/crypto-js/pad-pkcs7/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const Pkcs7: typeof pad.Pkcs7; +export = Pkcs7; diff --git a/crypto-js/pad-zeropadding/index.d.ts b/crypto-js/pad-zeropadding/index.d.ts new file mode 100644 index 0000000000..cf481402ab --- /dev/null +++ b/crypto-js/pad-zeropadding/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const ZeroPadding: typeof pad.ZeroPadding; +export = ZeroPadding; diff --git a/crypto-js/pbkdf2/index.d.ts b/crypto-js/pbkdf2/index.d.ts new file mode 100644 index 0000000000..e242e6fe05 --- /dev/null +++ b/crypto-js/pbkdf2/index.d.ts @@ -0,0 +1,3 @@ +import { PBKDF2 } from '../index'; + +export = PBKDF2; diff --git a/crypto-js/rabbit-legacy/index.d.ts b/crypto-js/rabbit-legacy/index.d.ts new file mode 100644 index 0000000000..6befe37563 --- /dev/null +++ b/crypto-js/rabbit-legacy/index.d.ts @@ -0,0 +1,3 @@ +import { RabbitLegacy } from '../index'; + +export = RabbitLegacy; diff --git a/crypto-js/rabbit/index.d.ts b/crypto-js/rabbit/index.d.ts new file mode 100644 index 0000000000..f708a6f20b --- /dev/null +++ b/crypto-js/rabbit/index.d.ts @@ -0,0 +1,3 @@ +import { Rabbit } from '../index'; + +export = Rabbit; diff --git a/crypto-js/rc4/index.d.ts b/crypto-js/rc4/index.d.ts new file mode 100644 index 0000000000..38a929f490 --- /dev/null +++ b/crypto-js/rc4/index.d.ts @@ -0,0 +1,3 @@ +import { RC4 } from '../index'; + +export = RC4; diff --git a/crypto-js/ripemd160/index.d.ts b/crypto-js/ripemd160/index.d.ts new file mode 100644 index 0000000000..90e3e770ce --- /dev/null +++ b/crypto-js/ripemd160/index.d.ts @@ -0,0 +1,3 @@ +import { RIPEMD160 } from '../index'; + +export = RIPEMD160; diff --git a/crypto-js/sha1/index.d.ts b/crypto-js/sha1/index.d.ts new file mode 100644 index 0000000000..14fb4d2a6b --- /dev/null +++ b/crypto-js/sha1/index.d.ts @@ -0,0 +1,3 @@ +import { SHA1 } from '../index'; + +export = SHA1; diff --git a/crypto-js/sha224/index.d.ts b/crypto-js/sha224/index.d.ts new file mode 100644 index 0000000000..3ff1ff4596 --- /dev/null +++ b/crypto-js/sha224/index.d.ts @@ -0,0 +1,3 @@ +import { SHA224 } from '../index'; + +export = SHA224; diff --git a/crypto-js/sha256/index.d.ts b/crypto-js/sha256/index.d.ts new file mode 100644 index 0000000000..59781b01f3 --- /dev/null +++ b/crypto-js/sha256/index.d.ts @@ -0,0 +1,3 @@ +import { SHA256 } from '../index'; + +export = SHA256; diff --git a/crypto-js/sha3/index.d.ts b/crypto-js/sha3/index.d.ts new file mode 100644 index 0000000000..241574a711 --- /dev/null +++ b/crypto-js/sha3/index.d.ts @@ -0,0 +1,3 @@ +import { SHA3 } from '../index'; + +export = SHA3; diff --git a/crypto-js/sha384/index.d.ts b/crypto-js/sha384/index.d.ts new file mode 100644 index 0000000000..5bad55498a --- /dev/null +++ b/crypto-js/sha384/index.d.ts @@ -0,0 +1,3 @@ +import { SHA384 } from '../index'; + +export = SHA384; diff --git a/crypto-js/sha512/index.d.ts b/crypto-js/sha512/index.d.ts new file mode 100644 index 0000000000..0f764329e2 --- /dev/null +++ b/crypto-js/sha512/index.d.ts @@ -0,0 +1,3 @@ +import { SHA512 } from '../index'; + +export = SHA512; diff --git a/crypto-js/test/submodule-tests.ts b/crypto-js/test/submodule-tests.ts new file mode 100644 index 0000000000..0cfd8cd83f --- /dev/null +++ b/crypto-js/test/submodule-tests.ts @@ -0,0 +1,184 @@ +import Core = require('../core'); +import X64Core = require('../x64-core'); +import LibTypedarrays = require('../lib-typedarrays'); +// --- +import MD5 = require('../md5'); +import SHA1 = require('../sha1'); +import SHA256 = require('../sha256'); +import SHA224 = require('../sha224'); +import SHA512 = require('../sha512'); +import SHA384 = require('../sha384'); +import SHA3 = require('../sha3'); +import RIPEMD160 = require('../ripemd160'); +// --- +import HmacMD5 = require('../hmac-md5'); +import HmacSHA1 = require('../hmac-sha1'); +import HmacSHA256 = require('../hmac-sha256'); +import HmacSHA224 = require('../hmac-sha224'); +import HmacSHA512 = require('../hmac-sha512'); +import HmacSHA384 = require('../hmac-sha384'); +import HmacSHA3 = require('../hmac-sha3'); +import HmacRIPEMD160 = require('../hmac-ripemd160'); +// --- +import PBKDF2 = require('../pbkdf2'); +// --- +import AES = require('../aes'); +import TripleDES = require('../tripledes'); +import RC4 = require('../rc4'); +import Rabbit = require('../rabbit'); +import RabbitLegacy = require('../rabbit-legacy'); +import EvpKDF = require('../evpkdf'); +// --- +import FormatOpenSSL = require('../format-openssl'); +import FormatHex = require('../format-hex'); +// --- +import EncLatin1 = require('../enc-latin1'); +import EncUtf8 = require('../enc-utf8'); +import EncHex = require('../enc-hex'); +import EncUtf16 = require('../enc-utf16'); +import EncBase64 = require('../enc-base64'); +// --- +import ModeCFB = require('../mode-cfb'); +import ModeCTR = require('../mode-ctr'); +import ModeCTRGladman = require('../mode-ctr-gladman'); +import ModeOFB = require('../mode-ofb'); +import ModeECB = require('../mode-ecb'); +// --- +import PadPkcs7 = require('../pad-pkcs7'); +import PadAnsiX923 = require('../pad-ansix923'); +import PadIso10126 = require('../pad-iso10126'); +import PadIso97971 = require('../pad-iso97971'); +import PadZeroPadding = require('../pad-zeropadding'); +import PadNoPadding = require('../pad-nopadding'); + +// Hashers +var str: string; +str = MD5('some message'); +str = MD5('some message', 'some key'); + +str = SHA1('some message'); +str = SHA1('some message', 'some key', { any: true }); + +str = FormatOpenSSL('some message'); +str = FormatOpenSSL('some message', 'some key'); + + +// Ciphers +var encrypted: CryptoJS.WordArray; +var decrypted: CryptoJS.DecryptedMessage; + +encrypted = AES.encrypt("Message", "Secret Passphrase"); +decrypted = AES.decrypt(encrypted, "Secret Passphrase"); + +encrypted = Core.DES.encrypt("Message", "Secret Passphrase"); +decrypted = Core.DES.decrypt(encrypted, "Secret Passphrase"); + +encrypted = TripleDES.encrypt("Message", "Secret Passphrase"); +decrypted = TripleDES.decrypt(encrypted, "Secret Passphrase"); + + +encrypted = Rabbit.encrypt("Message", "Secret Passphrase"); +decrypted = Rabbit.decrypt(encrypted, "Secret Passphrase"); + +encrypted = RC4.encrypt("Message", "Secret Passphrase"); +decrypted = RC4.decrypt(encrypted, "Secret Passphrase"); + +encrypted = Core.RC4Drop.encrypt("Message", "Secret Passphrase"); +encrypted = Core.RC4Drop.encrypt("Message", "Secret Passphrase", { drop: 3072 / 4 }); +decrypted = Core.RC4Drop.decrypt(encrypted, "Secret Passphrase", { drop: 3072 / 4 }); + +var key = EncHex.parse('000102030405060708090a0b0c0d0e0f'); +var iv = EncHex.parse('101112131415161718191a1b1c1d1e1f'); +encrypted = AES.encrypt("Message", key, { iv: iv }); + +encrypted = AES.encrypt("Message", "Secret Passphrase", { + mode: ModeCFB, + padding: PadAnsiX923 +}); + + +// The Cipher Output +encrypted = AES.encrypt("Message", "Secret Passphrase"); +alert(encrypted.key); +// 74eb593087a982e2a6f5dded54ecd96d1fd0f3d44a58728cdcd40c55227522223 +alert(encrypted.iv); +// 7781157e2629b094f0e3dd48c4d786115 +alert(encrypted.salt); +// 7a25f9132ec6a8b34 +alert(encrypted.ciphertext); +// 73e54154a15d1beeb509d9e12f1e462a0 +alert(encrypted); +// U2FsdGVkX1+iX5Ey7GqLND5UFUoV0b7rUJ2eEvHkYqA= + +var JsonFormatter = { + stringify: function(cipherParams: any) { + // create json object with ciphertext + var jsonObj: any = { + ct: cipherParams.ciphertext.toString(EncBase64) + }; + // optionally add iv and salt + if (cipherParams.iv) { + jsonObj.iv = cipherParams.iv.toString(); + } + if (cipherParams.salt) { + jsonObj.s = cipherParams.salt.toString(); + } + // stringify json object + return JSON.stringify(jsonObj); + }, + parse: function (jsonStr: any) { + // parse json string + var jsonObj = JSON.parse(jsonStr); + // extract ciphertext from json object, and create cipher params object + var cipherParams = (Core).lib.CipherParams.create({ + ciphertext: EncBase64.parse(jsonObj.ct) + }); + // optionally extract iv and salt + if (jsonObj.iv) { + cipherParams.iv = EncHex.parse(jsonObj.iv); + } + if (jsonObj.s) { + cipherParams.salt = EncHex.parse(jsonObj.s); + } return cipherParams; + } +}; +encrypted = AES.encrypt("Message", "Secret Passphrase", { + format: JsonFormatter +}); +alert(encrypted); +// {"ct":"tZ4MsEnfbcDOwqau68aOrQ==","iv":"8a8c8fd8fe33743d3638737ea4a00698","s":"ba06373c8f57179c"} +decrypted = AES.decrypt(encrypted, "Secret Passphrase", { + format: JsonFormatter +}); +alert(decrypted.toString(EncUtf8)); // Message + + +// Progressive Ciphering +var key = EncHex.parse('000102030405060708090a0b0c0d0e0f'); +var iv = EncHex.parse('101112131415161718191a1b1c1d1e1f'); +var aesEncryptor = Core.algo.AES.createEncryptor(key, { iv: iv }); +var ciphertextPart1 = aesEncryptor.process("Message Part 1"); +var ciphertextPart2 = aesEncryptor.process("Message Part 2"); +var ciphertextPart3 = aesEncryptor.process("Message Part 3"); +var ciphertextPart4 = aesEncryptor.finalize(); +var aesDecryptor = Core.algo.AES.createDecryptor(key, { iv: iv }); +var plaintextPart1 = aesDecryptor.process(ciphertextPart1); +var plaintextPart2 = aesDecryptor.process(ciphertextPart2); +var plaintextPart3 = aesDecryptor.process(ciphertextPart3); +var plaintextPart4 = aesDecryptor.process(ciphertextPart4); +var plaintextPart5 = aesDecryptor.finalize(); + + +// Encoders +var words = EncBase64.parse('SGVsbG8sIFdvcmxkIQ=='); +var base64 = EncBase64.stringify(words); +var words = EncLatin1.parse('Hello, World!'); +var latin1 = EncLatin1.stringify(words); +var words = EncHex.parse('48656c6c6f2c20576f726c6421'); +var hex = EncHex.stringify(words); +var words = EncUtf8.parse('𤭢'); +var utf8 = EncUtf8.stringify(words); +var words = EncUtf16.parse('Hello, World!'); +var utf16 = EncUtf16.stringify(words); +var words = Core.enc.Utf16LE.parse('Hello, World!'); +var utf16 = Core.enc.Utf16LE.stringify(words); diff --git a/crypto-js/tripledes/index.d.ts b/crypto-js/tripledes/index.d.ts new file mode 100644 index 0000000000..ea22173d98 --- /dev/null +++ b/crypto-js/tripledes/index.d.ts @@ -0,0 +1,3 @@ +import { TripleDES } from '../index'; + +export = TripleDES; diff --git a/crypto-js/tsconfig.json b/crypto-js/tsconfig.json index 94793c83ae..10865613d3 100644 --- a/crypto-js/tsconfig.json +++ b/crypto-js/tsconfig.json @@ -18,6 +18,51 @@ }, "files": [ "index.d.ts", - "crypto-js-tests.ts" + "crypto-js-tests.ts", + "test/submodule-tests.ts", + "core/index.d.ts", + "x64-core/index.d.ts", + "lib-typedarrays/index.d.ts", + "md5/index.d.ts", + "sha1/index.d.ts", + "sha256/index.d.ts", + "sha224/index.d.ts", + "sha512/index.d.ts", + "sha384/index.d.ts", + "sha3/index.d.ts", + "ripemd160/index.d.ts", + "hmac-md5/index.d.ts", + "hmac-sha1/index.d.ts", + "hmac-sha256/index.d.ts", + "hmac-sha224/index.d.ts", + "hmac-sha512/index.d.ts", + "hmac-sha384/index.d.ts", + "hmac-sha3/index.d.ts", + "hmac-ripemd160/index.d.ts", + "pbkdf2/index.d.ts", + "aes/index.d.ts", + "tripledes/index.d.ts", + "rc4/index.d.ts", + "rabbit/index.d.ts", + "rabbit-legacy/index.d.ts", + "evpkdf/index.d.ts", + "format-openssl/index.d.ts", + "format-hex/index.d.ts", + "enc-latin1/index.d.ts", + "enc-utf8/index.d.ts", + "enc-hex/index.d.ts", + "enc-utf16/index.d.ts", + "enc-base64/index.d.ts", + "mode-cfb/index.d.ts", + "mode-ctr/index.d.ts", + "mode-ctr-gladman/index.d.ts", + "mode-ofb/index.d.ts", + "mode-ecb/index.d.ts", + "pad-pkcs7/index.d.ts", + "pad-ansix923/index.d.ts", + "pad-iso10126/index.d.ts", + "pad-iso97971/index.d.ts", + "pad-zeropadding/index.d.ts", + "pad-nopadding/index.d.ts" ] -} \ No newline at end of file +} diff --git a/crypto-js/x64-core/index.d.ts b/crypto-js/x64-core/index.d.ts new file mode 100644 index 0000000000..1ef7a67477 --- /dev/null +++ b/crypto-js/x64-core/index.d.ts @@ -0,0 +1,3 @@ +import * as X64Core from '../index'; + +export = X64Core; diff --git a/cryptojs/test/sha1-tests.ts b/cryptojs/test/sha1-tests.ts index 50dfe1992b..fa05f3289d 100644 --- a/cryptojs/test/sha1-tests.ts +++ b/cryptojs/test/sha1-tests.ts @@ -31,7 +31,7 @@ YUI.add('algo-sha1-test', function (Y) { Y.Assert.areEqual('761c457bf73b14d27e9e9265c46f4b4dda11f940', C.SHA1('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789').toString()); }, - testVector7: function () { + testVector7() { Y.Assert.areEqual('50abf5706a150990a08b2c5ea40fa0e585554732', C.SHA1('12345678901234567890123456789012345678901234567890123456789012345678901234567890').toString()); }, diff --git a/csv-stringify/csv-stringify-tests.ts b/csv-stringify/csv-stringify-tests.ts index 7ffd1f6e3e..bd6873affb 100644 --- a/csv-stringify/csv-stringify-tests.ts +++ b/csv-stringify/csv-stringify-tests.ts @@ -19,6 +19,6 @@ stream = stringify({ delimiter: "," }); stream.write(["1", "2", "3"]); -let transform: NodeJS.ReadWriteStream = stream; +const transform: NodeJS.ReadWriteStream = stream; stream = stringify(); diff --git a/csv-stringify/index.d.ts b/csv-stringify/index.d.ts index fcf3321319..e65695c059 100644 --- a/csv-stringify/index.d.ts +++ b/csv-stringify/index.d.ts @@ -8,7 +8,9 @@ declare namespace stringify { interface StringifyOpts { /** - * List of fields, applied when transform returns an object, order matters, read the transformer documentation for additionnal information, columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line. + * List of fields, applied when transform returns an object. + * Order matters, read the transformer documentation for additionnal information, + * columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line. */ columns?: string[]; /** @@ -28,7 +30,8 @@ declare namespace stringify { */ header?: boolean; /** - * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). + * String used to delimit record rows or a special value; + * special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). */ lineBreaks?: string; /** @@ -48,7 +51,8 @@ declare namespace stringify { */ quotedString?: boolean; /** - * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). + * String used to delimit record rows or a special value; + * special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). */ rowDelimiter?: string; diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index dd92ee7c19..87089671ae 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -9,6 +9,12 @@ function StepSample() { var step = this; var hook = this; + hook.setWorldConstructor(function() { + this.visit = function(url: string, callback: Callback) { + callback(null, 'pending'); + } + }) + hook.Before(function(scenario: HookScenario, callback: Callback){ scenario.isFailed() && callback.pending(); }); diff --git a/cucumber/index.d.ts b/cucumber/index.d.ts index 154e6707cc..a8b85539ce 100644 --- a/cucumber/index.d.ts +++ b/cucumber/index.d.ts @@ -69,6 +69,7 @@ declare namespace cucumber { After(code: HookCode): void; Around(code: AroundCode):void; setDefaultTimeout(time:number): void; + setWorldConstructor(world: () => void): void; registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void; registerListener(listener: EventListener): void; } @@ -207,7 +208,7 @@ declare namespace cucumber { } export interface SupportCodeConsumer { - (stepDefinitions:StepDefinitions | Hooks):void; + (stepDefinitions:StepDefinitions & Hooks):void; } export function defineSupportCode(consumer:SupportCodeConsumer): void; diff --git a/d3-array/d3-array-tests.ts b/d3-array/d3-array-tests.ts index 26ef2d3ef5..74b749bea3 100644 --- a/d3-array/d3-array-tests.ts +++ b/d3-array/d3-array-tests.ts @@ -15,23 +15,22 @@ import { timeYear } from 'd3-time'; // ----------------------------------------------------------------------------- class NumCoercible { - public a: number; + a: number; constructor(a: number) { this.a = a; } - public valueOf() { + valueOf() { return this.a; } } - class MixedObject { - public num: number; - public str: string; - public numeric: NumCoercible; - public date: Date; + num: number; + str: string; + numeric: NumCoercible; + date: Date; constructor(a: number, date: Date) { this.num = a; @@ -40,29 +39,58 @@ class MixedObject { this.date = date; } } + let num: number; -let str: string; -let numeric: NumCoercible; let date: Date; -let extentNum: [number, number]; -let extentStr: [string, string]; -let extentNumeric: [NumCoercible, NumCoercible]; -let extentDateMixed: [d3Array.Primitive, d3Array.Primitive]; -let extentMixed: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible]; -let extentDate: [Date, Date]; + +let numOrUndefined: number | undefined; +let strOrUndefined: string | undefined; +let numericOrUndefined: NumCoercible | undefined; +let dateOrUndefined: Date | undefined; +let numOrUndefinedExtent: [number, number] | [undefined, undefined]; +let strOrUndefinedExtent: [string, string] | [undefined, undefined]; +let numericOrUndefinedExtent: [NumCoercible, NumCoercible] | [undefined, undefined]; +let dateMixedOrUndefined: [Date , Date] | [undefined, undefined]; +let mixedOrUndefinedExtent: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible] | [undefined, undefined]; +let dateOrUndefinedExtent: [Date, Date] | [undefined, undefined]; let numbersArray = [10, 20, 30, 40, 50]; -let stringyNumbersArray = ['10', '20', '30', '40', '50']; -let numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; -let dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; -let mixedObjectArray = [ +const numbersOrUndefinedArray = [10, 20, undefined, null, 40, 50]; +const stringyNumbersArray = ['10', '20', '30', '40', '50']; +const numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; +const dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; +const mixedObjectArray = [ new MixedObject(10, new Date(2016, 6, 1)), new MixedObject(20, new Date(2016, 7, 30)), new MixedObject(30, new Date(2015, 3, 15)), new MixedObject(40, new Date(2014, 3, 15)), new MixedObject(50, new Date(2017, 4, 15)) ]; +const mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined]; +function accessorMixedObjectToNum(datum: MixedObject, index: number, array: MixedObject[]): number { + return datum.num; +} + +function accessorMixedObjectToStr(datum: MixedObject, index: number, array: MixedObject[]): string { + return datum.str; +} + +function accessorMixedObjectToNumeric(datum: MixedObject, index: number, array: MixedObject[]): NumCoercible { + return datum.numeric; +} + +function accessorMixedObjectToDate(datum: MixedObject, index: number, array: MixedObject[]): Date { + return datum.date; +} + +function accessorMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: Array): number | undefined | null { + return datum ? datum.num : undefined; +} + +function accessorMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: MixedObject[]): string | undefined | null { + return datum ? datum.str : undefined; +} // ----------------------------------------------------------------------------- // Test Statistics @@ -72,186 +100,109 @@ let mixedObjectArray = [ // without accessors -num = d3Array.max(numbersArray); -str = d3Array.max(stringyNumbersArray); -numeric = d3Array.max(numericArray); -date = d3Array.max(dateArray); +numOrUndefined = d3Array.max(numbersArray); +strOrUndefined = d3Array.max(stringyNumbersArray); +numericOrUndefined = d3Array.max(numericArray); +dateOrUndefined = d3Array.max(dateArray); // with accessors -num = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); - -str = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.str; -}); - -numeric = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.numeric; -}); - -date = d3Array.max(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.date; -}); +numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStr); +numericOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumeric); +dateOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStrOrUndefined); // min() ----------------------------------------------------------------------- // without accessors -num = d3Array.min(numbersArray); -str = d3Array.min(stringyNumbersArray); -numeric = d3Array.min(numericArray); -date = d3Array.min(dateArray); +numOrUndefined = d3Array.min(numbersArray); +strOrUndefined = d3Array.min(stringyNumbersArray); +numericOrUndefined = d3Array.min(numericArray); +dateOrUndefined = d3Array.min(dateArray); // with accessors -num = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); - -str = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.str; -}); - -numeric = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.numeric; -}); - -date = d3Array.min(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.date; -}); +numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStr); +numericOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumeric); +dateOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStrOrUndefined); // extent() -------------------------------------------------------------------- // without accessors -extentNum = d3Array.extent(numbersArray); -extentStr = d3Array.extent(stringyNumbersArray); -extentNumeric = d3Array.extent(numericArray); -extentDate = d3Array.extent(dateArray); -extentMixed = d3Array.extent([new NumCoercible(10), 13, '12', true]); +numOrUndefinedExtent = d3Array.extent(numbersArray); +strOrUndefinedExtent = d3Array.extent(stringyNumbersArray); +numericOrUndefinedExtent = d3Array.extent(numericArray); +dateOrUndefinedExtent = d3Array.extent(dateArray); // with accessors -extentNum = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); - -extentStr = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.str; -}); - -extentMixed = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.numeric; -}); - -extentDateMixed = d3Array.extent(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.date; -}); +numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStr); +mixedOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumeric); +dateMixedOrUndefined = d3Array.extent(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStrOrUndefined); // mean() ---------------------------------------------------------------------- -num = d3Array.mean(numbersArray); +numOrUndefined = d3Array.mean(numbersArray); +numOrUndefined = d3Array.mean(numericArray); +numOrUndefined = d3Array.mean(numbersOrUndefinedArray); -num = d3Array.mean(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.mean(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.mean(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // median() -------------------------------------------------------------------- -num = d3Array.median(numbersArray); +numOrUndefined = d3Array.median(numbersArray); +numOrUndefined = d3Array.median(numericArray); +numOrUndefined = d3Array.median(numbersOrUndefinedArray); -num = d3Array.median(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.median(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.median(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // quantile() ------------------------------------------------------------------ -num = d3Array.quantile(numbersArray, 0.5); +numOrUndefined = d3Array.quantile(numbersArray, 0.5); +numOrUndefined = d3Array.quantile(numericArray, 0.5); +numOrUndefined = d3Array.quantile(numbersOrUndefinedArray, 0.5); -num = d3Array.quantile(mixedObjectArray, 0.5, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.quantile(mixedObjectArray, 0.5, accessorMixedObjectToNum); +numOrUndefined = d3Array.quantile(mixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined); // sum() ----------------------------------------------------------------------- +numOrUndefined = d3Array.sum(numbersArray); +numOrUndefined = d3Array.sum(numericArray); +numOrUndefined = d3Array.sum(numbersOrUndefinedArray); -num = d3Array.sum(numbersArray); - -num = d3Array.sum(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.sum(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.sum(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // deviation() ----------------------------------------------------------------- -num = d3Array.deviation(numbersArray); +numOrUndefined = d3Array.deviation(numbersArray); +numOrUndefined = d3Array.deviation(numericArray); +numOrUndefined = d3Array.deviation(numbersOrUndefinedArray); -num = d3Array.deviation(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.deviation(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.deviation(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // variance() ------------------------------------------------------------------ -num = d3Array.variance(numbersArray); +numOrUndefined = d3Array.variance(numbersArray); +numOrUndefined = d3Array.variance(numericArray); +numOrUndefined = d3Array.variance(numbersOrUndefinedArray); -num = d3Array.variance(mixedObjectArray, function (datum, index, array) { - let d: MixedObject = datum; - let i: number = index; - let arr: Array = array; - return datum.num; -}); +numOrUndefined = d3Array.variance(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.variance(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // ----------------------------------------------------------------------------- // Test Searching Arrays @@ -259,8 +210,18 @@ num = d3Array.variance(mixedObjectArray, function (datum, index, array) { // scan() ---------------------------------------------------------------------- -num = d3Array.scan(mixedObjectArray, function (a, b) { - return a.num - b.num; // a and b are of type MixedObject +numOrUndefined = d3Array.scan(numbersArray); + +numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => { + const aElem: MixedObject = a; + const bElem: MixedObject = b; + return a.num - b.num; +}); + +numOrUndefined = d3Array.scan(mixedObjectOrUndefinedArray, (a, b) => { + const aElem: MixedObject | undefined = a; + const bElem: MixedObject | undefined = b; + return a && b ? a.num - b.num : NaN; }); // bisectLeft() ---------------------------------------------------------------- @@ -307,19 +268,16 @@ num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, // bisector() ------------------------------------------------------------------ -mixedObjectArray.sort(function (a, b) { return a.date.valueOf() - b.date.valueOf(); }); +mixedObjectArray.sort((a, b) => a.date.valueOf() - b.date.valueOf()); let mixedObjectDateBisectorObject: d3Array.Bisector; // define using accessor -mixedObjectDateBisectorObject = d3Array.bisector(function (el) { - return el.date; -}); +mixedObjectDateBisectorObject = d3Array.bisector(el => el.date); // define using comparator -mixedObjectDateBisectorObject = d3Array.bisector(function (el, x) { - return el.date.valueOf() - x.valueOf(); -}); +mixedObjectDateBisectorObject = d3Array.bisector((el, x) => + el.date.valueOf() - x.valueOf()); // bisect left num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14)); @@ -334,12 +292,14 @@ num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14 // ascending() ----------------------------------------------------------------- +num = d3Array.ascending(undefined, 20); num = d3Array.ascending(10, 20); num = d3Array.ascending('10', '20'); num = d3Array.ascending(new Date(2016, 6, 13), new Date(2016, 6, 14)); // descending() ---------------------------------------------------------------- +num = d3Array.descending(undefined, 20); num = d3Array.descending(10, 20); num = d3Array.descending('10', '20'); num = d3Array.descending(new Date(2016, 6, 13), new Date(2016, 6, 14)); @@ -364,12 +324,11 @@ let testArrays: MixedObject[][] = [ ] ]; - let mergedArray: MixedObject[]; mergedArray = d3Array.merge(testArrays); // inferred type mergedArray = d3Array.merge(testArrays); // explicit type -// mergedArray = d3.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch +// mergedArray = d3Array.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch // pairs() --------------------------------------------------------------------- @@ -384,14 +343,14 @@ mergedArray = d3Array.permute(mergedArray, [1, 0, 2, 5, 3, 4, 6]); // Getting an ordered array with object properties -let testObject = { +const testObject = { val: 10, name: 'Test', when: new Date(), more: [10, 30, 40] }; -let x: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); +const x: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); // range() --------------------------------------------------------------------- @@ -450,7 +409,7 @@ testArrays = d3Array.zip( // Test Histogram // ----------------------------------------------------------------------------- -let tScale = scaleTime(); +const tScale = scaleTime(); // Create histogram generator ================================================== @@ -464,10 +423,10 @@ testHistogram = d3Array.histogram(); // value(...) ------------------------------------------------------------------ -testHistogram = testHistogram.value(function (d, i, data) { - let datum: MixedObject = d; // d is of type MixedObject - let index: number = i; // i is number - let array: MixedObject[] = data; // data is of type MixedObject[] +testHistogram = testHistogram.value((d, i, data) => { + const datum: MixedObject = d; // d is of type MixedObject + const index: number = i; // i is number + const array: MixedObject[] = data; // data is of type MixedObject[] return datum.date; }); @@ -480,16 +439,14 @@ valueAccessorFn = testHistogram.value(); testHistogram = testHistogram.domain([new Date(2014, 3, 15), new Date(2017, 4, 15)]); // usage with scale domain: -let domain = tScale.domain(); +const domain = tScale.domain(); testHistogram = testHistogram.domain([domain[0], domain[domain.length]]); // testHistogram = testHistogram.domain(tScale.domain()); // fails, as scale domain is an array with possibly more than the two elements expected by histogram // use with accessor function -testHistogram = testHistogram.domain(function (values) { - return [values[0], values[values.length]]; -}); +testHistogram = testHistogram.domain(values => [values[0], values[values.length]]); // get current domain accessor function let domainAccessorFn: (values: Date[]) => [Date, Date]; @@ -508,7 +465,7 @@ defaultHistogram = defaultHistogram.thresholds(d3Array.thresholdScott); testHistogram = testHistogram.thresholds([new Date(2015, 11, 15), new Date(2016, 6, 1), new Date(2016, 8, 30)]); // with thresholds value array accessors -testHistogram = testHistogram.thresholds(function (values: Date[], min: Date, max: Date) { +testHistogram = testHistogram.thresholds((values: Date[], min: Date, max: Date) => { let thresholds: Date[]; thresholds = [values[0], values[2], values[4]]; return thresholds; @@ -536,7 +493,7 @@ let testBin: d3Array.Bin; testBin = testBins[0]; num = testBin.length; // defaultBin is array -let mixedObject: MixedObject = testBin[0]; // with element type MixedObject +const mixedObject: MixedObject = testBin[0]; // with element type MixedObject date = testBin.x0; // bin lower bound is Date date = testBin.x1; // bin upper bound is Date diff --git a/d3-array/index.d.ts b/d3-array/index.d.ts index e3bd2d549d..336eb2bc83 100644 --- a/d3-array/index.d.ts +++ b/d3-array/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for D3JS d3-array module v1.0.1 +// Type definitions for D3JS d3-array module 1.0 // Project: https://github.com/d3/d3-array // Definitions by: Alex Ford , Boris Yankov , Tom Wanzek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last module patch version validated against: 1.0.2 + // -------------------------------------------------------------------------- // Shared Types and Interfaces // -------------------------------------------------------------------------- @@ -20,17 +22,11 @@ interface Numeric { valueOf(): number; } - // -------------------------------------------------------------------------------------- // Descriptive Statistics // -------------------------------------------------------------------------------------- -/** - * Return the maximum value in the array of numbers using natural order. - */ -export function max(array: number[]): number | undefined; - /** * Return the maximum value in the array of strings using natural order. */ @@ -41,25 +37,15 @@ export function max(array: string[]): string | undefined; */ export function max(array: T[]): T | undefined; -/** - * Return the maximum value in the array using natural order and a projection function to map values to numbers. - */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; - /** * Return the maximum value in the array using natural order and a projection function to map values to strings. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => string): string | undefined; +export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => U): U | undefined; - -/** - * Return the minimum value in the array using natural order. - */ -export function min(array: number[]): number | undefined; +export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; /** * Return the minimum value in the array using natural order. @@ -74,25 +60,15 @@ export function min(array: T[]): T | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => string): string | undefined; - -/** - * Return the minimum value in the array using natural order. - */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => U): U | undefined; +export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; -/** - * Return the min and max simultaneously. - */ -export function extent(array: number[]): [number, number] | [undefined, undefined]; - /** * Return the min and max simultaneously. */ @@ -106,79 +82,70 @@ export function extent(array: T[]): [T, T] | [undefined, unde /** * Return the min and max simultaneously. */ -export function extent(array: Array): [T | Primitive, T | Primitive] | [undefined, undefined]; +export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => number): [number, number] | [undefined, undefined]; - -/** - * Return the min and max simultaneously. - */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => string): [string, string] | [undefined, undefined]; - -/** - * Return the min and max simultaneously. - */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => U): [U, U ] | [undefined, undefined]; +export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): [U, U] | [undefined, undefined]; /** * Return the mean of an array of numbers */ -export function mean(array: number[]): number | undefined; -export function mean(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function mean(array: Array): number | undefined; +export function mean(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; /** * Return the median of an array of numbers */ -export function median(array: number[]): number | undefined; -export function median(array: T[], accessor: (element: T, i: number, array: T[]) => number): number | undefined; +export function median(array: Array): number | undefined; +export function median(array: T[], accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; /** * Returns the p-quantile of an array of numbers */ -export function quantile(array: number[], p: number): number | undefined; -export function quantile(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number): number | undefined; +export function quantile(array: Array, p: number): number | undefined; +export function quantile(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; /** * Compute the sum of an array of numbers. */ -export function sum(array: number[]): number; +export function sum(array: Array): number; /** * Compute the sum of an array, using the given accessor to convert values to numbers. */ -export function sum(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number; +export function sum(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers. */ -export function deviation(array: number[]): number | undefined; +export function deviation(array: Array): number | undefined; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array, * using the given accessor to convert values to numbers. */ -export function deviation(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function deviation(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array of numbers. */ -export function variance(array: number[]): number | undefined; +export function variance(array: Array): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array, * using the given accessor to convert values to numbers. */ -export function variance(array: T[], accessor: (datum: T, index: number, array: T[]) => number): number | undefined; +export function variance(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; // -------------------------------------------------------------------------------------- // Searching Arrays // -------------------------------------------------------------------------------------- -export function scan(array: T[], comparator: (a: T, b: T) => number): number; +export function scan(array: number[], comparator?: (a: number, b: number) => number): number | undefined; +export function scan(array: T[], comparator: (a: T, b: T) => number): number | undefined; export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number; export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number; @@ -202,16 +169,16 @@ export function bisector(accessor: (x: T) => U): Bisector; /** * Compares two primitive values for sorting (in ascending order). */ -export function ascending(a: Primitive, b: Primitive): number; +export function ascending(a: Primitive | undefined, b: Primitive | undefined): number; // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** * Compares two primitive values for sorting (in ascending order). */ -export function descending(a: Primitive, b: Primitive): number; +export function descending(a: Primitive | undefined, b: Primitive | undefined): number; // -------------------------------------------------------------------------------------- -// Transforming Arrays +// Transforming Arrays // -------------------------------------------------------------------------------------- @@ -236,7 +203,6 @@ export function permute(array: { [key: number]: T }, keys: number[]): T[]; */ export function permute(object: { [key: string]: T }, keys: string[]): T[]; - /** * Generates a 0-based numeric sequence. The output range does not include 'stop'. */ diff --git a/d3-array/tsconfig.json b/d3-array/tsconfig.json index db900a4087..b70f6aed80 100644 --- a/d3-array/tsconfig.json +++ b/d3-array/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/d3-array/tslint.json b/d3-array/tslint.json new file mode 100644 index 0000000000..68d10d72a6 --- /dev/null +++ b/d3-array/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "unified-signatures": false + } +} diff --git a/d3-axis/d3-axis-tests.ts b/d3-axis/d3-axis-tests.ts index 1aa50ba641..1a4077d690 100644 --- a/d3-axis/d3-axis-tests.ts +++ b/d3-axis/d3-axis-tests.ts @@ -54,9 +54,9 @@ axisScaleString = scalePoint(); // -------------------------------------------------------------------------- let containerElement: d3Axis.AxisContainerElement; -const svg: SVGSVGElement = select('svg').node() !; //mock -const g: SVGGElement = select('g').node() !; //mock -const canvas: HTMLCanvasElement = select('canvas').node() !; //mock +const svg: SVGSVGElement = select('svg').node() !; // mock +const g: SVGGElement = select('g').node() !; // mock +const canvas: HTMLCanvasElement = select('canvas').node() !; // mock containerElement = svg; containerElement = g; @@ -78,7 +78,7 @@ let leftAxis: d3Axis.Axis = d3Axis.axisLeft(scal // scale(...) ---------------------------------------------------------------- leftAxis = leftAxis.scale(scalePow()); -let powerScale: ScalePower = leftAxis.scale>(); +const powerScale: ScalePower = leftAxis.scale>(); // powerScale = leftAxis.scale(); // fails, without casting as AxisScale is purposely generic @@ -86,8 +86,8 @@ let powerScale: ScalePower = leftAxis.scale()); // bottomAxis = bottomAxis.scale(scalePow()) // fails, domain of scale incompatible with domain of axis -let axisScale: d3Axis.AxisScale = bottomAxis.scale(); -let ordinalScale: ScaleOrdinal = bottomAxis.scale>(); +const axisScale: d3Axis.AxisScale = bottomAxis.scale(); +const ordinalScale: ScaleOrdinal = bottomAxis.scale>(); // ordinalScale = bottomAxis.scale(); // fails, without casting as AxisScale is purposely generic // ticks(...) ---------------------------------------------------------------- @@ -102,7 +102,7 @@ topAxis = topAxis.tickArguments([20, 's']); rightAxis = rightAxis.tickArguments([timeMinute.every(5)]); -let tickArguments: any[] = leftAxis.tickArguments(); +const tickArguments: any[] = leftAxis.tickArguments(); // tickValues(...) ---------------------------------------------------------------- @@ -112,17 +112,17 @@ bottomAxis = bottomAxis.tickValues(['strongly negative', 'strongly positive']); leftAxis = leftAxis.tickValues(null); -let tickValues: Date[] | null = rightAxis.tickValues(); +const tickValues: Date[] | null = rightAxis.tickValues(); // tickFormat(...) ---------------------------------------------------------------- topAxis = topAxis.tickFormat(format(',.0f')); topAxis = topAxis.tickFormat(null); -let formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat(); +const formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat(); -bottomAxis.tickFormat(function (d, i) { return '#' + i; }); -bottomAxis.tickFormat(function (d) { return d + '!'; }); +bottomAxis.tickFormat((d, i) => '#' + i); +bottomAxis.tickFormat(d => d + '!'); // tickSize(...) ---------------------------------------------------------------- rightAxis = rightAxis.tickSize(5); @@ -147,20 +147,20 @@ num = rightAxis.tickPadding(); // Test Apply Axis // -------------------------------------------------------------------------- -let gSelection: Selection = select('g'); -let gTransition = gSelection.transition(); +const gSelection: Selection = select('g'); +const gTransition = gSelection.transition(); gSelection.call(topAxis); gTransition.call(topAxis); -let svgSelection: Selection = select('g'); -let svgTransition = svgSelection.transition(); +const svgSelection: Selection = select('g'); +const svgTransition = svgSelection.transition(); svgSelection.call(leftAxis); svgTransition.call(leftAxis); -let canvasSelection: Selection = select('canvas'); -let canvasTransition = canvasSelection.transition(); +const canvasSelection: Selection = select('canvas'); +const canvasTransition = canvasSelection.transition(); // canvasSelection.call(rightAxis); // fails, incompatible context container element // canvasTransition.call(rightAxis); // fails, incompatible context container element diff --git a/d3-brush/d3-brush-tests.ts b/d3-brush/d3-brush-tests.ts index eca4a8ef91..367cc05d1b 100644 --- a/d3-brush/d3-brush-tests.ts +++ b/d3-brush/d3-brush-tests.ts @@ -26,9 +26,9 @@ interface BrushDatum { let brush: d3Brush.BrushBehavior = d3Brush.brush(); -let brushX: d3Brush.BrushBehavior = d3Brush.brushX(); +const brushX: d3Brush.BrushBehavior = d3Brush.brushX(); -let brushY: d3Brush.BrushBehavior = d3Brush.brushY(); +const brushY: d3Brush.BrushBehavior = d3Brush.brushY(); // extent() ---------------------------------------------------------------------- @@ -39,7 +39,7 @@ extent = brush.extent(); brush = brush.extent([[0, 0], [300, 200]]); // chainable with function -brush = brush.extent(function (d, i, group) { +brush = brush.extent(function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return d.extent; // datum of type BrushDatum }); @@ -47,10 +47,10 @@ brush = brush.extent(function (d, i, group) { // filter() ---------------------------------------------------------------- // chainable -brush = brush.filter(function (d, i, group) { +brush = brush.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - let e = > event; + const e = > event; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return e.sourceEvent.type !== 'zoom' || !d.filterZoomEvent; // datum type is BrushDatum (as propagated to SVGGElement with brush event attached) @@ -63,17 +63,17 @@ filterFn = brush.filter(); // chainable brush = brush.handleSize(7); -let handleSize: number = brush.handleSize(); +const handleSize: number = brush.handleSize(); // on() ------------------------------------------------------------------------ let brushed: ((this: SVGGElement, datum: BrushDatum, index: number, group: SVGGElement[] | ArrayLike) => void) | undefined; -brushed = function (d, i, group) { +brushed = (d, i, group) => { // do anything }; -let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike) => void; -let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike) => void; +// let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike) => void; +// let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike) => void; // chainable brush = brush.on('end', brushed); @@ -87,11 +87,11 @@ brushed = brush.on('end'); brush = brush.on('end', null); // re-apply -brush.on('end', function (d, i, g) { - let that: SVGGElement = this; - let datum: BrushDatum = d; - let index: number = i; - let group: SVGGElement[] | ArrayLike = g; +brush.on('end', function(d, i, g) { + const that: SVGGElement = this; + const datum: BrushDatum = d; + const index: number = i; + const group: SVGGElement[] | ArrayLike = g; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement console.log('Extent as per data: ', d.extent); // datum of type BrushDatum // do anything @@ -103,7 +103,7 @@ brush.on('end', function (d, i, g) { // Test Attach Brush Behavior // ----------------------------------------------------------------------------- -let g = select('svg') +const g = select('svg') .append('g') .classed('brush', true) .datum({ @@ -113,7 +113,7 @@ let g = select('svg') g.call(brush); -let gX = select('svg') +const gX = select('svg') .append('g') .classed('brush', true) .datum({ @@ -129,13 +129,13 @@ gX.call(brushX); // Test Use Brush Behavior // ----------------------------------------------------------------------------- -let gTransition = g.transition(); +const gTransition = g.transition(); // 2d brush move with Selection brush.move(g, [[10, 10], [50, 50]]); // two-dimensional brush -brush.move(g, function (d, i, group) { +brush.move(g, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; + const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum selection[0][1] = d.extent[0][1] + 10; selection[1][0] = d.extent[0][0] + 40; @@ -145,9 +145,9 @@ brush.move(g, function (d, i, group) { // 2d brush move with Transition brush.move(gTransition, [[10, 10], [50, 50]]); // two-dimensional brush -brush.move(gTransition, function (d, i, group) { +brush.move(gTransition, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; + const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum selection[0][1] = d.extent[0][1] + 10; selection[1][0] = d.extent[0][0] + 40; @@ -156,13 +156,13 @@ brush.move(gTransition, function (d, i, group) { }); -let gXTransition = gX.transition(); +const gXTransition = gX.transition(); // 1d brush move with Selection brush.move(gX, [10, 40]); // two-dimensional brush -brush.move(gX, function (d, i, group) { +brush.move(gX, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [number, number] = [0, 0]; + const selection: [number, number] = [0, 0]; selection[0] = d.extent[0][0] + 10; // datum type is brushDatum selection[1] = d.extent[0][0] + 40; return selection; @@ -170,9 +170,9 @@ brush.move(gX, function (d, i, group) { // 1d brush move with Transition brush.move(gXTransition, [10, 40]); // two-dimensional brush -brush.move(gXTransition, function (d, i, group) { +brush.move(gXTransition, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [number, number] = [0, 0]; + const selection: [number, number] = [0, 0]; selection[0] = d.extent[0][0] + 10; // datum type is brushDatum selection[1] = d.extent[0][0] + 40; return selection; @@ -184,10 +184,10 @@ brush.move(gXTransition, function (d, i, group) { // ----------------------------------------------------------------------------- -let e: d3Brush.D3BrushEvent = event; +const e: d3Brush.D3BrushEvent = event; -let target: d3Brush.BrushBehavior = e.target; -let type: 'start' | 'brush' | 'end' | string = e.type; -let brushSelection: d3Brush.BrushSelection = e.selection; -let sourceEvent: any = e.sourceEvent; +const target: d3Brush.BrushBehavior = e.target; +const type: 'start' | 'brush' | 'end' | string = e.type; +const brushSelection: d3Brush.BrushSelection = e.selection; +const sourceEvent: any = e.sourceEvent; diff --git a/d3-chord/d3-chord-tests.ts b/d3-chord/d3-chord-tests.ts index b2dd960b79..c826c81fac 100644 --- a/d3-chord/d3-chord-tests.ts +++ b/d3-chord/d3-chord-tests.ts @@ -15,7 +15,7 @@ import { ascending } from 'd3-array'; // Preparatory Steps // --------------------------------------------------------------------- -let context: CanvasRenderingContext2D | null= document.querySelector('canvas')!.getContext('2d'); +let context: CanvasRenderingContext2D | null = document.querySelector('canvas')!.getContext('2d'); let chords: d3Chord.Chords; let chordGroups: d3Chord.ChordGroup[]; @@ -23,7 +23,7 @@ let chord: d3Chord.Chord; let chordSubgroup: d3Chord.ChordSubgroup; let num: number; -let matrix: number[][] = [ +const matrix: number[][] = [ [11975, 5871, 8916, 2868], [1951, 10048, 2060, 6171], [8010, 16145, 8090, 8045], @@ -79,7 +79,7 @@ chords = chordLayout(matrix); // Test supporting interfaces ========================================== -let length: number = chords.length; +const length: number = chords.length; chordGroups = chords.groups; @@ -126,7 +126,7 @@ svgRibbon = svgRibbon.context(null); // source() ----------------------------------------------------------- -svgRibbon = svgRibbon.source(function (d) { +svgRibbon = svgRibbon.source(d => { return d.source; // datum is of type Chord }); @@ -134,7 +134,7 @@ subgroupAccessor = svgRibbon.source(); // target() ----------------------------------------------------------- -svgRibbon = svgRibbon.target(function (d) { +svgRibbon = svgRibbon.target(d => { return d.target; // datum is of type Chord }); @@ -145,7 +145,7 @@ subgroupAccessor = svgRibbon.target(); canvasRibbon = canvasRibbon.radius(30); -svgRibbon = svgRibbon.radius(function (d) { +svgRibbon = svgRibbon.radius(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement console.log('Subgroup startAngle', d.startAngle); // datum is of type Chord return 30; @@ -157,7 +157,7 @@ numAccessor = svgRibbon.radius(); canvasRibbon = canvasRibbon.startAngle(0); -svgRibbon = svgRibbon.startAngle(function (d) { +svgRibbon = svgRibbon.startAngle(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement return d.startAngle; // datum is of type ChordSubgroup }); @@ -168,7 +168,7 @@ numAccessor = svgRibbon.startAngle(); canvasRibbon = canvasRibbon.endAngle(Math.PI); -svgRibbon = svgRibbon.endAngle(function (d) { +svgRibbon = svgRibbon.endAngle(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement return d.endAngle; // datum is of type ChordSubgroup }); @@ -178,7 +178,7 @@ numAccessor = svgRibbon.endAngle(); // Use RibbonGenerator ================================================= // use canvas -let ribbon: d3Chord.Ribbon = { +const ribbon: d3Chord.Ribbon = { source: {startAngle: 0.7524114, endAngle: 1.1212972, radius: 240}, target: {startAngle: 1.8617078, endAngle: 1.9842927, radius: 240} }; @@ -199,6 +199,6 @@ let ribbonPaths: Selection('g') .datum(chords) .selectAll() - .data(function (chords) { return chords; }) + .data(chords => chords) .enter().append('path') .attr('d', svgRibbon); diff --git a/d3-chord/index.d.ts b/d3-chord/index.d.ts index 4696693d83..b4865c962c 100644 --- a/d3-chord/index.d.ts +++ b/d3-chord/index.d.ts @@ -306,8 +306,9 @@ export interface RibbonGenerator { * Sets the radius accessor to the specified function and returns this ribbon generator. * * @param radius An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and - * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed - * into the generator, with the exception of the first element representing the chord datum itself. The function returns the radius value. + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the radius value. */ radius(radius: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; @@ -326,8 +327,9 @@ export interface RibbonGenerator { * Sets the start angle accessor to the specified function and returns this ribbon generator. * * @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and - * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed - * into the generator, with the exception of the first element representing the chord datum itself. The function returns the start angle in radians. + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the start angle in radians. */ startAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; @@ -346,8 +348,9 @@ export interface RibbonGenerator { * Sets the end angle accessor to the specified function and returns this ribbon generator. * * @param angle An accessor function which is invoked for the source and target of the chord. The accessor function is invoked in the same "this" context as the generator was invoked in and - * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. It is also passed any additional arguments that were passed - * into the generator, with the exception of the first element representing the chord datum itself. The function returns the end angle in radians. + * receives as the first argument the source or target object returned by the respective source or target accessor function of the generator. + * It is also passed any additional arguments that were passed into the generator, with the exception of the first element representing the chord datum itself. + * The function returns the end angle in radians. */ endAngle(angle: (this: This, d: RibbonSubgroupDatum, ...args: any[]) => number): this; diff --git a/d3-drag/d3-drag-tests.ts b/d3-drag/d3-drag-tests.ts index 379647117b..deb5a6dc55 100644 --- a/d3-drag/d3-drag-tests.ts +++ b/d3-drag/d3-drag-tests.ts @@ -38,9 +38,9 @@ interface CustomSubject { r: number; } -let svg: SVGSVGElement = select('svg').node()!; // mock +const svg: SVGSVGElement = select('svg').node()!; // mock -let circles: Selection = select('svg').selectAll('circle'); // mock +const circles: Selection = select('svg').selectAll('circle'); // mock // ----------------------------------------------------------------------------- // Test Define DragBehavior @@ -65,7 +65,7 @@ circleCustomDrag = d3Drag.drag) => d3Drag.DragContainerElement; -containerAccessor = function (d, i, group) { +containerAccessor = function(d, i, group) { console.log('Node Id of circle: ', d.nodeId); // console.log(this.a); // fails, a is not a property of SVGCircleElement return this.ownerSVGElement; // this-type is SVGCircleElement @@ -73,7 +73,7 @@ containerAccessor = function (d, i, group) { // Test chainability circleDrag = circleDrag - .container(function (d, i, group) { // container accessor function setter + .container(function(d, i, group) { // container accessor function setter console.log('Node Id of circle: ', d.nodeId); // CircleDatum type // console.log(this.a); // fails, a is not a property of SVGCircleElement return this.ownerSVGElement; // this-type is SVGCircleElement @@ -93,12 +93,12 @@ containerAccessor = circleDrag.container(); let filterFn: (this: SVGCircleElement, datum: CircleDatum, index: number, group: SVGCircleElement[] | NodeListOf) => boolean; -filterFn = function (d) { +filterFn = function(d) { return (d.color !== 'green' && this.r.baseVal.value < 10) ? !event.button : true; // 'this' is SVGCircleElement and d is CircleDatum }; // chainable -circleDrag = circleDrag.filter(function (d, i, group) { +circleDrag = circleDrag.filter(function(d, i, group) { return (d.color !== 'green' && this.r.baseVal.value < 10) ? !event.button : true; // 'this' is SVGCircleElement and d is CircleDatum }); @@ -108,13 +108,13 @@ filterFn = circleDrag.filter(); // set and get subject --------------------------------------------------------- -circleCustomDrag.subject(function (d, i, g) { +circleCustomDrag.subject(function(d, i, g) { // Cast event type for completeness, otherwise event is of type any. - let e = > event; - let that: SVGCircleElement = this; - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + const e = > event; + const that: SVGCircleElement = this; + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; if (d == null) { return { x: e.x, y: e.y }; @@ -139,14 +139,14 @@ subjectAccessor = circleCustomDrag.subject(); function dragstarted(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - let e = > event; + const e = > event; e.sourceEvent.stopPropagation(); select(this).classed('dragging', true); } function dragged(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - let e = > event; + const e = > event; select(this).attr('cx', d.x = e.x).attr('cy', d.y = e.y); } @@ -174,16 +174,17 @@ circleDrag = circleDrag circleDrag.on('start.tmp', null); let handler: ((this: SVGCircleElement, d: CircleDatum, i: number, group: SVGCircleElement[] | NodeListOf) => void) | undefined = circleDrag.on('start'); -// let wrongHandler1: ((this:SVGRectElement, d:CircleDatum, i: number, group: SVGRectElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); // fails, wrong dragged DOM event -// let wrongHandler2: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); // fails, handler with wrong datum type - +// fails, wrong dragged DOM event +// let wrongHandler1: ((this:SVGRectElement, d:CircleDatum, i: number, group: SVGRectElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); +// fails, handler with wrong datum type +// let wrongHandler2: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = circleDrag.on('start'); // ----------------------------------------------------------------------------- // Test Attach Drag Behavior // ----------------------------------------------------------------------------- circles.call(circleDrag); -let wrongSelection: Selection = select('div'); +const wrongSelection: Selection = select('div'); // wrongSelection.call(circleDrag); // fails, as dragged elements are not of type specified for drag behavior @@ -197,15 +198,15 @@ let e: d3Drag.D3DragEvent)=> void) | undefined = e.on('dragged'); // fails, wrong dragged DOM event -// let wrongHandler4: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = e.on('dragged'); // fails, handler with wrong datum type +// fails, wrong dragged DOM event +// let wrongHandler3: ((this:SVGRectElement, d:CircleDatum, i: number, group: SVGRectElement[] | NodeListOf)=> void) | undefined = e.on('dragged'); +// fails, handler with wrong datum type +// let wrongHandler4: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = e.on('dragged'); // ----------------------------------------------------------------------------- // Test dragDisable() and dragEnable() // ----------------------------------------------------------------------------- -let w: Window = window; +const w: Window = window; d3Drag.dragDisable(w); diff --git a/d3-dsv/d3-dsv-tests.ts b/d3-dsv/d3-dsv-tests.ts index 40516166b1..a4d958f01b 100644 --- a/d3-dsv/d3-dsv-tests.ts +++ b/d3-dsv/d3-dsv-tests.ts @@ -13,13 +13,13 @@ import * as d3Dsv from 'd3-dsv'; // ------------------------------------------------------------------------------------------ -let csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; -let tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; -let pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; +const csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +const tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +const pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; -let csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; -let tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; -let pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; +const csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +const tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +const pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; interface ParsedTestObject { year: Date; @@ -31,11 +31,11 @@ interface ParsedTestObject { let parseArray: d3Dsv.DSVParsedArray; let parseMappedArray: d3Dsv.DSVParsedArray; -let parseRowsArray: Array>; -let parseRowsMappedArray: Array; +let parseRowsArray: string[][]; +let parseRowsMappedArray: ParsedTestObject[]; -let columns: Array; +let columns: string[]; let num: number; let date: Date; let str: string; @@ -57,21 +57,17 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- -parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, function (rawRow, index, columns) { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: Array = columns; - let pr: ParsedTestObject; - - pr = { +parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -94,20 +90,16 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- -parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, function (rawRow, index) { - let rr: Array = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { +parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -122,14 +114,12 @@ str = d3Dsv.csvFormat(parseRowsMappedArray, columns); // csvFormatRows(...) ======================================================================== -str = d3Dsv.csvFormatRows(parseRowsMappedArray.map(function(d, i) { - return [ +str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [ d.year.getFullYear().toString(), d.make, d.model, d.length.toString() - ]; -})); +])); // ------------------------------------------------------------------------------------------ // Test TSV @@ -148,21 +138,17 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- -parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, function (rawRow, index, columns) { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: Array = columns; - let pr: ParsedTestObject; - - pr = { +parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -185,20 +171,16 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- -parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, function (rawRow, index) { - let rr: Array = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { +parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -213,14 +195,12 @@ str = d3Dsv.tsvFormat(parseRowsMappedArray, columns); // tsvFormatRows(...) ======================================================================== -str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map(function(d, i) { - return [ +str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d, i) => [ d.year.getFullYear().toString(), d.make, d.model, d.length.toString() - ]; -})); +])); // ------------------------------------------------------------------------------------------ // Test DSV Generalized Parsers and Formatters @@ -244,21 +224,17 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- -parseMappedArray = dsv.parse(pipedTestStringWithHeader, function (rawRow, index, columns) { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: Array = columns; - let pr: ParsedTestObject; - - pr = { +parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -281,20 +257,16 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- -parseRowsMappedArray = dsv.parseRows(pipedTestString, function (rawRow, index) { - let rr: Array = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { +parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -309,11 +281,9 @@ str = dsv.format(parseRowsMappedArray, columns); // formatRows(...) ======================================================================== -str = dsv.formatRows(parseRowsMappedArray.map(function(d, i) { - return [ +str = dsv.formatRows(parseRowsMappedArray.map((d, i) => [ d.year.getFullYear().toString(), d.make, d.model, d.length.toString() - ]; -})); +])); diff --git a/d3-dsv/index.d.ts b/d3-dsv/index.d.ts index 7682644987..eaf9797b02 100644 --- a/d3-dsv/index.d.ts +++ b/d3-dsv/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-dsv module v1.0.1 +// Type definitions for D3JS d3-dsv module 1.0 // Project: https://github.com/d3/d3-dsv/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -16,7 +16,7 @@ export interface DSVRowAny { } export interface DSVParsedArray extends Array { - columns: Array; + columns: string[]; } // ------------------------------------------------------------------------------------------ @@ -26,21 +26,20 @@ export interface DSVParsedArray extends Array { // csvParse(...) ============================================================================ export function csvParse(csvString: string): DSVParsedArray; -export function csvParse(csvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow): DSVParsedArray; +export function csvParse(csvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DSVParsedArray; // csvParseRows(...) ======================================================================== -export function csvParseRows(csvString: string): Array>; -export function csvParseRows(csvString: string, row: (rawRow: Array, index: number) => ParsedRow): Array; +export function csvParseRows(csvString: string): string[][]; +export function csvParseRows(csvString: string, row: (rawRow: string[], index: number) => ParsedRow): ParsedRow[]; // csvFormat(...) ============================================================================ -export function csvFormat(rows: Array): string; -export function csvFormat(rows: Array, columns: Array): string; +export function csvFormat(rows: DSVRowAny[], columns?: string[]): string; // csvFormatRows(...) ======================================================================== -export function csvFormatRows(rows: Array>): string; +export function csvFormatRows(rows: string[][]): string; // ------------------------------------------------------------------------------------------ // TSV Parsers and Formatters @@ -49,21 +48,20 @@ export function csvFormatRows(rows: Array>): string; // tsvParse(...) ============================================================================ export function tsvParse(tsvString: string): DSVParsedArray; -export function tsvParse(tsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => MappedRow): DSVParsedArray; +export function tsvParse(tsvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow): DSVParsedArray; // tsvParseRows(...) ======================================================================== -export function tsvParseRows(tsvString: string): Array>; -export function tsvParseRows(tsvString: string, row: (rawRow: Array, index: number) => MappedRow): Array; +export function tsvParseRows(tsvString: string): string[][]; +export function tsvParseRows(tsvString: string, row: (rawRow: string[], index: number) => MappedRow): MappedRow[]; // tsvFormat(...) ============================================================================ -export function tsvFormat(rows: Array): string; -export function tsvFormat(rows: Array, columns: Array): string; +export function tsvFormat(rows: DSVRowAny[], columns?: string[]): string; // tsvFormatRows(...) ======================================================================== -export function tsvFormatRows(rows: Array>): string; +export function tsvFormatRows(rows: string[][]): string; // ------------------------------------------------------------------------------------------ // DSV Generalized Parsers and Formatters @@ -71,12 +69,11 @@ export function tsvFormatRows(rows: Array>): string; export interface DSV { parse(dsvString: string): DSVParsedArray; - parse(dsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow): DSVParsedArray; - parseRows(dsvString: string): Array>; - parseRows(dsvString: string, row: (rawRow: Array, index: number) => ParsedRow): Array; - format(rows: Array): string; - format(rows: Array, columns: Array): string; - formatRows(rows: Array>): string; + parse(dsvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DSVParsedArray; + parseRows(dsvString: string): string[][]; + parseRows(dsvString: string, row: (rawRow: string[], index: number) => ParsedRow): ParsedRow[]; + format(rows: DSVRowAny[], columns?: string[]): string; + formatRows(rows: string[][]): string; } export function dsvFormat(delimiter: string): DSV; diff --git a/d3-dsv/v0/index.d.ts b/d3-dsv/v0/index.d.ts index 5547fccf6c..82ccd0f87f 100644 --- a/d3-dsv/v0/index.d.ts +++ b/d3-dsv/v0/index.d.ts @@ -38,7 +38,12 @@ interface D3Dsv { ): TRow[]; /** - Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. The string is assumed to be RFC4180-compliant. Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. Each row is represented as an array rather than an object. Rows may have variable length. For example, consider the following CSV file: + Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. + The string is assumed to be RFC4180-compliant. + Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. + Each row is represented as an array rather than an object. + Rows may have variable length. + For example, consider the following CSV file: 1997,Ford,E350,2.34 2000,Mercury,Cougar,2.38 @@ -55,14 +60,20 @@ interface D3Dsv { ): TRow[]; /** - Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parse. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. + Converts the specified array of rows into comma-separated values format, returning a string. + This operation is the reverse of parse. + Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). + Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. - Each row should be an object, and all object properties will be converted into fields. For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. + Each row should be an object, and all object properties will be converted into fields. + For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. */ format(rows: any[]): string; /** - Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. + Converts the specified array of rows into comma-separated values format, returning a string. + This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). + Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. */ formatRows(rows: any[]): string; } diff --git a/d3-dsv/v0/tslint.json b/d3-dsv/v0/tslint.json index 06eb30c7b9..af53769b6b 100644 --- a/d3-dsv/v0/tslint.json +++ b/d3-dsv/v0/tslint.json @@ -1 +1 @@ -{ "extends": "../../tslint.json" } \ No newline at end of file +{ "extends": "../../tslint.json" } diff --git a/d3-ease/d3-ease-tests.ts b/d3-ease/d3-ease-tests.ts index 84e34aa064..b50ceba9a4 100644 --- a/d3-ease/d3-ease-tests.ts +++ b/d3-ease/d3-ease-tests.ts @@ -8,7 +8,7 @@ import * as d3Ease from 'd3-ease'; -let t_in: number = 0.5; +const t_in: number = 0.5; let t_out: number; t_out = d3Ease.easeLinear(t_in); diff --git a/d3-ease/tslint.json b/d3-ease/tslint.json index f9e30021f4..377cc837d4 100644 --- a/d3-ease/tslint.json +++ b/d3-ease/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/d3-force/d3-force-tests.ts b/d3-force/d3-force-tests.ts index b760864079..0ecd7555d3 100644 --- a/d3-force/d3-force-tests.ts +++ b/d3-force/d3-force-tests.ts @@ -31,7 +31,7 @@ interface Graph { } -let graph: Graph = { +const graph: Graph = { nodes: [ { id: 'Myriel', group: 1, r: 5 }, { id: 'Napoleon', group: 1, r: 10 }, @@ -55,10 +55,10 @@ let simLinks: SimLink[]; let num: number; -let canvas = document.querySelector('canvas')!; -let context = canvas.getContext('2d'); -let width = canvas.width; -let height = canvas.height; +const canvas = document.querySelector('canvas')!; +const context = canvas.getContext('2d'); +const width = canvas.width; +const height = canvas.height; // ------------------------------------------------------------------------------------- // Test Pre-Defined Forces @@ -105,10 +105,10 @@ forceCollide = d3Force.forceCollide(); forceCollide = d3Force.forceCollide(15); // with radius accessor function -forceCollide = d3Force.forceCollide(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceCollide = d3Force.forceCollide((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return n.r; }); @@ -120,10 +120,10 @@ let radiusAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number; // radius forceCollide = forceCollide.radius(20); -forceCollide = forceCollide.radius(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceCollide = forceCollide.radius((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 2 * n.r; }); @@ -161,7 +161,7 @@ forceLink = d3Force.forceLink(graph.links); // Configure Link force ----------------------------------------------------------- let linkNumberAccessor: (link: SimLink, i: number, links: SimLink[]) => number; -let nodeIdAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number | string; +// let nodeIdAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number | string; // links @@ -174,7 +174,7 @@ simLink = simLinks[0]; simNode = (typeof simLink.source !== 'number' && typeof simLink.source !== 'string') ? simLink.source : undefined; simNode = (typeof simLink.target !== 'number' && typeof simLink.target !== 'string') ? simLink.target : undefined; -let maybeNum: number | undefined = simLink.index; // Ex-ante type before initialization of links +const maybeNum: number | undefined = simLink.index; // Ex-ante type before initialization of links num = simLink.index!; // Ex-post after link initialization, use ! non-null assertion operator to narrow to number num = simLink.value; @@ -184,20 +184,20 @@ num = simLink.s; // id (node id accessor) -forceLink = forceLink.id(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceLink = forceLink.id((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return n.id; }); // distance forceLink = forceLink.distance(50); -forceLink = forceLink.distance(function (link, index, links) { - let l: SimLink = link; - let i: number = index; - let ls: SimLink[] = links; +forceLink = forceLink.distance((link, index, links) => { + const l: SimLink = link; + const i: number = index; + const ls: SimLink[] = links; return l.d; }); @@ -206,10 +206,10 @@ linkNumberAccessor = forceLink.distance(); // strength forceLink = forceLink.strength(0.95); -forceLink = forceLink.strength(function (link, index, links) { - let l: SimLink = link; - let i: number = index; - let ls: SimLink[] = links; +forceLink = forceLink.strength((link, index, links) => { + const l: SimLink = link; + const i: number = index; + const ls: SimLink[] = links; return l.s; }); @@ -242,10 +242,10 @@ let simNodeNumberAccessor: (node: SimNode, i: number, nodes: SimNode[]) => numbe // strength forceCharge = forceCharge.strength(-3000); -forceCharge = forceCharge.strength(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forceCharge = forceCharge.strength((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return -1000 * n.group; }); simNodeNumberAccessor = forceCharge.strength(); @@ -286,10 +286,10 @@ forcePosX = d3Force.forceX(); // strength forcePosX = forcePosX.strength(0.2); -forcePosX = forcePosX.strength(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosX = forcePosX.strength((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 0.1 * n.group; }); simNodeNumberAccessor = forcePosX.strength(); @@ -297,10 +297,10 @@ simNodeNumberAccessor = forcePosX.strength(); // x forcePosX = forcePosX.x(100); -forcePosX = forcePosX.x(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosX = forcePosX.x((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; let target: number; switch (n.group) { case 1: @@ -341,10 +341,10 @@ forcePosY = d3Force.forceY(); // strength forcePosY = forcePosY.strength(0.2); -forcePosY = forcePosY.strength(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosY = forcePosY.strength((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 0.1 * n.group; }); simNodeNumberAccessor = forcePosY.strength(); @@ -352,10 +352,10 @@ simNodeNumberAccessor = forcePosY.strength(); // y forcePosY = forcePosY.y(100); -forcePosY = forcePosY.y(function (node, index, nodes) { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; +forcePosY = forcePosY.y((node, index, nodes) => { + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; let target: number; switch (n.group) { case 1: @@ -503,7 +503,7 @@ function drawNode(d: SimNode) { nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() { - let that: d3Force.Simulation = this; + const that: d3Force.Simulation = this; if (context) { context.clearRect(0, 0, width, height); @@ -525,7 +525,7 @@ nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() { nodeSimulation = nodeSimulation.on('tick', null); // get listener -let listener: ((this: d3Force.Simulation) => void) | undefined = nodeSimulation.on('tick'); +const listener: ((this: d3Force.Simulation) => void) | undefined = nodeSimulation.on('tick'); // Configure and Use Force Simulation =================================================== diff --git a/d3-hierarchy/d3-hierarchy-tests.ts b/d3-hierarchy/d3-hierarchy-tests.ts index ce7354afe3..7079fae827 100644 --- a/d3-hierarchy/d3-hierarchy-tests.ts +++ b/d3-hierarchy/d3-hierarchy-tests.ts @@ -125,6 +125,13 @@ hierarchyRootNode = hierarchyRootNode.sum(function (d) { return d.val; }); num = hierarchyRootNode.value; +// count() and value ---------------------------------------------------------- + +hierarchyRootNode = hierarchyRootNode.count(); + +num = hierarchyRootNode.value; + + // sort --------------------------------------------------------------------- hierarchyRootNode = hierarchyRootNode.sort(function (a, b) { @@ -307,6 +314,12 @@ clusterRootNode = clusterRootNode.sum(function (d) { return d.val; }); num = clusterRootNode.value; +// count() and value ---------------------------------------------------------- + +clusterRootNode = clusterRootNode.count(); + +num = clusterRootNode.value; + // sort --------------------------------------------------------------------- clusterRootNode = clusterRootNode.sort(function (a, b) { @@ -584,6 +597,11 @@ treemapRootNode = treemapRootNode.sum(function (d) { return d.val; }); num = treemapRootNode.value; +// count() and value ---------------------------------------------------------- + +treemapRootNode = treemapRootNode.count(); + +num = treemapRootNode.value; // sort --------------------------------------------------------------------- treemapRootNode = treemapRootNode.sort(function (a, b) { @@ -766,6 +784,11 @@ packRootNode = packRootNode.sum(function (d) { return d.val; }); num = packRootNode.value; +// count() and value ---------------------------------------------------------- + +packRootNode = packRootNode.count(); + +num = packRootNode.value; // sort --------------------------------------------------------------------- packRootNode = packRootNode.sort(function (a, b) { diff --git a/d3-hierarchy/index.d.ts b/d3-hierarchy/index.d.ts index 7eef444875..bfe750b31e 100644 --- a/d3-hierarchy/index.d.ts +++ b/d3-hierarchy/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for D3JS d3-hierarchy module v1.0.2 +// Type definitions for D3JS d3-hierarchy module 1.1 // Project: https://github.com/d3/d3-hierarchy/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last module patch version validated against: 1.1.1 + // ----------------------------------------------------------------------- // Hierarchy // ----------------------------------------------------------------------- @@ -20,7 +22,7 @@ export interface HierarchyNode { parent: HierarchyNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -35,6 +37,7 @@ export interface HierarchyNode { path(target: HierarchyNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyNode, b: HierarchyNode) => number): this; each(func: (node: HierarchyNode) => void): this; eachAfter(func: (node: HierarchyNode) => void): this; @@ -43,7 +46,7 @@ export interface HierarchyNode { } -export function hierarchy(data: Datum, children?: (d: Datum) => (Array | null)): HierarchyNode; +export function hierarchy(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode; // ----------------------------------------------------------------------- // Stratify @@ -53,11 +56,11 @@ export function hierarchy(data: Datum, children?: (d: Datum) => (Array { - (data: Array): HierarchyNode; - id(): (d: Datum, i: number, data: Array) => (string | null | '' | undefined); - id(id: (d: Datum, i?: number, data?: Array) => (string | null | '' | undefined)): this; - parentId(): (d: Datum, i: number, data: Array) => (string | null | '' | undefined); - parentId(parentId: (d: Datum, i?: number, data?: Array) => (string | null | '' | undefined)): this; + (data: Datum[]): HierarchyNode; + id(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; + parentId(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; } export function stratify(): StratifyOperator; @@ -80,7 +83,7 @@ export interface HierarchyPointNode { parent: HierarchyPointNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -95,6 +98,7 @@ export interface HierarchyPointNode { path(target: HierarchyPointNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; each(func: (node: HierarchyPointNode) => void): this; eachAfter(func: (node: HierarchyPointNode) => void): this; @@ -150,7 +154,7 @@ export interface HierarchyRectangularNode { parent: HierarchyRectangularNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -165,6 +169,7 @@ export interface HierarchyRectangularNode { path(target: HierarchyRectangularNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyRectangularNode, b: HierarchyRectangularNode) => number): this; each(func: (node: HierarchyRectangularNode) => void): this; eachAfter(func: (node: HierarchyRectangularNode) => void): this; @@ -258,7 +263,7 @@ export interface HierarchyCircularNode { parent: HierarchyCircularNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -273,6 +278,7 @@ export interface HierarchyCircularNode { path(target: HierarchyCircularNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyCircularNode, b: HierarchyCircularNode) => number): this; each(func: (node: HierarchyCircularNode) => void): this; eachAfter(func: (node: HierarchyCircularNode) => void): this; @@ -310,6 +316,6 @@ export interface PackCircle { // For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment // on the mandatory nature, then to create separate interfaces and having to deal with recasting. -export function packSiblings(circles: Array): Array; +export function packSiblings(circles: Datum[]): Datum[]; -export function packEnclose(circles: Array): { r: number, x: number, y: number }; +export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; diff --git a/d3-scale/d3-scale-tests.ts b/d3-scale/d3-scale-tests.ts index 269218967e..c1feb4766a 100644 --- a/d3-scale/d3-scale-tests.ts +++ b/d3-scale/d3-scale-tests.ts @@ -37,7 +37,6 @@ class StringCoercible { } let num: number; -let str: string; let date: Date; let clampFlag: boolean; @@ -46,7 +45,7 @@ let outputNumber: number; let outputString: string; let domainNumbers: number[] = [1, 100]; -let domainNumeric: NumCoercible[] = [new NumCoercible(0), new NumCoercible(100)]; +const domainNumeric: NumCoercible[] = [new NumCoercible(0), new NumCoercible(100)]; let domainStrings: string[]; let domainDates: Date[] = [new Date(2016, 0, 15), new Date(2016, 5, 15)]; @@ -126,19 +125,15 @@ clampFlag = linearScaleNumber.clamp(); linearScaleString = linearScaleString.interpolate(interpolateCubehelix.gamma(3)); -linearScaleNumString = linearScaleNumString.interpolate(function (a, b) { +linearScaleNumString = linearScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // Changes scale output type (inferred generic) -linearScaleNumString = linearScaleNumber.interpolate(function (a, b) { +linearScaleNumString = linearScaleNumber.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -169,7 +164,7 @@ outputString = linearScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedLinearScale: d3Scale.ScaleLinear = linearScaleNumString.copy(); +const copiedLinearScale: d3Scale.ScaleLinear = linearScaleNumString.copy(); // ------------------------------------------------------------------------------- // Power Scale Factories @@ -198,7 +193,7 @@ squarerootScaleNumString = d3Scale.scaleSqrt(); // exponent -------------------------------------------------------------------- -let exponent: number = squarerootScaleNumber.exponent(); +const exponent: number = squarerootScaleNumber.exponent(); powerScaleNumber = powerScaleNumber.exponent(5); @@ -249,11 +244,9 @@ clampFlag = powerScaleNumber.clamp(); powerScaleString = powerScaleString.interpolate(interpolateCubehelix.gamma(3)); -powerScaleNumString = powerScaleNumString.interpolate(function (a, b) { +powerScaleNumString = powerScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -283,7 +276,7 @@ outputString = powerScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedPowerScale: d3Scale.ScalePower = powerScaleNumString.copy(); +const copiedPowerScale: d3Scale.ScalePower = powerScaleNumString.copy(); // ------------------------------------------------------------------------------- // Logarithmic Scale Factory @@ -305,7 +298,7 @@ logScaleNumString = d3Scale.scaleLog(); // base -------------------------------------------------------------------- -let base: number = logScaleNumber.base(); +const base: number = logScaleNumber.base(); logScaleNumber = logScaleNumber.base(42); @@ -356,11 +349,9 @@ clampFlag = logScaleNumber.clamp(); logScaleString = logScaleString.interpolate(interpolateCubehelix.gamma(3)); -logScaleNumString = logScaleNumString.interpolate(function (a, b) { +logScaleNumString = logScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -390,7 +381,7 @@ outputString = logScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedLogScale: d3Scale.ScaleLogarithmic = logScaleNumString.copy(); +const copiedLogScale: d3Scale.ScaleLogarithmic = logScaleNumString.copy(); // ------------------------------------------------------------------------------- // Identity Scale Factory @@ -446,7 +437,7 @@ outputNumber = identityScale(10); // copy(...) ----------------------------------------------------------------- -let copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); +const copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); // ------------------------------------------------------------------------------- @@ -517,11 +508,9 @@ clampFlag = localTimeScaleNumber.clamp(); localTimeScaleString = localTimeScaleString.interpolate(interpolateCubehelix.gamma(3)); -localTimeScaleNumString = localTimeScaleNumString.interpolate(function (a, b) { +localTimeScaleNumString = localTimeScaleNumString.interpolate((a, b) => { // take two numbers - return function (t: number) { - return (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type - }; + return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- @@ -565,7 +554,7 @@ outputString = localTimeScaleNumString(new Date(2016, 6, 4)); // copy(...) ----------------------------------------------------------------- -let copiedTimeScale: d3Scale.ScaleTime = localTimeScaleNumString.copy(); +const copiedTimeScale: d3Scale.ScaleTime = localTimeScaleNumString.copy(); // ------------------------------------------------------------------------------- // Sequential Scale Factory @@ -584,7 +573,7 @@ sequentialScaleColorString = d3Scale.scaleSequential(d3Scale.interpolateCool); / sequentialScaleColorString = sequentialScaleColorString.domain([0, 1]); sequentialScaleColorString = sequentialScaleColorString.domain([new NumCoercible(0), new NumCoercible(100)]); -let domainSequential: [number, number] = sequentialScaleColorString.domain(); +const domainSequential: [number, number] = sequentialScaleColorString.domain(); // clamp(...) ----------------------------------------------------------------- @@ -604,7 +593,7 @@ outputString = sequentialScaleColorString(10); // copy(...) ----------------------------------------------------------------- -let copiedSequentialScale: d3Scale.ScaleSequential = sequentialScaleColorString.copy(); +const copiedSequentialScale: d3Scale.ScaleSequential = sequentialScaleColorString.copy(); @@ -650,7 +639,7 @@ quantizeScaleString = d3Scale.scaleQuantize(); quantizeScaleNumber = quantizeScaleNumber.domain([0, 1]); quantizeScaleNumber = quantizeScaleNumber.domain([new NumCoercible(0), new NumCoercible(100)]); -let domainQuantize: [number, number] = quantizeScaleNumber.domain(); +const domainQuantize: [number, number] = quantizeScaleNumber.domain(); // range(...) ----------------------------------------------------------------- @@ -690,7 +679,7 @@ outputNumber = quantizeScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- -let copiedQuantizeScale: d3Scale.ScaleQuantize = quantizeScaleNumber.copy(); +const copiedQuantizeScale: d3Scale.ScaleQuantize = quantizeScaleNumber.copy(); // ------------------------------------------------------------------------------- @@ -734,7 +723,7 @@ numExtent = quantileScaleString.invertExtent('q50'); // quantile() ----------------------------------------------------------------------- -let quantiles: number[] = quantileScaleNumber.quantiles(); +const quantiles: number[] = quantileScaleNumber.quantiles(); // (...) value mapping from domain to output ----------------------------------- @@ -742,7 +731,7 @@ outputNumber = quantileScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- -let copiedQuantileScale: d3Scale.ScaleQuantile = quantileScaleNumber.copy(); +const copiedQuantileScale: d3Scale.ScaleQuantile = quantileScaleNumber.copy(); // ------------------------------------------------------------------------------- @@ -790,7 +779,7 @@ outputString = thresholdScaleNumberString(0.9); // copy(...) ----------------------------------------------------------------- -let copiedThresholdScale: d3Scale.ScaleThreshold = thresholdScaleNumberString.copy(); +const copiedThresholdScale: d3Scale.ScaleThreshold = thresholdScaleNumberString.copy(); // ------------------------------------------------------------------------------- @@ -826,13 +815,13 @@ rangeNumbers = ordinalScaleStringNumber.range(); // unknown(...) and d3Scale.scaleImplicit -------------------------------------- -let implicit: { name: 'implicit' } = d3Scale.scaleImplicit; +const implicit: { name: 'implicit' } = d3Scale.scaleImplicit; ordinalScaleStringString = ordinalScaleStringString.unknown(d3Scale.scaleImplicit); ordinalScaleStringNumber = ordinalScaleStringNumber.unknown(0); -let unknownValue: string | { name: 'implicit' } = ordinalScaleStringString.unknown(); +const unknownValue: string | { name: 'implicit' } = ordinalScaleStringString.unknown(); if (typeof unknownValue === 'string') { console.log(unknownValue); @@ -848,7 +837,7 @@ outputNumber = ordinalScaleStringNumber('negative'); // copy(...) ----------------------------------------------------------------- -let copiedOrdinalScale: d3Scale.ScaleOrdinal = ordinalScaleStringNumber.copy(); +const copiedOrdinalScale: d3Scale.ScaleOrdinal = ordinalScaleStringNumber.copy(); // ------------------------------------------------------------------------------- @@ -930,7 +919,7 @@ outputNumberMaybe = bandScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- -let copiedBandScale: d3Scale.ScaleBand = bandScaleCoercible.copy(); +const copiedBandScale: d3Scale.ScaleBand = bandScaleCoercible.copy(); // ------------------------------------------------------------------------------- @@ -1001,7 +990,7 @@ outputNumberMaybe = pointScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- -let copiedPointScale: d3Scale.ScalePoint = pointScaleCoercible.copy(); +const copiedPointScale: d3Scale.ScalePoint = pointScaleCoercible.copy(); // ------------------------------------------------------------------------------- // Categorical Color Schemas for Ordinal Scales diff --git a/d3-scale/index.d.ts b/d3-scale/index.d.ts index 2fe664346a..2ba9eeec8a 100644 --- a/d3-scale/index.d.ts +++ b/d3-scale/index.d.ts @@ -501,8 +501,10 @@ export interface ScaleLogarithmic extends ScaleContinuousNumeric< /** * Returns a number format function suitable for displaying a tick value, automatically computing the appropriate precision based on the fixed interval between tick values. * - * The specified count typically has the same value as the count that is used to generate the tick values. If there are too many ticks, the formatter may return the empty string for some of the tick labels; - * however, note that the ticks are still shown. To disable filtering, specify a count of Infinity. When specifying a count, you may also provide a format specifier or format function. + * The specified count typically has the same value as the count that is used to generate the tick values. + * If there are too many ticks, the formatter may return the empty string for some of the tick labels; + * however, note that the ticks are still shown. + * To disable filtering, specify a count of Infinity. When specifying a count, you may also provide a format specifier or format function. * For example, to get a tick formatter that will display 20 ticks of a currency, say log.tickFormat(20, "$,f"). * If the specifier does not have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. * This provides a convenient way of specifying a format whose precision will be automatically set by the scale. @@ -1271,8 +1273,10 @@ export function scaleQuantize(): ScaleQuantize; // ------------------------------------------------------------------------------- /** - * Quantile scales map a sampled input domain to a discrete range. The domain is considered continuous and thus the scale will accept any reasonable input value; - * however, the domain is specified as a discrete set of sample values. The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. + * Quantile scales map a sampled input domain to a discrete range. + * The domain is considered continuous and thus the scale will accept any reasonable input value; + * however, the domain is specified as a discrete set of sample values. + * The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. * To compute the quantiles, the domain is sorted, and treated as a population of discrete values; see d3-array’s quantile. * * The generic correponds to the data type of range elements. @@ -1358,7 +1362,8 @@ export function scaleQuantile(): ScaleQuantile; * Threshold scales are similar to quantize scales, except they allow you to map arbitrary subsets of the domain to discrete values in the range. * The input domain is still continuous, and divided into slices based on a set of threshold values. * - * If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. If there are fewer than N elements in the domain, the additional values in the range are ignored. + * If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. + * If there are fewer than N elements in the domain, the additional values in the range are ignored. * If there are more than N elements in the domain, the scale may return undefined for some inputs. * * The first generic corresponds to the data type of domain values. diff --git a/d3-selection-multi/d3-selection-multi-tests.ts b/d3-selection-multi/d3-selection-multi-tests.ts index 5f8259052d..515dd8e92e 100644 --- a/d3-selection-multi/d3-selection-multi-tests.ts +++ b/d3-selection-multi/d3-selection-multi-tests.ts @@ -34,10 +34,10 @@ selection = selection.attrs({ }); // Function that returns a map -selection = selection.attrs(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +selection = selection.attrs(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return this.id ? {} : { id: d }; }); @@ -67,11 +67,11 @@ selection = selection.styles({ }, 'important'); // Functions that return a map -selection.styles(function (d) { +selection.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }); -selection = selection.styles(function (d) { +selection = selection.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }, 'important'); @@ -89,10 +89,10 @@ selection = selection.properties({ }); // Function that returns an object -selection = selection.properties(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +selection = selection.properties(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return that.href ? {} : { href: d }; }); @@ -112,16 +112,16 @@ transition = transition.attrs({ foo: () => 1, bar: (d) => d, baz: (d, i) => i !== 0, - bat: function () { + bat() { return this.href; }, }); // Function that returns a map -transition = transition.attrs(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +transition = transition.attrs(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return this.id ? {} : { id: d }; }); @@ -151,11 +151,11 @@ transition = transition.styles({ }, 'important'); // Function that returns a map -transition = transition.styles(function (d) { +transition = transition.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }); -transition = transition.styles(function (d) { +transition = transition.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }, 'important'); @@ -174,22 +174,22 @@ valueMap = { foo2: 2, foo3: true, foo4: null, - bar1: function (d) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; + bar1(d) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; return d.name; }, - bar2: function (d, i) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; - let index: number = i; + bar2(d, i) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; + const index: number = i; return d.r; }, - bar3: function (d, i, g) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + bar3(d, i, g) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; return d.filled; } }; @@ -200,7 +200,7 @@ valueMap = { // valueMap = { // fails, as a ValueFunction returning an array is not a permissible value type // foo1: function (d) { -// let that: SVGCircleElement = this; +// const that: SVGCircleElement = this; // let datum: SampleDatum = d; // return [1, 2]; // } diff --git a/d3-selection/d3-selection-tests.ts b/d3-selection/d3-selection-tests.ts index 042fba622a..43d8708938 100644 --- a/d3-selection/d3-selection-tests.ts +++ b/d3-selection/d3-selection-tests.ts @@ -15,7 +15,7 @@ import * as d3Selection from 'd3-selection'; // --------------------------------------------------------------------------------------- // Generic DOM related variables -let xDoc: Document = document; +const xDoc: Document = document; let xWindow: Window = window; interface BodyDatum { @@ -59,14 +59,14 @@ interface CircleDatumAlternative { // test top-level .selection() ----------------------------------------------------------- -let topSelection: d3Selection.Selection = d3Selection.selection(); +const topSelection: d3Selection.Selection = d3Selection.selection(); // test top-level select() --------------------------------------------------------------- // Using select() with string argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any' -let baseTypeEl: d3Selection.Selection = d3Selection.select('body'); +const baseTypeEl: d3Selection.Selection = d3Selection.select('body'); // Using select() with string argument and type parameters creates selection // with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type HTMLElement with datum of type 'any' @@ -76,18 +76,18 @@ let body: d3Selection.Selection = // Using select() with node argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined' -let baseTypeEl2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); +const baseTypeEl2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // let body2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // fails as baseTypeEl.node() is of type cannot be assigned to HTMLElement -let body3: d3Selection.Selection = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node() +const body3: d3Selection.Selection = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node() // Using select() with node argument and type parameters creates selection // with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type 'null' with datum of type 'undefined' -let body4: d3Selection.Selection = d3Selection.select(body.node()!); +const body4: d3Selection.Selection = d3Selection.select(body.node()!); // Explicitly cast body.node() to HTMLBodyElement to narrow selection definition. -let body5: d3Selection.Selection = d3Selection.select(body.node()!); +const body5: d3Selection.Selection = d3Selection.select(body.node()!); // d3Selection.select(baseTypeEl.node()!); // fails as baseTypeEl.node() is not of type HTMLBodyElement @@ -98,7 +98,8 @@ maybeSVG1 = d3Selection.select('svg'); let maybeSVG2: d3Selection.Selection; maybeSVG2 = d3Selection.select(maybeSVG1.node()); -// let body7: d3Selection.Selection = d3Selection.select(maybeSVG1.node()); // fails, as node type mismatches selection type +// fails, as node type mismatches selection type +// let body7: d3Selection.Selection = d3Selection.select(maybeSVG1.node()); // test "special case DOM objects" @@ -119,26 +120,28 @@ emptyRootSelection = d3Selection.selectAll(undefined); // Using selectAll(...) with string argument and no type parameters creates selection // with Group elements of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any' -let baseTypeElements: d3Selection.Selection = d3Selection.selectAll('div'); +const baseTypeElements: d3Selection.Selection = d3Selection.selectAll('div'); // Using selectAll() with string argument and type parameters creates selection // with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type HTMLElement with datum of type 'any' -let divElements: d3Selection.Selection = d3Selection.selectAll('div'); +const divElements: d3Selection.Selection = d3Selection.selectAll('div'); // Using selectAll(...) with node array argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined' -let baseTypeElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); -// let divElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); // fails, group elements types not of compatible for baseTypeElements +const baseTypeElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); +// fails, group elements types not of compatible for baseTypeElements +// let divElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); -let divElements3: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // element types match, but datum is of type 'any' as it cannot be inferred from .nodes() +// element types match, but datum is of type 'any' as it cannot be inferred from .nodes() +const divElements3: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // Using selectAll(...) with node array argument and type parameters creates selection // with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type 'null' with datum of type 'undefined' -let divElements4: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); +const divElements4: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // d3Selection.selectAll(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement @@ -146,12 +149,12 @@ let divElements4: d3Selection.Selection argument -let xSVGCircleElementList: NodeListOf = document.querySelectorAll('circle'); -let circleSelection: d3Selection.Selection = d3Selection.selectAll(xSVGCircleElementList); +const xSVGCircleElementList: NodeListOf = document.querySelectorAll('circle'); +const circleSelection: d3Selection.Selection = d3Selection.selectAll(xSVGCircleElementList); // selectAll(...) accepts HTMLCollection, HTMLCollectionOf<...> argument -let documentLinks: d3Selection.Selection = d3Selection.selectAll(document.links); +const documentLinks: d3Selection.Selection = d3Selection.selectAll(document.links); @@ -168,7 +171,7 @@ let documentLinks: d3Selection.Selection = d3Selection.select('svg'); +const svgEl: d3Selection.Selection = d3Selection.select('svg'); let firstG: d3Selection.Selection = svgEl.select('g'); // let firstG_2: d3Selection.Selection = svgEl.select('g'); // fails, parent element of selection does not change with .select(...) @@ -187,19 +190,19 @@ function svgGroupSelector(this: SVGSVGElement, d: SVGDatum, i: number, groups: S firstG = svgEl.select(svgGroupSelector); -firstG = svgEl.select(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +firstG = svgEl.select(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelector('g')!; // this of type SVGSVGElement by type inference }); -firstG = svgEl.select(function (d, i, g) { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: SVGSVGElement[] | d3Selection.ArrayLike = g; +firstG = svgEl.select(function(d, i, g) { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: SVGSVGElement[] | d3Selection.ArrayLike = g; console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement console.log('Width in datum:', d.width); // d is type of originating selection element Datum: SVGDatum if (g.length > 1) { @@ -246,19 +249,19 @@ function wrongSvgGroupSelectorAll(this: HTMLElement, d: SVGDatum, i: number, gro } // gElementsOldData = svgEl.selectAll(wrongSvgGroupSelectorAll); // fails, wrong this context -gElementsOldData = svgEl.selectAll(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +gElementsOldData = svgEl.selectAll(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); -gElementsOldData = svgEl.selectAll(function (d, i, g) { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: SVGSVGElement[] | d3Selection.ArrayLike = g; +gElementsOldData = svgEl.selectAll(function(d, i, g) { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: SVGSVGElement[] | d3Selection.ArrayLike = g; console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement console.log('Width in datum:', d.width); // type of d is SVGDatum if (g.length > 1) { @@ -277,9 +280,9 @@ gElementsOldData = svgEl.selectAll(function (d, i, g) elementsUnknownData = svgEl.selectAll(svgGroupSelectorAll); -elementsUnknownData = svgEl.selectAll(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +elementsUnknownData = svgEl.selectAll(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); @@ -288,13 +291,13 @@ elementsUnknownData = svgEl.selectAll(function () { // return this.querySelectorAll('a'); // }); -maybeG.selectAll(function (d, i, g) { - let that: SVGGElement | null = this; - // let that2: SVGGElement = this; // fails with strictNullChecks - // let that3: HTMLElement | null = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: Array | d3Selection.ArrayLike = g; +maybeG.selectAll(function(d, i, g) { + const that: SVGGElement | null = this; + // const that2: SVGGElement = this; // fails with strictNullChecks + // const that3: HTMLElement | null = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: Array | d3Selection.ArrayLike = g; return that ? that.querySelectorAll('circle') : []; }); @@ -319,12 +322,12 @@ let filterdGElements: d3Selection.Selection = g; +filterdGElements = gElementsOldData.filter(function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Element Id of DOM element: ', this.id); // this context SVGGElement if (g.length > 0) { console.log('Element Id of first DOM element in group: ', g[0].id); // group: Array @@ -341,11 +344,11 @@ filterdGElements2 = d3Selection.selectAll('.any-svg-type').filt // filterdGElements2 = d3Selection.selectAll('.any-type').filter('g'); // fails without using narrowing generic on filter method filterdGElements2 = d3Selection.selectAll('.any-svg-type').filter(function(){ - let that: SVGElement = this; + const that: SVGElement = this; return that.tagName === 'g' || that.tagName === 'G'; }); // filterdGElements2 = d3Selection.selectAll('.any-svg-type').filter(function(){ -// let that: SVGElement = this; +// const that: SVGElement = this; // return that.tagName === 'g'|| that.tagName === 'G'; // }); // fails without using narrowing generic on filter method @@ -385,27 +388,23 @@ circles = d3Selection.selectAll('circl .attr('stroke', 'blue'); // string circles = circles // re-assignment test chaining return-type - .attr('cx', function (d, i, g) { - let that: SVGGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGGElement[] | d3Selection.ArrayLike = g; + .attr('cx', function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (g.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array } return d.cx; // numeric return value }) - .attr('stroke', function (d) { - return d.color; // string return value - }); + .attr('stroke', d => d.color); // string return value divs = d3Selection.selectAll('div') .attr('contenteditable', false) // boolean - .attr('contenteditable', function () { - return false; // boolean return value - }); + .attr('contenteditable', () => false); // boolean return value // classed(...) Tests @@ -413,12 +412,12 @@ divs = divs .classed('success', true); divs = divs - .classed('zero-px-padding', function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: DivDatum = d; - let index: number = i; - let group: HTMLDivElement[] | d3Selection.ArrayLike = g; + .classed('zero-px-padding', function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: DivDatum = d; + const index: number = i; + const group: HTMLDivElement[] | d3Selection.ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement if (g.length > 0) { console.log('Alignment of first group element:', g[0].align); // group : Array @@ -436,23 +435,21 @@ divs = divs .style('color', 'green', 'important'); divs = divs - .style('padding', function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: DivDatum = d; - let index: number = i; - let group: HTMLDivElement[] | d3Selection.ArrayLike = g; + .style('padding', function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: DivDatum = d; + const index: number = i; + const group: HTMLDivElement[] | d3Selection.ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement if (g.length > 0) { console.log('Alignment of first group element:', g[0].align); // group : Array } return d.padding; // string return value }) - .style('hidden', function () { - return true; - }, null) // boolean return + test: priority = null - // .style('color', function () { return 'green'; }, 'test') // fails, test: invalid priority value - .style('color', function () { return 'green'; }, 'important'); // boolean return + test: priority = 'important'; + .style('hidden', () => true, null) // boolean return + test: priority = null + // .style('color', function() { return 'green'; }, 'test') // fails, test: invalid priority value + .style('color', () => 'green', 'important'); // boolean return + test: priority = 'important'; // property(...) Tests @@ -464,12 +461,12 @@ circles = circles }); // any circles = circles - .property('__hitchhikersguide__', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; + .property('__hitchhikersguide__', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (g.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array @@ -488,32 +485,28 @@ body = body .text(true); // boolean will be converted to string by D3 body = body - .text(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; + .text(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('Body background color: ', this.bgColor); // this context HTMLBodyElement return d.foo; // BodyDatum }) - .text(function (d) { - return 42; // number will be converted to string by D3 - }) - .text(function (d) { - return true; // boolean will be converted to string by D3 - }); + .text(d => 42) // number will be converted to string by D3 + .text(d => true); // boolean will be converted to string by D3 body = body .html('
42
'); body = body - .html(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; + .html(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; return '
Body Background Color: ' + this.bgColor + ', Foo Datum: ' + d.foo + '
'; // this context HTMLBodyElement, datum BodyDatum }); @@ -522,13 +515,13 @@ body = body // --------------------------------------------------------------------------------------- -let data: CircleDatum[] = [ +const data: CircleDatum[] = [ { nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo' }, { nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar' }, { nodeId: 'c3', cx: 30, cy: 30, r: 5, name: 'fooBar', label: 'Foo Bar' } ]; -let data2: CircleDatumAlternative[] = [ +const data2: CircleDatumAlternative[] = [ { nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo', color: 'seagreen' }, { nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar', color: 'midnightblue' }, { nodeId: 'c4', cx: 10, cy: 15, r: 10, name: 'newbie', label: 'Newbie', color: 'red' } @@ -538,7 +531,7 @@ let data2: CircleDatumAlternative[] = [ // Tests of Datum ----------------------------------------------------------------------- // TEST GETTER -let bodyDatum: BodyDatum = body.datum(); +const bodyDatum: BodyDatum = body.datum(); // TEST REMOVE DATUM body.datum(null); // removes datum, i.e. return type has group datum type 'undefined' @@ -555,18 +548,18 @@ newBodyDatum = body.datum({ newFoo: 'new foo' }).datum(); // inferred type // function-based -newBodyDatum = body.datum(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +newBodyDatum = body.datum(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement console.log('Old foo:', d.foo); // current data of type BodyDatum return { newFoo: 'new foo' }; }).datum(); // inferred type -// newBodyDatum = body.datum(function (d) { // fails, data type incompatible with return value type +// newBodyDatum = body.datum(function(d) { // fails, data type incompatible with return value type // console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement // return { newFoo: 'new foo' }; // }).datum(); // inferred type @@ -579,7 +572,7 @@ newBodyDatum = body.datum(function (d, i, g) { d3Selection.select('#svg-1') .select('g.circles-group') // first matching element only .datum(data2) - .classed('has-transform-property', function (d) { + .classed('has-transform-property', function(d) { console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); return this.transform !== undefined; }); @@ -589,12 +582,12 @@ d3Selection.select('#svg-1') d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain .select('g.circles-group') .datum(data2) // new data type inferred - .classed('has-transform-property', function (d, i, g) { - let that: SVGGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative[] = d; - let index: number = i; - let group: SVGGElement[] | d3Selection.ArrayLike = g; + .classed('has-transform-property', function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative[] = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); // CircleDatumAlternative type return this.transform !== undefined; }); @@ -604,7 +597,7 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la // d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain // .select('g.circles-group') // missing typing of selected DOM element for use in .classed(...) // .datum(data2) // new data type inferred -// .classed('has-transform-property', function (d) { +// .classed('has-transform-property', function(d) { // console.log('Color of first data element array', d.length > 0? d[0].color: 'Data array empty'); // CircleDatumAlternative type // return this.transform !== undefined; // }); @@ -614,12 +607,12 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain .select('g.circles-group') // irrelevant typing to get contextual typing in last step of chain .datum(data2) // new data type inferred - .classed('has-green-first-data-element', function (d, i, g) { - let that: d3Selection.BaseType = this; - // let that2: Element = this; // fails, type mismatch - let datum: CircleDatumAlternative[] = d; - let index: number = i; - let group: d3Selection.BaseType[] | d3Selection.ArrayLike = g; + .classed('has-green-first-data-element', function(d, i, g) { + const that: d3Selection.BaseType = this; + // const that2: Element = this; // fails, type mismatch + const datum: CircleDatumAlternative[] = d; + const index: number = i; + const group: d3Selection.BaseType[] | d3Selection.ArrayLike = g; return d.length > 0 && d[0].color === 'green'; }); @@ -627,12 +620,12 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la // Tests of Data Join -------------------------------------------------------------------- -let dimensions: SVGDatum = { +const dimensions: SVGDatum = { width: 500, height: 300 }; -let startCircleData: CircleDatumAlternative[] = [ +const startCircleData: CircleDatumAlternative[] = [ { nodeId: 'n1', name: 'node_1', @@ -652,7 +645,7 @@ let startCircleData: CircleDatumAlternative[] = [ color: 'slateblue' } ]; -let endCircleData: CircleDatumAlternative[] = [ +const endCircleData: CircleDatumAlternative[] = [ { nodeId: 'n1', name: 'node_1', @@ -683,8 +676,8 @@ let circles2: d3Selection.Selection('#svg2') .datum(dimensions) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }) + .attr('width', d => d.width) + .attr('height', d => d.height) .selectAll() // create empty Selection .data(startCircleData) // assign data for circles to be added (no previous circles) .enter() // obtain enter selection @@ -694,9 +687,9 @@ circles2 = d3Selection.select('#svg2') // Assign new data and use key(...) function for mapping circles2 = circles2 // returned update selection has the same type parameters as original selection, if data type is unchanged - .data(endCircleData, function (d) { return d.nodeId; }); + .data(endCircleData, d => d.nodeId); -// circles2.data(endCircleData, function (d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch +// circles2.data(endCircleData, function(d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch // ENTER-selection ----------------------------------------------------------------- @@ -706,27 +699,27 @@ let enterElements: d3Selection.Selection('circle') // enter selection with materialized DOM elements (svg circles) - .attr('cx', function (d) { return d.cx; }) - .attr('cy', function (d) { return d.cy; }) - .attr('r', function (d) { return d.r; }) - .style('stroke', function (d) { return d.color; }) - .style('fill', function (d) { return d.color; }); + .attr('cx', d => d.cx) + .attr('cy', d => d.cy) + .attr('r', d => d.r) + .style('stroke', d => d.color) + .style('fill', d => d.color); // EXIT-selection ---------------------------------------------------------------------- // tests exit(...) and remove() -let exitCircles = circles2.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' +const exitCircles = circles2.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' exitCircles - .style('opacity', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; + .style('opacity', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; console.log('Circle Radius exit node: ', this.r.baseVal.value); // this type is SVGCircleElement return d.color === 'green' ? 1 : 0; // data type as per .exit<...>() parameterization }) @@ -737,7 +730,7 @@ exitCircles // let exitCircles2 = circles2.exit(); // Note: Without explicit re-typing to the old data type, the data type default to '{}' // exitCircles2 -// .style('opacity', function (d) { +// .style('opacity', function(d) { // console.log('Circle Radius exit node: ', this.r.baseVal.value); // return d.color === 'green' ? 1 : 0; // fails, as data type is defaulted to {}. If datum access is required, this should trigger the thought to type .exit<...> // }); @@ -775,14 +768,14 @@ nMatrix = tr.data(); // i.e. matrix let td: d3Selection.Selection; td = tr.selectAll() - .data(function (d) { return d; }) // d : Array inferred (Array[4] of number per parent ) + .data(d => d) // d : Array inferred (Array[4] of number per parent ) .enter().append('td') - .text(function (d, i, g) { - let that: HTMLTableDataCellElement = this; - // let that2: Element = this; // fails, type mismatch - let datum: number = d; - let index: number = i; - let group: HTMLTableDataCellElement[] | d3Selection.ArrayLike = g; + .text(function(d, i, g) { + const that: HTMLTableDataCellElement = this; + // const that2: Element = this; // fails, type mismatch + const datum: number = d; + const index: number = i; + const group: HTMLTableDataCellElement[] | d3Selection.ArrayLike = g; console.log('Abbreviated text for object', this.abbr); // this-type HTMLTableDataCellElement (demonstration only) return d; }); // d:number inferred @@ -791,7 +784,7 @@ nRow = td.data(); // flattened matrix (Array[16] of number) // SCENARIO 2 - Completely inferred types, when there is no need for `this` typings -let tr2 = d3Selection.select('body') +const tr2 = d3Selection.select('body') .append('table') .selectAll('tr') .data(matrix) @@ -799,10 +792,10 @@ let tr2 = d3Selection.select('body') nMatrix = tr2.data(); // i.e. matrix -let td2 = tr2.selectAll('td') - .data(function (d) { return d; }) // d : Array inferred (Array[4] of number per parent ) +const td2 = tr2.selectAll('td') + .data(d => d) // d : Array inferred (Array[4] of number per parent ) .enter().append('td') - .text(function (d) { return d; }); // d:number inferred + .text(d => d); // d:number inferred nRow = td2.data(); // flattened matrix (Array[16] of number) @@ -823,12 +816,12 @@ newDiv2 = body.append('div'); newDiv2 = body.append(d3Selection.creator('div')); // newDiv2 = body.append(d3Selection.creator('div')); // fails, as creator returns BaseType element, but HTMLDivElement is expected. -newDiv2 = body.append(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +newDiv2 = body.append(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('Body element foo property: ', d.foo); // data of type BodyDatum return this.ownerDocument.createElement('div'); // this-type HTMLBodyElement }); @@ -850,23 +843,23 @@ newParagraph = body.insert('p'); // Two arguments; the first can be string, selection , or a -const typeValueFunction = function ( +const typeValueFunction = function( this: HTMLBodyElement, d: BodyDatum, i: number, g: HTMLBodyElement[] | d3Selection.ArrayLike ) { return this.ownerDocument.createElement('p'); // this-type HTMLParagraphElement -} +}; -const beforeValueFunction = function ( +const beforeValueFunction = function( this: HTMLBodyElement, d: BodyDatum, i: number, g: HTMLBodyElement[] | d3Selection.ArrayLike ) { - return this.children[0]; -} + return this.children[0]; +}; let newParagraph2: d3Selection.Selection; @@ -887,9 +880,7 @@ newParagraph2 = body.insert(typeValueFunction); // sort(...) ----------------------------------------------------------------------------- // NB: Return new selection of same type -circles2 = circles2.sort(function (a, b) { - return (b.r - a.r); -}); +circles2 = circles2.sort((a, b) => b.r - a.r); // order(...) ---------------------------------------------------------------------------- @@ -911,27 +902,27 @@ circles2 = circles2.lower(); // --------------------------------------------------------------------------------------- // empty() ------------------------------------------------------------------------------- -let emptyFlag = gElementsOldData.empty(); +const emptyFlag = gElementsOldData.empty(); // node() and nodes() -------------------------------------------------------------------- -let bodyNode: HTMLBodyElement | null= body.node(); +const bodyNode: HTMLBodyElement | null = body.node(); -let gElementsNodes: SVGGElement[] = gElementsOldData.nodes(); +const gElementsNodes: SVGGElement[] = gElementsOldData.nodes(); // size() -------------------------------------------------------------------------------- -let size: number = gElementsOldData.size(); +const size: number = gElementsOldData.size(); // each() ------------------------------------------------------------------------------- // returns 'this' selection -circles = circles.each(function (d, i, g) { // check chaining return type by re-assigning - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; +circles = circles.each(function(d, i, g) { // check chaining return type by re-assigning + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; if (this.r.baseVal.value < d.r) { // this of type SVGCircleElement, datum of type CircleDatumAlternative d3Selection.select(this).attr('r', d.r); } @@ -942,8 +933,8 @@ circles = circles.each(function (d, i, g) { // check chaining return type by re function enforceMinRadius(selection: d3Selection.Selection, minRadius: number): void { - selection.attr('r', function (d) { - let r: number = +d3Selection.select(this).attr('r'); + selection.attr('r', function(d) { + const r: number = +d3Selection.select(this).attr('r'); return Math.max(r, minRadius); }); @@ -952,11 +943,11 @@ function enforceMinRadius(selection: d3Selection.Selection):void { +// circles.call(function(selection: d3Selection.Selection):void { // // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement // }); -// circles.call(function (selection: d3Selection.Selection):void { +// circles.call(function(selection: d3Selection.Selection):void { // // fails, group datum types of selection not compatible: CircleDatumAlternative v DivDatum // }); @@ -969,12 +960,12 @@ circles = circles.call(enforceMinRadius, 40); // check chaining return type by r let listener: undefined | ((this: HTMLBodyElement, datum: BodyDatum, index: number, group: HTMLBodyElement[] | ArrayLike) => void); -body = body.on('click', function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | ArrayLike = g; +body = body.on('click', function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | ArrayLike = g; console.log('onclick print body background color: ', this.bgColor); // HTMLBodyElement console.log('onclick print "foo" datum property: ', d.foo); // BodyDatum type }); @@ -993,7 +984,7 @@ body = body.on('click', null); // check chaining return type by re-assigning // dispatch(...) ------------------------------------------------------------------------- -let fooEventParam: d3Selection.CustomEventParameters = { +const fooEventParam: d3Selection.CustomEventParameters = { cancelable: true, bubbles: true, detail: [1, 2, 3, 4] @@ -1002,12 +993,12 @@ let fooEventParam: d3Selection.CustomEventParameters = { // returns 'this' selection body = body.dispatch('fooEvent', fooEventParam); // re-assign for chaining test; -body = body.dispatch('fooEvent', function (d, i, g) { // re-assign for chaining test; - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +body = body.dispatch('fooEvent', function(d, i, g) { // re-assign for chaining test; + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; let eParam: d3Selection.CustomEventParameters; console.log('fooEvent dispatch body background color', this.bgColor); eParam = { @@ -1030,17 +1021,17 @@ interface SuccessEvent { team: string; sourceEvent?: any; } -let successEvent = { type: 'wonEuro2016', team: 'Island' }; +const successEvent = { type: 'wonEuro2016', team: 'Island' }; let customListener: (this: HTMLBodyElement, finalOpponent: string) => string; -customListener = function (finalOpponent) { - let e = d3Selection.event; +customListener = finalOpponent => { + const e = d3Selection.event; return e.team + ' defeated ' + finalOpponent + ' in the EURO 2016 Cup. Who would have thought!!!'; }; -let resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); +const resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // let result = d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in call // let resultValue: number = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types @@ -1051,10 +1042,10 @@ let resultText: string = d3Selection.customEvent(successEvent, customListener, b // mouse() --------------------------------------------------------------------------------- let position: [number, number] | null; -let svg: SVGSVGElement = d3Selection.select('svg').node()!; -let g: SVGGElement = d3Selection.select('g').node()!; -let h: HTMLElement = d3Selection.select('div').node()!; -let changedTouches: TouchList = new TouchList(); // dummy +const svg: SVGSVGElement = d3Selection.select('svg').node()!; +const g: SVGGElement = d3Selection.select('g').node()!; +const h: HTMLElement = d3Selection.select('div').node()!; +const changedTouches: TouchList = new TouchList(); // dummy position = d3Selection.mouse(svg); position = d3Selection.mouse(g); @@ -1084,9 +1075,9 @@ positions = d3Selection.touches(h, changedTouches); // Tests of Local // --------------------------------------------------------------------------------------- -let xElement: Element = d3Selection.select('foo').node()!; -let foo: d3Selection.Local = d3Selection.local(); -let propName: string = foo.toString(); +let xElement: Element = d3Selection.select('foo').node()!; +const foo: d3Selection.Local = d3Selection.local(); +const propName: string = foo.toString(); // direct set & get on Local object xElement = foo.set(xElement, [1, 2, 3]); @@ -1104,7 +1095,7 @@ foo.remove(xElement); // Tests of Namespace // --------------------------------------------------------------------------------------- -let predefinedNamespaces: d3Selection.NamespaceMap = d3Selection.namespaces; +const predefinedNamespaces: d3Selection.NamespaceMap = d3Selection.namespaces; const svgNamespace: string = predefinedNamespaces['svg']; diff --git a/d3-selection/index.d.ts b/d3-selection/index.d.ts index 1d0ab9472c..49cd141dfa 100644 --- a/d3-selection/index.d.ts +++ b/d3-selection/index.d.ts @@ -820,7 +820,8 @@ interface Selection): this; diff --git a/d3-shape/d3-shape-tests.ts b/d3-shape/d3-shape-tests.ts index beec6c84c8..204f1e7eb1 100644 --- a/d3-shape/d3-shape-tests.ts +++ b/d3-shape/d3-shape-tests.ts @@ -16,7 +16,6 @@ import { path } from 'd3-path'; let context: CanvasRenderingContext2D | null = document.querySelector('canvas')!.getContext('2d'); let num: number; -let pathString: string; let pathStringMaybe: string | null; // ----------------------------------------------------------------------------------- @@ -31,7 +30,7 @@ interface ArcDatum { pAngle: number; } -let arcDefaultDatum: d3Shape.DefaultArcObject = { +const arcDefaultDatum: d3Shape.DefaultArcObject = { innerRadius: 40, outerRadius: 60, startAngle: 0, @@ -39,7 +38,7 @@ let arcDefaultDatum: d3Shape.DefaultArcObject = { padAngle: 0.03 }; -let arcDatum: ArcDatum = { +const arcDatum: ArcDatum = { iRadius: 40, oRadius: 60, sAngle: 0, @@ -52,7 +51,7 @@ let accessorArcDatumNumberOrNull: ((this: any, d: ArcDatum, ...args: any[]) => n // DefaultArcObject interface ======================================================== -let defaultArcObject: d3Shape.DefaultArcObject = { +const defaultArcObject: d3Shape.DefaultArcObject = { innerRadius: 0, outerRadius: 100, startAngle: 0, @@ -86,7 +85,7 @@ svgArc = svgArc.context(null); // use as path string generator for SVG canvasArc = canvasArc.innerRadius(40); -svgArc = svgArc.innerRadius(function (d) { +svgArc = svgArc.innerRadius(d => { return d.iRadius; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.innerRadius(); @@ -95,7 +94,7 @@ accessorArcDatumNumber = svgArc.innerRadius(); canvasArc = canvasArc.outerRadius(60); -svgArc = svgArc.outerRadius(function (d) { +svgArc = svgArc.outerRadius(d => { return d.oRadius; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.outerRadius(); @@ -104,7 +103,7 @@ accessorArcDatumNumber = svgArc.outerRadius(); canvasArc = canvasArc.cornerRadius(4); -svgArc = svgArc.cornerRadius(function (d) { +svgArc = svgArc.cornerRadius(d => { return d.oRadius / 10; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.cornerRadius(); @@ -113,7 +112,7 @@ accessorArcDatumNumber = svgArc.cornerRadius(); canvasArc = canvasArc.startAngle(0); -svgArc = svgArc.startAngle(function (d) { +svgArc = svgArc.startAngle(d => { return d.sAngle; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.startAngle(); @@ -122,7 +121,7 @@ accessorArcDatumNumber = svgArc.startAngle(); canvasArc = canvasArc.endAngle(Math.PI / 2); -svgArc = svgArc.endAngle(function (d) { +svgArc = svgArc.endAngle(d => { return d.eAngle; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.endAngle(); @@ -131,7 +130,7 @@ accessorArcDatumNumber = svgArc.endAngle(); canvasArc = canvasArc.padAngle(0); -svgArc = svgArc.padAngle(function (d) { +svgArc = svgArc.padAngle(d => { return d.pAngle; // datum type is ArcDatum }); accessorArcDatumNumber = svgArc.padAngle(); @@ -140,7 +139,7 @@ accessorArcDatumNumber = svgArc.padAngle(); canvasArc = canvasArc.padRadius(0); -svgArc = svgArc.padRadius(function (d) { +svgArc = svgArc.padRadius(d => { return Math.sqrt(d.iRadius * d.iRadius + d.oRadius * d.oRadius); }); @@ -153,7 +152,7 @@ accessorArcDatumNumberOrNull = svgArc.padRadius(); // centroid(...) --------------------------------------------------------------------- -let centroid: [number, number] = svgArc.centroid(arcDatum); +const centroid: [number, number] = svgArc.centroid(arcDatum); // centroid = svgArc.centroid(arcDefaultDatum); // fails, wrong datum type // generate arc ---------------------------------------------------------------------- @@ -164,9 +163,9 @@ canvasArc(arcDefaultDatum); // use with svg -let pArc: Selection = select('.arc-paths'); // mock -let wrongArc1: Selection = select('.arc-paths'); // mock -let wrongArc2: Selection = select('.arc-paths'); // mock +const pArc: Selection = select('.arc-paths'); // mock +const wrongArc1: Selection = select('.arc-paths'); // mock +const wrongArc2: Selection = select('.arc-paths'); // mock pArc.attr('d', svgArc); // wrongArc1.attr('d', svgArc); // fails, incompatible this contexts @@ -192,10 +191,10 @@ class Arcer { this.cornerRadius = 3; this.arc = d3Shape.arc() - .innerRadius(function (d) { + .innerRadius(d => { return Math.min(d.innerRadius, this.innerRadius); }) - .outerRadius(function (d) { + .outerRadius(d => { return Math.min(d.outerRadius, this.outerRadius); }) .cornerRadius(this.cornerRadius) @@ -217,7 +216,7 @@ class Arcer { } } -let arcer = new Arcer(100, 120); +const arcer = new Arcer(100, 120); pathStringMaybe = arcer.getPathString(); pathStringMaybe = arcer.getPathString({ innerRadius: 10, outerRadius: 20 }); @@ -237,7 +236,7 @@ let accessorPieDatumNumber: (this: any, data: PieDatum[], ...args: any[]) => num // PieArcDatum interface ============================================================= -let pieArcObject: d3Shape.PieArcDatum = { +const pieArcObject: d3Shape.PieArcDatum = { data: { val: 10, name: "Segment 1" @@ -249,7 +248,7 @@ let pieArcObject: d3Shape.PieArcDatum = { padAngle: 0 }; -let pieDatum: PieDatum = pieArcObject.data; +const pieDatum: PieDatum = pieArcObject.data; num = pieArcObject.value; num = pieArcObject.index; num = pieArcObject.startAngle; @@ -274,7 +273,7 @@ defaultPieValueAccessor = defaultPie.value(); let pieValueAccessor: (d: PieDatum, i?: number, data?: PieDatum[]) => number; -pie = pie.value(function (d, i, data) { +pie = pie.value((d, i, data) => { console.log(data.length > 0 ? data[0].val : 'no data'); // data type is Array return d.val; // d type is PieDatum }); @@ -286,7 +285,7 @@ pieValueAccessor = pie.value(); let pieSorter: ((a: PieDatum, b: PieDatum) => number) | null; -pie = pie.sort(function (a, b) { +pie = pie.sort((a, b) => { return b.val - a.val; // type of a and b is PieDatum }); @@ -298,7 +297,7 @@ pie = pie.sort(null); let pieValuesSorter: ((a: number, b: number) => number) | null; -pie = pie.sortValues(function (a, b) { +pie = pie.sortValues((a, b) => { return b - a; // type of a and b is number }); @@ -310,7 +309,7 @@ pie = pie.sortValues(null); defaultPie = defaultPie.startAngle(0); -pie = pie.startAngle(function (d) { +pie = pie.startAngle(d => { console.log(d.length > 0 ? d[0].val : 'no data'); // data type is Array return 0; }); @@ -320,7 +319,7 @@ accessorPieDatumNumber = pie.startAngle(); defaultPie = defaultPie.endAngle(2 * Math.PI); -pie = pie.endAngle(function (d) { +pie = pie.endAngle(d => { console.log(d.length > 0 ? d[0].val : 'no data'); // data type is Array return 2 * Math.PI; }); @@ -330,7 +329,7 @@ accessorPieDatumNumber = pie.endAngle(); defaultPie = defaultPie.padAngle(0.03); -pie = pie.padAngle(function (d) { +pie = pie.padAngle(d => { console.log(d.length > 0 ? d[0].val : 'no data'); // data type is Array return 0.03; @@ -343,7 +342,7 @@ let defaultPieChart: Array>; defaultPieChart = defaultPie([20, 10, 30, 40]); -let pieData: PieDatum[] = [ +const pieData: PieDatum[] = [ { name: 'John', val: 20 }, { name: 'Jill', val: 10 }, { name: 'Rodrigo', val: 30 } @@ -396,7 +395,7 @@ line = line.context(null); // use as path string generator for SVG defaultLine = defaultLine.x(30); -line = line.x(function (d, t, data) { +line = line.x((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X-Coordinate of first point: ', data[0].x); // data type is Array return d.x; // d type is LineDatum @@ -408,7 +407,7 @@ lineXYAccessorFn = line.x(); defaultLine = defaultLine.y(10); -line = line.y(function (d, t, data) { +line = line.y((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y-Coordinate of first point: ', data[0].y); // data type is Array return d.y; // d type is LineDatum @@ -420,7 +419,7 @@ lineXYAccessorFn = line.y(); defaultLine = defaultLine.defined(true); -line = line.defined(function (d, t, data) { +line = line.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y-Coordinate of first point: ', data[0].y); // data type is Array return !d.missing; // d type is LineDatum @@ -440,13 +439,13 @@ let currentCurveFactory: d3Shape.CurveFactory | d3Shape.CurveFactoryLineOnly = l defaultLine([[10, 10], [20, 10], [20, 20]]); -let lineData: LineDatum[] = [ +const lineData: LineDatum[] = [ { x: 10, y: 10, missing: false }, { x: 20, y: 10, missing: false }, { x: 20, y: 20, missing: false } ]; -let linePathStringMaybe: string | null = line(lineData); +const linePathStringMaybe: string | null = line(lineData); // radialLine(...) create Line generator ===================================================== @@ -468,7 +467,7 @@ radialLine = radialLine.context(null); // use as path string generator for SVG defaultRadialLine = defaultRadialLine.angle(Math.PI); -radialLine = radialLine.angle(function (d, t, data) { +radialLine = radialLine.angle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Angle of first point: ', data[0].angle); // data type is Array return d.angle; // d type is RadialLineDatum @@ -480,7 +479,7 @@ radialLineAngRAccessorFn = radialLine.angle(); defaultRadialLine = defaultRadialLine.radius(30); -radialLine = radialLine.radius(function (d, t, data) { +radialLine = radialLine.radius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Angle of first point: ', data[0].angle); // data type is Array return d.radius; // d type is RadialLineDatum @@ -492,7 +491,7 @@ radialLineAngRAccessorFn = radialLine.radius(); defaultRadialLine = defaultRadialLine.defined(true); -radialLine = radialLine.defined(function (d, t, data) { +radialLine = radialLine.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Angle of first point: ', data[0].angle); // data type is Array return !d.missing; // d type is RadialLineDatum @@ -512,13 +511,13 @@ currentCurveFactory = radialLine.curve(); defaultRadialLine([[10, 10], [20, 10], [20, 20]]); -let radialLineData: RadialLineDatum[] = [ +const radialLineData: RadialLineDatum[] = [ { angle: 0, radius: 10, missing: false }, { angle: Math.PI / 2, radius: 20, missing: false }, { angle: 2 * Math.PI, radius: 10, missing: false } ]; -let radialLinePathStringMaybe: string | null = radialLine(radialLineData); +const radialLinePathStringMaybe: string | null = radialLine(radialLineData); // ----------------------------------------------------------------------------------- @@ -569,7 +568,7 @@ area = area.context(null); // use as path string generator for SVG defaultArea = defaultArea.x(30); -area = area.x(function (d, t, data) { +area = area.x((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X0-Coordinate of first point: ', data[0].x0); // data type is Array return d.x0; // d type is AreaDatum @@ -581,7 +580,7 @@ areaXYAccessorFn = area.x(); defaultArea = defaultArea.x0(30); -area = area.x0(function (d, t, data) { +area = area.x0((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X0-Coordinate of first point: ', data[0].x0); // data type is Array return d.x0; // d type is AreaDatum @@ -593,7 +592,7 @@ areaXYAccessorFn = area.x0(); defaultArea = defaultArea.x1(30); -area = area.x1(function (d, t, data) { +area = area.x1((d, t, data) => { console.log('Number of Points: ', data.length); console.log('X1-Coordinate of first point: ', data[0].x1); // data type is Array return d.x1; // d type is AreaDatum @@ -605,7 +604,7 @@ areaXYAccessorFnMaybe = area.x1(); defaultArea = defaultArea.y(10); -area = area.y(function (d, t, data) { +area = area.y((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y0-Coordinate of first point: ', data[0].y0); // data type is Array return d.y0; // d type is AreaDatum @@ -617,7 +616,7 @@ areaXYAccessorFn = area.y(); defaultArea = defaultArea.y0(10); -area = area.y0(function (d, t, data) { +area = area.y0((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y0-Coordinate of first point: ', data[0].y0); // data type is Array return d.y0; // d type is AreaDatum @@ -629,7 +628,7 @@ areaXYAccessorFn = area.y0(); defaultArea = defaultArea.y1(10); -area = area.y1(function (d, t, data) { +area = area.y1((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y1-Coordinate of first point: ', data[0].y1); // data type is Array return d.y1; // d type is AreaDatum @@ -641,7 +640,7 @@ areaXYAccessorFnMaybe = area.y1(); defaultArea = defaultArea.defined(true); -area = area.defined(function (d, t, data) { +area = area.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Y0-Coordinate of first point: ', data[0].y0); // data type is Array return !d.missing; // d type is AreaDatum @@ -662,13 +661,13 @@ currentCurveFactory = area.curve(); defaultArea([[10, 10], [20, 10], [20, 20]]); -let areaData: AreaDatum[] = [ +const areaData: AreaDatum[] = [ { x0: 10, y0: 10, x1: 10, y1: 30, missing: false }, { x0: 20, y0: 20, x1: 20, y1: 40, missing: false }, { x0: 30, y0: 30, x1: 30, y1: 30, missing: false } ]; -let areaPathStringMaybe: string | null = area(areaData); +const areaPathStringMaybe: string | null = area(areaData); // Get Line Generators from Area generator ======================================================== @@ -699,7 +698,7 @@ radialArea = radialArea.context(null); // use as path string generator for SVG defaultRadialArea = defaultRadialArea.angle(Math.PI); -radialArea = radialArea.angle(function (d, t, data) { +radialArea = radialArea.angle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Start angle of first point: ', data[0].startAngle); // data type is Array return d.startAngle; // d type is RadialAreaDatum @@ -711,7 +710,7 @@ radialAreaAngRAccessorFn = radialArea.angle(); defaultRadialArea = defaultRadialArea.startAngle(Math.PI); -radialArea = radialArea.startAngle(function (d, t, data) { +radialArea = radialArea.startAngle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Start angle of first point: ', data[0].startAngle); // data type is Array return d.startAngle; // d type is RadialAreaDatum @@ -723,7 +722,7 @@ radialAreaAngRAccessorFn = radialArea.startAngle(); defaultRadialArea = defaultRadialArea.endAngle(Math.PI); -radialArea = radialArea.endAngle(function (d, t, data) { +radialArea = radialArea.endAngle((d, t, data) => { console.log('Number of Points: ', data.length); console.log('End angle of first point: ', data[0].endAngle); // data type is Array return d.endAngle; // d type is RadialAreaDatum @@ -735,7 +734,7 @@ radialAreaAngRAccessorFnMaybe = radialArea.endAngle(); defaultRadialArea = defaultRadialArea.radius(10); -radialArea = radialArea.radius(function (d, t, data) { +radialArea = radialArea.radius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Inner radius of first point: ', data[0].innerRadius); // data type is Array return d.innerRadius; // d type is RadialAreaDatum @@ -747,7 +746,7 @@ radialAreaAngRAccessorFn = radialArea.radius(); defaultRadialArea = defaultRadialArea.innerRadius(10); -radialArea = radialArea.innerRadius(function (d, t, data) { +radialArea = radialArea.innerRadius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Inner radius of first point: ', data[0].innerRadius); // data type is Array return d.innerRadius; // d type is RadialAreaDatum @@ -759,7 +758,7 @@ radialAreaAngRAccessorFn = radialArea.innerRadius(); defaultRadialArea = defaultRadialArea.outerRadius(20); -radialArea = radialArea.outerRadius(function (d, t, data) { +radialArea = radialArea.outerRadius((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Outer radius of first point: ', data[0].outerRadius); // data type is Array return d.outerRadius; // d type is RadialAreaDatum @@ -771,7 +770,7 @@ radialAreaAngRAccessorFnMaybe = radialArea.outerRadius(); defaultRadialArea = defaultRadialArea.defined(true); -radialArea = radialArea.defined(function (d, t, data) { +radialArea = radialArea.defined((d, t, data) => { console.log('Number of Points: ', data.length); console.log('Inner radius of first point: ', data[0].innerRadius); // data type is Array return !d.missing; // d type is RadialAreaDatum @@ -792,13 +791,13 @@ currentCurveFactory = radialArea.curve(); defaultRadialArea([[10, 10], [20, 10], [20, 20]]); -let radialAreaData: RadialAreaDatum[] = [ +const radialAreaData: RadialAreaDatum[] = [ { startAngle: 0, innerRadius: 10, endAngle: 0, outerRadius: 30, missing: false }, { startAngle: Math.PI / 2, innerRadius: 20, endAngle: Math.PI / 2, outerRadius: 40, missing: false }, { startAngle: Math.PI, innerRadius: 30, endAngle: Math.PI, outerRadius: 30, missing: false } ]; -let radialAreaPathStringMaybe: string | null = radialArea(radialAreaData); +const radialAreaPathStringMaybe: string | null = radialArea(radialAreaData); // Get RadialLine Generators from RadialArea generator ======================================================== @@ -818,7 +817,7 @@ areaRadialLineGenerator = radialArea.lineOuterRadius(); let lineOnlyGenerator: d3Shape.CurveGeneratorLineOnly; -let lineOnlyFactory: d3Shape.CurveFactoryLineOnly = d3Shape.curveBundle; +const lineOnlyFactory: d3Shape.CurveFactoryLineOnly = d3Shape.curveBundle; lineOnlyGenerator = lineOnlyFactory(path()); lineOnlyGenerator = lineOnlyFactory(context!); // force context to be non-null with post-fix for mock @@ -925,7 +924,7 @@ interface SymbolDatum { let customSymbol: d3Shape.SymbolType; customSymbol = { - draw: function (context: CanvasPathMethods, size: number): void { + draw(context: CanvasPathMethods, size: number): void { // draw custom symbol using canvas path methods } }; @@ -955,7 +954,7 @@ svgSymbol = svgSymbol.context(null); // use as path string generator for SVG canvasSymbol = canvasSymbol.size(30); -svgSymbol = svgSymbol.size(function (d) { +svgSymbol = svgSymbol.size(d => { return d.size; // datum type is SymbolDatum }); @@ -966,7 +965,7 @@ sizeAccessorFn = svgSymbol.size(); canvasSymbol = canvasSymbol.type(d3Shape.symbolDiamond); -svgSymbol = svgSymbol.type(function (d) { +svgSymbol = svgSymbol.type(d => { let t: d3Shape.SymbolType; switch (d.type) { // datum type is SymbolDatum case 'circle': @@ -990,14 +989,14 @@ typeAccessorFn = svgSymbol.type(); // use with canvas canvasSymbol(); -let symbolDatum: SymbolDatum = { +const symbolDatum: SymbolDatum = { size: 30, type: 'circle' }; -let pSymbol: Selection = select('.symbol-path'); // mock -let wrongSymbol1: Selection = select('.symbol-path'); // mock -let wrongSymbol2: Selection = select('.symbol-path'); // mock +const pSymbol: Selection = select('.symbol-path'); // mock +const wrongSymbol1: Selection = select('.symbol-path'); // mock +const wrongSymbol2: Selection = select('.symbol-path'); // mock pSymbol.attr('d', svgSymbol); // wrongSymbol1.attr('d', svgSymbol); // fails, incompatible this contexts @@ -1023,10 +1022,10 @@ class Symbolizer { break; } this.symbol = d3Shape.symbol() - .size(function (this: Symbolizer, d?: SymbolDatum) { + .size(function(this: Symbolizer, d?: SymbolDatum) { return d ? d.size : this.size; }) - .type(function (this: Symbolizer, d?: SymbolDatum) { + .type(function(this: Symbolizer, d?: SymbolDatum) { let type = this.type; if (d && d.type) { switch (d.type) { @@ -1052,7 +1051,7 @@ class Symbolizer { } } -let sym = new Symbolizer(100, 'square'); +const sym = new Symbolizer(100, 'square'); pathStringMaybe = sym.getPathString(); pathStringMaybe = sym.getPathString({ size: 10, type: 'circle' }); @@ -1060,7 +1059,7 @@ pathStringMaybe = sym.getPathString({ size: 10, type: 'circle' }); // Test pre-fab symbols =============================================================== -let symbolArray: d3Shape.SymbolType[] = d3Shape.symbols; +const symbolArray: d3Shape.SymbolType[] = d3Shape.symbols; customSymbol = d3Shape.symbolCircle; customSymbol = d3Shape.symbolCross; @@ -1087,13 +1086,13 @@ interface StackKey { let key: StackKey; -let keys: StackKey[] = [ +const keys: StackKey[] = [ { name: 'bananas', label: 'Bananas' }, { name: 'apples', label: 'Apples' }, { name: 'oranges', label: 'Oranges' } ]; -let stackData: StackDatum[] = [ +const stackData: StackDatum[] = [ { values: { bananas: 10, apples: 20, oranges: 10 } }, { values: { bananas: 10, apples: 25, oranges: 0 } }, { values: { bananas: 20, apples: 20, oranges: 30 } }, @@ -1118,7 +1117,7 @@ overlyComplicatedStack = d3Shape.stack(); defaultStack = defaultStack.keys(['bananas', 'apples', 'oranges']); -overlyComplicatedStack = overlyComplicatedStack.keys(function (data: StackDatum[], keys: StackKey[]) { +overlyComplicatedStack = overlyComplicatedStack.keys((data: StackDatum[], keys: StackKey[]) => { return keys; }); @@ -1129,7 +1128,7 @@ keysAccessor = overlyComplicatedStack.keys(); defaultStack = defaultStack.value(30); -overlyComplicatedStack = overlyComplicatedStack.value(function (d, key, j, data) { +overlyComplicatedStack = overlyComplicatedStack.value((d, key, j, data) => { return d.values[key.name]; }); @@ -1172,7 +1171,7 @@ seriesArray = overlyComplicatedStack(stackData, keys); // Test SeriesPoint and Series interfaces ============================================ -let series: d3Shape.Series = seriesArray[0]; +const series: d3Shape.Series = seriesArray[0]; let seriesPoint: d3Shape.SeriesPoint; seriesPoint = series[0]; key = series.key; @@ -1187,7 +1186,7 @@ seriesDatum = seriesPoint.data; // Test stack orders =============================================================== let order: number[]; -let seriesAnyAny: d3Shape.Series = seriesArray[0]; +const seriesAnyAny: d3Shape.Series = seriesArray[0]; order = d3Shape.stackOrderAscending(seriesAnyAny); order = d3Shape.stackOrderDescending(seriesAnyAny); diff --git a/d3-shape/index.d.ts b/d3-shape/index.d.ts index 3292eae937..367a9dee2b 100644 --- a/d3-shape/index.d.ts +++ b/d3-shape/index.d.ts @@ -371,11 +371,15 @@ export interface PieArcDatum { */ index: number; /** - * The start angle of the arc. If the pie generator was configured to be used for the arc generator, than the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * The start angle of the arc. + * If the pie generator was configured to be used for the arc generator, + * then the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. */ startAngle: number; /** - * The end angle of the arc. If the pie generator was configured to be used for the arc generator, than the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. + * The end angle of the arc. + * If the pie generator was configured to be used for the arc generator, + * then the units are in radians with 0 at -y (12 o’clock) and positive angles proceeding clockwise. */ endAngle: number; /** @@ -1160,7 +1164,8 @@ export interface Area { * * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. * When an area is generated, the defined accessor will be invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. - * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. * As a result, the generated area may have several discrete segments. * @@ -1176,8 +1181,10 @@ export interface Area { * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. * * The default accessor for defined returns a constant boolean value of true, thus assumes that the input data is always defined. - * When an area is generated, the defined accessor will be invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. - * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. + * When an area is generated, the defined accessor will be invoked for each element in the input data array, + * being passed the element d, the index i, and the array data as three arguments. + * If the given element is defined (i.e., if the defined accessor returns a truthy value for this element), + * the x0, x1, y0 and y1 accessors will subsequently be evaluated and the point will be added to the current area segment. * Otherwise, the element will be skipped, the current area segment will be ended, and a new area segment will be generated for the next defined point. * As a result, the generated area may have several discrete segments. * @@ -2095,7 +2102,8 @@ export interface Series extends Array> { /** * A stack generator. * - * Some shape types can be stacked, placing one shape adjacent to another. For example, a bar chart of monthly sales might be broken down into a multi-series bar chart by product category, stacking bars vertically. + * Some shape types can be stacked, placing one shape adjacent to another. + * For example, a bar chart of monthly sales might be broken down into a multi-series bar chart by product category, stacking bars vertically. * This is equivalent to subdividing a bar chart by an ordinal dimension (such as product category) and applying a color encoding. * * Stacked charts can show overall value and per-category value simultaneously; however, it is typically harder to compare across categories, as only the bottom layer of the stack is aligned. @@ -2140,7 +2148,8 @@ export interface Stack { * A series (layer) is generated for each key. Keys are typically strings, but they may be arbitrary values. * The series’ key is passed to the value accessor, along with each data point, to compute the point’s value. * - * @param keys An accessor function returning the array of keys. The accessor function is invoked with the "this" context of the Stack generator and passed the same arguments passed into the generator. + * @param keys An accessor function returning the array of keys. + * The accessor function is invoked with the "this" context of the Stack generator and passed the same arguments passed into the generator. */ keys(keys: (this: This, data: Datum[], ...args: any[]) => Key[]): this; @@ -2208,7 +2217,8 @@ export interface Stack { /** * Sets the offset accessor to the specified function and returns this stack generator. * - * @param offset A function which is passed the generated series array and the order index array. The offset function is then responsible for updating the lower and upper values in the series array to layout the stack. + * @param offset A function which is passed the generated series array and the order index array. + * The offset function is then responsible for updating the lower and upper values in the series array to layout the stack. */ offset(offset: (series: Series, order: number[]) => void): this; diff --git a/d3-transition/d3-transition-tests.ts b/d3-transition/d3-transition-tests.ts index 1feeabf042..c2917aaf94 100644 --- a/d3-transition/d3-transition-tests.ts +++ b/d3-transition/d3-transition-tests.ts @@ -39,12 +39,12 @@ interface CircleDatum { color: string; } -let dimensions: SVGDatum = { +const dimensions: SVGDatum = { width: 500, height: 300 }; -let startCircleData: CircleDatum[] = [ +const startCircleData: CircleDatum[] = [ { nodeId: 'n1', name: 'node_1', @@ -65,7 +65,7 @@ let startCircleData: CircleDatum[] = [ } ]; -let endCircleData: CircleDatum[] = [ +const endCircleData: CircleDatum[] = [ { nodeId: 'n1', name: 'node_1', @@ -97,33 +97,33 @@ let circles: Selection; circles = select('svg') .datum(dimensions) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }) + .attr('width', d => d.width) + .attr('height', d => d.height) .selectAll() .data(startCircleData) .enter() .append('circle') - .attr('cx', function (d) { return d.cx; }) - .attr('cy', function (d) { return d.cy; }) - .attr('r', function (d) { return d.r; }) - .style('stroke', function (d) { return d.color; }) - .style('fill', function (d) { return d.color; }); + .attr('cx', d => d.cx) + .attr('cy', d => d.cy) + .attr('r', d => d.r) + .style('stroke', d => d.color) + .style('fill', d => d.color); circles = circles - .data(endCircleData, function (d) { return d.nodeId; }); + .data(endCircleData, d => d.nodeId); -let enterCircles = circles +const enterCircles = circles .enter() .append('circle') - .classed('big', function (d) { return d.r > 10; }) - .attr('cx', function (d) { return d.cx; }) - .attr('cy', function (d) { return d.cy; }) - .attr('r', function (d) { return d.r; }) - .style('stroke', function (d) { return d.color; }) - .style('fill', function (d) { return d.color; }); + .classed('big', d => d.r > 10) + .attr('cx', d => d.cx) + .attr('cy', d => d.cy) + .attr('r', d => d.r) + .style('stroke', d => d.color) + .style('fill', d => d.color); -let exitCircles = circles.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' +const exitCircles = circles.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' // -------------------------------------------------------------------------- // Create Transition from Selection @@ -159,21 +159,19 @@ newEnterTransition = enterCircles.transition(differentDatumTypeTransition); // duration() --------------------------------------------------------------- enterTransition = enterTransition.duration(2000); // settable and chainable -let duration: number = enterTransition.duration(); +const duration: number = enterTransition.duration(); // delay() --------------------------------------------------------------- enterTransition = enterTransition.delay(500); // settable and chainable -let delay: number = enterTransition.delay(); +const delay: number = enterTransition.delay(); // ease() --------------------------------------------------------------- let easingFn: (normalizedTime: number) => number; -enterTransition = enterTransition.ease(function (t) { - return t; -}); // settable and chainable +enterTransition = enterTransition.ease(t => t); // settable and chainable easingFn = enterTransition.ease(); // -------------------------------------------------------------------------- @@ -190,7 +188,7 @@ interface ParagraphDatum { } // assume body was previously selected and its data were set to BodyDatum type using .datum() -let bodyTransition: d3Transition.Transition = select('body').transition(); +const bodyTransition: d3Transition.Transition = select('body').transition(); // select() ------------------------------------------------------------------ @@ -198,12 +196,12 @@ let bodyTransition: d3Transition.Transition = bodyTransition.select('div'); -firstDivTransition = bodyTransition.select(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | ArrayLike = g; +firstDivTransition = bodyTransition.select(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | ArrayLike = g; console.log('Body Datum foo', d.foo); // d is of type BodyDatum return this.querySelector('div')!; // 'this' type is HTMLElement, return type is HTMLDivElement @@ -217,12 +215,12 @@ firstDivTransition = bodyTransition.select(function (d, i, g) { let paragraphsTransition: d3Transition.Transition = firstDivTransition.selectAll('p'); -paragraphsTransition = firstDivTransition.selectAll(function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLDivElement[] | ArrayLike = g; +paragraphsTransition = firstDivTransition.selectAll(function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLDivElement[] | ArrayLike = g; console.log('Body Datum foo', d.foo); // d is of type BodyDatum return this.querySelectorAll('p'); // 'this' type is HTMLElement, return type is HTMLParagraphElement }); @@ -233,12 +231,12 @@ paragraphsTransition = firstDivTransition.selectAll = g; +exitTransition = exitTransition.filter(function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; // console.log(this.x) // fails, x property not defined on SVGCircleElement return this.r.baseVal.value < i * d.r; // this-type SVGCircleElement, datum tpye CircleDatum }); @@ -251,16 +249,16 @@ let filterdGElements2: d3Transition.Transition('.any-svg-type').transition().filter('g'); // filterdGElements2 = selectAll('.any-type').transition().filter('g'); // fails without using narrowing generic on filter method -filterdGElements2 = selectAll('.any-svg-type').transition().filter(function (d, i, g) { - let that: SVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGElement[] | ArrayLike = g; +filterdGElements2 = selectAll('.any-svg-type').transition().filter(function(d, i, g) { + const that: SVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGElement[] | ArrayLike = g; return that.tagName === 'g' || that.tagName === 'G'; }); // filterdGElements2 = selectAll('.any-svg-type').transition().filter(function(){ -// let that: SVGElement = this; +// const that: SVGElement = this; // return that.tagName === 'g'|| that.tagName === 'G'; // }); // fails without using narrowing generic on filter method @@ -281,21 +279,19 @@ enterTransition = enterTransition // re-assignment test chaining return-type .attr('stroke', 'blue'); // string enterTransition = enterTransition // re-assignment test chaining return-type - .attr('cx', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + .attr('cx', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (group.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array } return d.cx; // numeric return value }) - .attr('stroke', function (d) { - return d.color; // string return value - }); + .attr('stroke', d => d.color); // string return value enterTransition = enterTransition .style('fill', 'blue') // string @@ -304,30 +300,28 @@ enterTransition = enterTransition .style('stroke', 'green', 'important'); enterTransition = enterTransition - .style('fill', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + .style('fill', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context SVGCircleElement if (g.length > 0) { console.log('Radius of first group element:', g[0].r.baseVal.value); // group : Array } return d.color; // string return value }) - .style('hidden', function () { - return true; - }, null) // boolean return + test: priority = null - // .style('stroke', function () { return 'green'; }, 'test') // fails, test: invalid priority value - .style('stroke', function () { return 'green'; }, 'important'); // string return + test: priority = 'important'; + .style('hidden', () => true, null) // boolean return + test: priority = null + // .style('stroke', function() { return 'green'; }, 'test') // fails, test: invalid priority value + .style('stroke', () => 'green', 'important'); // string return + test: priority = 'important'; select('body') .datum({ test: 'New text.' }) .transition().duration(500) - .text('Let us start with this transition text.') + .text('const us start with this transition text.') .transition().duration(100) - .text(function (d) { return d.test; }); // selection datum type + .text(d => d.test); // selection datum type // test, when it is not certain, whether an element of the type to be selected exists @@ -337,12 +331,12 @@ maybeG1 = selectAll('svg') .selectAll('circle') .transition() .duration(500) - .attr('fill', function (d, i, g) { - let that: SVGCircleElement | null = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: Array | ArrayLike = g; + .attr('fill', function(d, i, g) { + const that: SVGCircleElement | null = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: Array | ArrayLike = g; if (that) { return that.r.baseVal.value < 5 ? 'slateblue' : 'seagreen'; @@ -354,19 +348,19 @@ maybeG1 = selectAll('svg') // Tweening Function Use ===================================================== -enterTransition = enterTransition.attrTween('r', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; +enterTransition = enterTransition.attrTween('r', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log(this.r.baseVal.value); // this type is SVGCircleElement return interpolateString(0, d.r); // datum type is CircleDatum }); -exitTransition = exitTransition.styleTween('fill', function (d, i, group) { +exitTransition = exitTransition.styleTween('fill', function(d, i, group) { console.log(this.r.baseVal.value); // this type is SVGCircleElement - let c: string = select(this).style('fill'); + const c: string = select(this).style('fill'); return interpolateRgb(c, d.color); // datum type is CircleDatum }); @@ -377,16 +371,16 @@ let tweenFnAccessor: undefined | ((this: SVGCircleElement, datum?: CircleDatum, updateTransition = updateTransition.tween('fillColor', null); // remove named tween // chainable -updateTransition = updateTransition.tween('fillColor', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; - let c: string | null = that.getAttribute('fill'); - let interpolator = interpolateRgb(c ? c : 'blue', d.color); // datum type CircleDatum +updateTransition = updateTransition.tween('fillColor', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; + const c: string | null = that.getAttribute('fill'); + const interpolator = interpolateRgb(c ? c : 'blue', d.color); // datum type CircleDatum console.log('Radius ', this.r.baseVal.value); // this type SVGCircleElement - return function (t) { + return t => { that.setAttribute('fill', interpolator(t)); }; }); @@ -414,12 +408,12 @@ exitTransition.remove(); let listener: undefined | ((this: SVGCircleElement, datum: CircleDatum, index: number, group: SVGCircleElement[] | ArrayLike) => void); -enterTransition = enterTransition.on('end', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; +enterTransition = enterTransition.on('end', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; console.log('transition end radius: ', this.r.baseVal.value); // SVGCircleElement console.log('end event datum color property: ', d.color); // CircleDatum type }); @@ -445,12 +439,12 @@ enterTransition = enterTransition.on('end', null); // check chaining return type // each(valueFn: (this: GElement, datum?: Datum, index?: number, group?: Array | ArrayLike) => void): Transition; // returns 'this' transition -enterTransition = enterTransition.each(function (d, i, g) { // check chaining return type by re-assigning - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; +enterTransition = enterTransition.each(function(d, i, g) { // check chaining return type by re-assigning + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; if (this.r.baseVal.value < d.r) { // this of type SVGCircleElement, datum of type CircleDatum console.log('Color of circles with current radius smaller than data radius: ', d.color); } @@ -461,33 +455,33 @@ enterTransition = enterTransition.each(function (d, i, g) { // check chaining r function changeExitColor(transition: d3Transition.Transition, fill: string, stroke: string) { transition - .style('fill', function (d) { return (d.r < 10) ? fill : 'black'; }) // datum type is CircleDatum - .style('stroke', function (d) { return (this.r.baseVal.value < 10) ? stroke : 'black'; }); // this type is SVGCircleElement + .style('fill', d => (d.r < 10) ? fill : 'black') // datum type is CircleDatum + .style('stroke', function(d) { return (this.r.baseVal.value < 10) ? stroke : 'black'; }); // this type is SVGCircleElement } // returns 'this' transition exitTransition = exitTransition.call(changeExitColor, 'midnightblue', 'black'); // check chaining return type by re-assigning -// exitTransition.call(function (transition: d3Transition.Transition): void { +// exitTransition.call(function(transition: d3Transition.Transition): void { // // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement // }); -// exitTransition.call(function (transition: d3Transition.Transition): void { +// exitTransition.call(function(transition: d3Transition.Transition): void { // // fails, group datum types of selection not compatible: CircleDatum v DivDatum // }); // empty() ------------------------------------------------------------------------------- -let empty: boolean = enterTransition.empty(); +const empty: boolean = enterTransition.empty(); // node() and nodes() -------------------------------------------------------------------- -let firstCircleNode: SVGCircleElement = enterTransition.node()!; -let circleNodes: SVGCircleElement[] = enterTransition.nodes(); +const firstCircleNode: SVGCircleElement = enterTransition.node()!; +const circleNodes: SVGCircleElement[] = enterTransition.nodes(); // size() -------------------------------------------------------------------------------- -let size: number = enterTransition.size(); +const size: number = enterTransition.size(); // -------------------------------------------------------------------------- // Sequencing transitions on the same selection diff --git a/d3-transition/index.d.ts b/d3-transition/index.d.ts index 22527c81ad..e2e49f6c2a 100644 --- a/d3-transition/index.d.ts +++ b/d3-transition/index.d.ts @@ -461,7 +461,8 @@ export interface Transition): this; diff --git a/d3-zoom/d3-zoom-tests.ts b/d3-zoom/d3-zoom-tests.ts index 4806479476..f4a1c0944e 100644 --- a/d3-zoom/d3-zoom-tests.ts +++ b/d3-zoom/d3-zoom-tests.ts @@ -16,7 +16,7 @@ import { interpolateZoom, interpolate, interpolateArray, ZoomInterpolator, ZoomV // Preparatory Steps // -------------------------------------------------------------------------- -let points: Array<[number, number]> = [ +const points: Array<[number, number]> = [ [10, 10], [20, 20], [50, 50] ]; @@ -28,12 +28,12 @@ interface CanvasDatum { radius: number; } -let canvas = select('canvas') +const canvas = select('canvas') .datum({ width: 500, height: 400, radius: 2.5 }) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }); + .attr('width', d => d.width) + .attr('height', d => d.height); -let context = canvas.node()!.getContext('2d'); +const context = canvas.node()!.getContext('2d'); function drawPointsOnCanvas(radius: number) { if (context) { @@ -44,8 +44,7 @@ function drawPointsOnCanvas(radius: number) { } function drawPointOnCanvas(radius: number) { - - return function (point: [number, number]) { + return (point: [number, number]) => { if (context) { context.moveTo(point[0] + radius, point[1]); context.arc(point[0], point[1], radius, 0, 2 * Math.PI); @@ -62,19 +61,19 @@ interface SVGDatum { filterBrushEvent: boolean; } -let svg = select('svg') +const svg = select('svg') .datum({ width: 500, height: 500, filterBrushEvent: true }) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }); + .attr('width', d => d.width) + .attr('height', d => d.height); -let g = svg.append('g'); +const g = svg.append('g'); g.selectAll() .data<[number, number]>(points) .enter().append('circle') - .attr('cx', function (d) { return d[0]; }) - .attr('cy', function (d) { return d[1]; }) + .attr('cx', d => d[0]) + .attr('cy', d => d[1]) .attr('r', 2.5); // For test of using zoomBehavior to transform selections and transitions ---- @@ -86,9 +85,6 @@ interface GroupDatum { toK: number; } -let groupsSelection: Selection; -let groupsTransition: Transition; - // -------------------------------------------------------------------------- // Test Define ZoomBehaviour @@ -99,7 +95,7 @@ let groupsTransition: Transition; function zoomedCanvas(this: HTMLCanvasElement, d: CanvasDatum) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - let e = > event; + const e = > event; if (context) { context.save(); context.clearRect(0, 0, this.width, this.height); // this element @@ -121,7 +117,7 @@ canvasZoom = d3Zoom.zoom() function zoomedSVGOverlay(this: SVGRectElement) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - let e = > event; + const e = > event; g.attr('transform', e.transform.toString()); } @@ -134,10 +130,9 @@ svgZoom = d3Zoom.zoom(); // filter() ---------------------------------------------------------------- // chainable -svgZoom = svgZoom.filter(function (d, i, group) { - +svgZoom = svgZoom.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - let e = > event; + const e = > event; console.log('Overlay Rectangle width: ', this.width.baseVal.value); // this typing is SVGRectElement return e.sourceEvent.type !== 'brush' || !d.filterBrushEvent; // datum type is SVGDatum (as propagated to SVGRectElement with zoom event attached) @@ -156,7 +151,7 @@ extentAccessor = svgZoom.extent(); svgZoom = svgZoom.extent([[0, 0], [200, 200]]); // chainable with accessor function -svgZoom = svgZoom.extent(function (d, i, group) { +svgZoom = svgZoom.extent(function(d, i, group) { console.log('Overlay Rectangle width: ', this.width.baseVal.value); // this typing is SVGRectElement return [[0, 0], [d.width, d.height]]; // datum type is SVGDatum }); @@ -183,7 +178,7 @@ translateExtent = svgZoom.translateExtent(); // chainable svgZoom = svgZoom.duration(500); -let duration: number = svgZoom.duration(); +const duration: number = svgZoom.duration(); // interpolate() -------------------------------------------------------------- @@ -234,14 +229,14 @@ canvas.call(canvasZoom); // SVG Example -------------------------------------------------------------- // attach the zoom behavior to an overlay svg rectangle -let svgOverlay: Selection = svg.append('rect') - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }) +const svgOverlay: Selection = svg.append('rect') + .attr('width', d => d.width) + .attr('height', d => d.height) .style('fill', 'none') .style('pointer-events', 'all') .call(svgZoom); -let svgOverlayTransition = svgOverlay.transition(); +const svgOverlayTransition = svgOverlay.transition(); // -------------------------------------------------------------------------- // Test Use ZoomBehaviour @@ -253,11 +248,11 @@ let svgOverlayTransition = svgOverlay.transition(); svgZoom.transform(svgOverlay, d3Zoom.zoomIdentity); // svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismachtes DOM Element type and datum type -svgZoom.transform(svgOverlay, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.transform(svgOverlay, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return d3Zoom.zoomIdentity; @@ -267,11 +262,11 @@ svgOverlayTransition.call(svgZoom.transform, d3Zoom.zoomIdentity); // svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismachtes DOM Element type and datum type svgZoom.transform(svgOverlayTransition, d3Zoom.zoomIdentity); -svgZoom.transform(svgOverlayTransition, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return d3Zoom.zoomIdentity; @@ -286,22 +281,22 @@ svgZoom.translateBy(svgOverlay, 20, 50); svgZoom.translateBy( svgOverlay, 20, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }); svgZoom.translateBy( svgOverlay, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -309,20 +304,20 @@ svgZoom.translateBy( 50); svgZoom.translateBy( svgOverlay, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -335,22 +330,22 @@ svgZoom.translateBy(svgOverlayTransition, 20, 50); svgZoom.translateBy( svgOverlayTransition, 20, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }); svgZoom.translateBy( svgOverlayTransition, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -358,20 +353,20 @@ svgZoom.translateBy( 50); svgZoom.translateBy( svgOverlayTransition, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; }, - function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -383,11 +378,11 @@ svgZoom.translateBy( svgZoom.scaleBy(svgOverlay, 3); // svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismachtes DOM Element type and datum type -svgZoom.scaleBy(svgOverlay, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 3; @@ -396,11 +391,11 @@ svgZoom.scaleBy(svgOverlay, function (datum, index, groups) { svgZoom.scaleBy(svgOverlayTransition, 3); // svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismachtes DOM Element type and datum type -svgZoom.scaleBy(svgOverlayTransition, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 3; @@ -412,11 +407,11 @@ svgZoom.scaleBy(svgOverlayTransition, function (datum, index, groups) { svgZoom.scaleTo(svgOverlay, 3); // svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismachtes DOM Element type and datum type -svgZoom.scaleTo(svgOverlay, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 3; @@ -425,11 +420,11 @@ svgZoom.scaleTo(svgOverlay, function (datum, index, groups) { svgZoom.scaleTo(svgOverlayTransition, 3); // svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismachtes DOM Element type and datum type -svgZoom.scaleTo(svgOverlayTransition, function (datum, index, groups) { - let that: SVGRectElement = this; - let d: SVGDatum = datum; - let i: number = index; - let g: SVGRectElement[] | ArrayLike = groups; +svgZoom.scaleTo(svgOverlayTransition, function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return 30; @@ -439,12 +434,12 @@ svgZoom.scaleTo(svgOverlayTransition, function (datum, index, groups) { // Test Zoom Event Interface // -------------------------------------------------------------------------- -let e: d3Zoom.D3ZoomEvent = event; // mock assignment +const e: d3Zoom.D3ZoomEvent = event; // mock assignment -let target: d3Zoom.ZoomBehavior = e.target; -let type: 'start' | 'zoom' | 'end' | string = e.type; -let zoomTransform: d3Zoom.ZoomTransform = e.transform; -let sourceEvent: any = e.sourceEvent; +const target: d3Zoom.ZoomBehavior = e.target; +const type: 'start' | 'zoom' | 'end' | string = e.type; +const zoomTransform: d3Zoom.ZoomTransform = e.transform; +const sourceEvent: any = e.sourceEvent; // -------------------------------------------------------------------------- // Test Zoom Transforms @@ -458,17 +453,17 @@ zTransform = d3Zoom.zoomTransform(canvas.node()!); // Test ZoomTransform ------------------------------------------------------- -let x: number = zTransform.x; -let y: number = zTransform.y; -let k: number = zTransform.k; +const x: number = zTransform.x; +const y: number = zTransform.y; +const k: number = zTransform.k; -let transformedPoint: [number, number] = zTransform.apply([15, 20]); -let transformedX: number = zTransform.applyX(15); -let transformedY: number = zTransform.applyY(20); +const transformedPoint: [number, number] = zTransform.apply([15, 20]); +const transformedX: number = zTransform.applyX(15); +const transformedY: number = zTransform.applyY(20); -let invertedPoint: [number, number] = zTransform.invert([150, 240]); -let invertedX: number = zTransform.invertX(150); -let invertedY: number = zTransform.invertY(240); +const invertedPoint: [number, number] = zTransform.invert([150, 240]); +const invertedX: number = zTransform.invertX(150); +const invertedY: number = zTransform.invertY(240); // TODO: reScaleX, reScaleY @@ -477,7 +472,7 @@ let linearScale: ScaleLinear = scaleLinear(); linearScale = zTransform.rescaleX(linearScale); linearScale = zTransform.rescaleY(linearScale); -let transformation: string = zTransform.toString(); +const transformation: string = zTransform.toString(); zTransform = zTransform.translate(50, 40); diff --git a/d3-zoom/index.d.ts b/d3-zoom/index.d.ts index 9e0d2b72ec..87a55e9b2a 100644 --- a/d3-zoom/index.d.ts +++ b/d3-zoom/index.d.ts @@ -577,10 +577,12 @@ export interface D3ZoomEvent = d3.selection(); +const d: d3.Selection = d3.selection(); diff --git a/d3/index.d.ts b/d3/index.d.ts index 61953fe148..bf7fa8e6b6 100644 --- a/d3/index.d.ts +++ b/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 4.4 +// Type definitions for D3JS d3 standard bundle 4.5 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/d3/tslint.json b/d3/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/d3/tslint.json +++ b/d3/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/dagre-d3/tslint.json b/dagre-d3/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/dagre-d3/tslint.json +++ b/dagre-d3/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/dagre/dagre-tests.ts b/dagre/dagre-tests.ts index d8004fa3da..2855055451 100644 --- a/dagre/dagre-tests.ts +++ b/dagre/dagre-tests.ts @@ -1,7 +1,7 @@ namespace DagreTests { const gDagre = new dagre.graphlib.Graph(); gDagre.setGraph({}) - .setDefaultEdgeLabel(function(){ return ; }) + .setDefaultEdgeLabel(() => {}) .setNode("a", {}) .setEdge("b", "c") .setEdge("c", "d", {class: "class"}); diff --git a/dagre/tslint.json b/dagre/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/dagre/tslint.json +++ b/dagre/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts b/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts index 8b3b2ab70f..561b968ba9 100644 --- a/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts +++ b/datatables.net-fixedheader/datatables.net-fixedheader-tests.ts @@ -1,8 +1,4 @@ -/// -/// - -$(document).ready(function() { - +$(document).ready(() => { var config: DataTables.Settings = { // FixedHeader extension options fixedHeader: { diff --git a/datatables.net-select/datatables.net-select-tests.ts b/datatables.net-select/datatables.net-select-tests.ts index 02c3249cf7..5d8fdd8dc6 100644 --- a/datatables.net-select/datatables.net-select-tests.ts +++ b/datatables.net-select/datatables.net-select-tests.ts @@ -1,8 +1,4 @@ -/// -/// - -$(document).ready(function() { - +$(document).ready(() => { var config: DataTables.Settings = { // Select extension options select: { diff --git a/deepmerge/deepmerge-tests.ts b/deepmerge/deepmerge-tests.ts index 7854f7adf1..4106de1275 100644 --- a/deepmerge/deepmerge-tests.ts +++ b/deepmerge/deepmerge-tests.ts @@ -1,13 +1,13 @@ import * as deepmerge from "deepmerge"; const x = { foo: { bar: 3 }, - array: [ { does: 'work', too: [ 1, 2, 3 ] } ] } + array: [ { does: 'work', too: [ 1, 2, 3 ] } ] }; const y = { foo: { baz: 4 }, quux: 5, - array: [ { does: 'work', too: [ 4, 5, 6 ] }, { really: 'yes' } ] } + array: [ { does: 'work', too: [ 4, 5, 6 ] }, { really: 'yes' } ] }; const expected = { foo: { bar: 3, baz: 4 }, array: [ { does: 'work', too: [ 1, 2, 3, 4, 5, 6 ] }, { really: 'yes' } ], - quux: 5 } + quux: 5 }; -const result = deepmerge(x, y); \ No newline at end of file +const result = deepmerge(x, y); \ No newline at end of file diff --git a/del/tslint.json b/del/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/del/tslint.json +++ b/del/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/devextreme/index.d.ts b/devextreme/index.d.ts index 6aae49d6cd..e327800618 100644 --- a/devextreme/index.d.ts +++ b/devextreme/index.d.ts @@ -1,10 +1,472 @@ -// Type definitions for DevExtreme 16.1.8 +// Type definitions for DevExtreme 16.2.4 // Project: http://js.devexpress.com/ // Definitions by: DevExpress Inc. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +interface JQuery { + dxAccordion(): JQuery; + dxAccordion(options: "instance"): DevExpress.ui.dxAccordion; + dxAccordion(options: string): any; + dxAccordion(options: string, ...params: any[]): any; + dxAccordion(options: DevExpress.ui.dxAccordionOptions): JQuery; +} +interface JQuery { + dxActionSheet(): JQuery; + dxActionSheet(options: "instance"): DevExpress.ui.dxActionSheet; + dxActionSheet(options: string): any; + dxActionSheet(options: string, ...params: any[]): any; + dxActionSheet(options: DevExpress.ui.dxActionSheetOptions): JQuery; +} +interface JQuery { + dxAutocomplete(): JQuery; + dxAutocomplete(options: "instance"): DevExpress.ui.dxAutocomplete; + dxAutocomplete(options: string): any; + dxAutocomplete(options: string, ...params: any[]): any; + dxAutocomplete(options: DevExpress.ui.dxAutocompleteOptions): JQuery; +} +interface JQuery { + dxBox(): JQuery; + dxBox(options: "instance"): DevExpress.ui.dxBox; + dxBox(options: string): any; + dxBox(options: string, ...params: any[]): any; + dxBox(options: DevExpress.ui.dxBoxOptions): JQuery; +} +interface JQuery { + dxButton(): JQuery; + dxButton(options: "instance"): DevExpress.ui.dxButton; + dxButton(options: string): any; + dxButton(options: string, ...params: any[]): any; + dxButton(options: DevExpress.ui.dxButtonOptions): JQuery; +} +interface JQuery { + dxCalendar(): JQuery; + dxCalendar(options: "instance"): DevExpress.ui.dxCalendar; + dxCalendar(options: string): any; + dxCalendar(options: string, ...params: any[]): any; + dxCalendar(options: DevExpress.ui.dxCalendarOptions): JQuery; +} +interface JQuery { + dxCheckBox(): JQuery; + dxCheckBox(options: "instance"): DevExpress.ui.dxCheckBox; + dxCheckBox(options: string): any; + dxCheckBox(options: string, ...params: any[]): any; + dxCheckBox(options: DevExpress.ui.dxCheckBoxOptions): JQuery; +} +interface JQuery { + dxColorBox(): JQuery; + dxColorBox(options: "instance"): DevExpress.ui.dxColorBox; + dxColorBox(options: string): any; + dxColorBox(options: string, ...params: any[]): any; + dxColorBox(options: DevExpress.ui.dxColorBoxOptions): JQuery; +} +interface JQuery { + dxContextMenu(): JQuery; + dxContextMenu(options: "instance"): DevExpress.ui.dxContextMenu; + dxContextMenu(options: string): any; + dxContextMenu(options: string, ...params: any[]): any; + dxContextMenu(options: DevExpress.ui.dxContextMenuOptions): JQuery; +} +interface JQuery { + dxDataGrid(): JQuery; + dxDataGrid(options: "instance"): DevExpress.ui.dxDataGrid; + dxDataGrid(options: string): any; + dxDataGrid(options: string, ...params: any[]): any; + dxDataGrid(options: DevExpress.ui.dxDataGridOptions): JQuery; +} +interface JQuery { + dxDateBox(): JQuery; + dxDateBox(options: "instance"): DevExpress.ui.dxDateBox; + dxDateBox(options: string): any; + dxDateBox(options: string, ...params: any[]): any; + dxDateBox(options: DevExpress.ui.dxDateBoxOptions): JQuery; +} +interface JQuery { + dxDeferRendering(): JQuery; + dxDeferRendering(options: "instance"): DevExpress.ui.dxDeferRendering; + dxDeferRendering(options: string): any; + dxDeferRendering(options: string, ...params: any[]): any; + dxDeferRendering(options: DevExpress.ui.dxDeferRenderingOptions): JQuery; +} +interface JQuery { + dxFileUploader(): JQuery; + dxFileUploader(options: "instance"): DevExpress.ui.dxFileUploader; + dxFileUploader(options: string): any; + dxFileUploader(options: string, ...params: any[]): any; + dxFileUploader(options: DevExpress.ui.dxFileUploaderOptions): JQuery; +} +interface JQuery { + dxForm(): JQuery; + dxForm(options: "instance"): DevExpress.ui.dxForm; + dxForm(options: string): any; + dxForm(options: string, ...params: any[]): any; + dxForm(options: DevExpress.ui.dxFormOptions): JQuery; +} +interface JQuery { + dxGallery(): JQuery; + dxGallery(options: "instance"): DevExpress.ui.dxGallery; + dxGallery(options: string): any; + dxGallery(options: string, ...params: any[]): any; + dxGallery(options: DevExpress.ui.dxGalleryOptions): JQuery; +} +interface JQuery { + dxList(): JQuery; + dxList(options: "instance"): DevExpress.ui.dxList; + dxList(options: string): any; + dxList(options: string, ...params: any[]): any; + dxList(options: DevExpress.ui.dxListOptions): JQuery; +} +interface JQuery { + dxLoadIndicator(): JQuery; + dxLoadIndicator(options: "instance"): DevExpress.ui.dxLoadIndicator; + dxLoadIndicator(options: string): any; + dxLoadIndicator(options: string, ...params: any[]): any; + dxLoadIndicator(options: DevExpress.ui.dxLoadIndicatorOptions): JQuery; +} +interface JQuery { + dxLoadPanel(): JQuery; + dxLoadPanel(options: "instance"): DevExpress.ui.dxLoadPanel; + dxLoadPanel(options: string): any; + dxLoadPanel(options: string, ...params: any[]): any; + dxLoadPanel(options: DevExpress.ui.dxLoadPanelOptions): JQuery; +} +interface JQuery { + dxLookup(): JQuery; + dxLookup(options: "instance"): DevExpress.ui.dxLookup; + dxLookup(options: string): any; + dxLookup(options: string, ...params: any[]): any; + dxLookup(options: DevExpress.ui.dxLookupOptions): JQuery; +} +interface JQuery { + dxMap(): JQuery; + dxMap(options: "instance"): DevExpress.ui.dxMap; + dxMap(options: string): any; + dxMap(options: string, ...params: any[]): any; + dxMap(options: DevExpress.ui.dxMapOptions): JQuery; +} +interface JQuery { + dxMenu(): JQuery; + dxMenu(options: "instance"): DevExpress.ui.dxMenu; + dxMenu(options: string): any; + dxMenu(options: string, ...params: any[]): any; + dxMenu(options: DevExpress.ui.dxMenuOptions): JQuery; +} +interface JQuery { + dxMultiView(): JQuery; + dxMultiView(options: "instance"): DevExpress.ui.dxMultiView; + dxMultiView(options: string): any; + dxMultiView(options: string, ...params: any[]): any; + dxMultiView(options: DevExpress.ui.dxMultiViewOptions): JQuery; +} +interface JQuery { + dxNavBar(): JQuery; + dxNavBar(options: "instance"): DevExpress.ui.dxNavBar; + dxNavBar(options: string): any; + dxNavBar(options: string, ...params: any[]): any; + dxNavBar(options: DevExpress.ui.dxNavBarOptions): JQuery; +} +interface JQuery { + dxNumberBox(): JQuery; + dxNumberBox(options: "instance"): DevExpress.ui.dxNumberBox; + dxNumberBox(options: string): any; + dxNumberBox(options: string, ...params: any[]): any; + dxNumberBox(options: DevExpress.ui.dxNumberBoxOptions): JQuery; +} +interface JQuery { + dxPanorama(): JQuery; + dxPanorama(options: "instance"): DevExpress.ui.dxPanorama; + dxPanorama(options: string): any; + dxPanorama(options: string, ...params: any[]): any; + dxPanorama(options: DevExpress.ui.dxPanoramaOptions): JQuery; +} +interface JQuery { + dxPivot(): JQuery; + dxPivot(options: "instance"): DevExpress.ui.dxPivot; + dxPivot(options: string): any; + dxPivot(options: string, ...params: any[]): any; + dxPivot(options: DevExpress.ui.dxPivotOptions): JQuery; +} +interface JQuery { + dxPivotGrid(): JQuery; + dxPivotGrid(options: "instance"): DevExpress.ui.dxPivotGrid; + dxPivotGrid(options: string): any; + dxPivotGrid(options: string, ...params: any[]): any; + dxPivotGrid(options: DevExpress.ui.dxPivotGridOptions): JQuery; +} +interface JQuery { + dxPivotGridFieldChooser(): JQuery; + dxPivotGridFieldChooser(options: "instance"): DevExpress.ui.dxPivotGridFieldChooser; + dxPivotGridFieldChooser(options: string): any; + dxPivotGridFieldChooser(options: string, ...params: any[]): any; + dxPivotGridFieldChooser(options: DevExpress.ui.dxPivotGridFieldChooserOptions): JQuery; +} +interface JQuery { + dxPopover(): JQuery; + dxPopover(options: "instance"): DevExpress.ui.dxPopover; + dxPopover(options: string): any; + dxPopover(options: string, ...params: any[]): any; + dxPopover(options: DevExpress.ui.dxPopoverOptions): JQuery; +} +interface JQuery { + dxPopup(): JQuery; + dxPopup(options: "instance"): DevExpress.ui.dxPopup; + dxPopup(options: string): any; + dxPopup(options: string, ...params: any[]): any; + dxPopup(options: DevExpress.ui.dxPopupOptions): JQuery; +} +interface JQuery { + dxProgressBar(): JQuery; + dxProgressBar(options: "instance"): DevExpress.ui.dxProgressBar; + dxProgressBar(options: string): any; + dxProgressBar(options: string, ...params: any[]): any; + dxProgressBar(options: DevExpress.ui.dxProgressBarOptions): JQuery; +} +interface JQuery { + dxRadioGroup(): JQuery; + dxRadioGroup(options: "instance"): DevExpress.ui.dxRadioGroup; + dxRadioGroup(options: string): any; + dxRadioGroup(options: string, ...params: any[]): any; + dxRadioGroup(options: DevExpress.ui.dxRadioGroupOptions): JQuery; +} +interface JQuery { + dxRangeSlider(): JQuery; + dxRangeSlider(options: "instance"): DevExpress.ui.dxRangeSlider; + dxRangeSlider(options: string): any; + dxRangeSlider(options: string, ...params: any[]): any; + dxRangeSlider(options: DevExpress.ui.dxRangeSliderOptions): JQuery; +} +interface JQuery { + dxResizable(): JQuery; + dxResizable(options: "instance"): DevExpress.ui.dxResizable; + dxResizable(options: string): any; + dxResizable(options: string, ...params: any[]): any; + dxResizable(options: DevExpress.ui.dxResizableOptions): JQuery; +} +interface JQuery { + dxResponsiveBox(): JQuery; + dxResponsiveBox(options: "instance"): DevExpress.ui.dxResponsiveBox; + dxResponsiveBox(options: string): any; + dxResponsiveBox(options: string, ...params: any[]): any; + dxResponsiveBox(options: DevExpress.ui.dxResponsiveBoxOptions): JQuery; +} +interface JQuery { + dxScheduler(): JQuery; + dxScheduler(options: "instance"): DevExpress.ui.dxScheduler; + dxScheduler(options: string): any; + dxScheduler(options: string, ...params: any[]): any; + dxScheduler(options: DevExpress.ui.dxSchedulerOptions): JQuery; +} +interface JQuery { + dxScrollView(): JQuery; + dxScrollView(options: "instance"): DevExpress.ui.dxScrollView; + dxScrollView(options: string): any; + dxScrollView(options: string, ...params: any[]): any; + dxScrollView(options: DevExpress.ui.dxScrollViewOptions): JQuery; +} +interface JQuery { + dxSelectBox(): JQuery; + dxSelectBox(options: "instance"): DevExpress.ui.dxSelectBox; + dxSelectBox(options: string): any; + dxSelectBox(options: string, ...params: any[]): any; + dxSelectBox(options: DevExpress.ui.dxSelectBoxOptions): JQuery; +} +interface JQuery { + dxSlideOut(): JQuery; + dxSlideOut(options: "instance"): DevExpress.ui.dxSlideOut; + dxSlideOut(options: string): any; + dxSlideOut(options: string, ...params: any[]): any; + dxSlideOut(options: DevExpress.ui.dxSlideOutOptions): JQuery; +} +interface JQuery { + dxSlideOutView(): JQuery; + dxSlideOutView(options: "instance"): DevExpress.ui.dxSlideOutView; + dxSlideOutView(options: string): any; + dxSlideOutView(options: string, ...params: any[]): any; + dxSlideOutView(options: DevExpress.ui.dxSlideOutViewOptions): JQuery; +} +interface JQuery { + dxSlider(): JQuery; + dxSlider(options: "instance"): DevExpress.ui.dxSlider; + dxSlider(options: string): any; + dxSlider(options: string, ...params: any[]): any; + dxSlider(options: DevExpress.ui.dxSliderOptions): JQuery; +} +interface JQuery { + dxSwitch(): JQuery; + dxSwitch(options: "instance"): DevExpress.ui.dxSwitch; + dxSwitch(options: string): any; + dxSwitch(options: string, ...params: any[]): any; + dxSwitch(options: DevExpress.ui.dxSwitchOptions): JQuery; +} +interface JQuery { + dxTabPanel(): JQuery; + dxTabPanel(options: "instance"): DevExpress.ui.dxTabPanel; + dxTabPanel(options: string): any; + dxTabPanel(options: string, ...params: any[]): any; + dxTabPanel(options: DevExpress.ui.dxTabPanelOptions): JQuery; +} +interface JQuery { + dxTabs(): JQuery; + dxTabs(options: "instance"): DevExpress.ui.dxTabs; + dxTabs(options: string): any; + dxTabs(options: string, ...params: any[]): any; + dxTabs(options: DevExpress.ui.dxTabsOptions): JQuery; +} +interface JQuery { + dxTagBox(): JQuery; + dxTagBox(options: "instance"): DevExpress.ui.dxTagBox; + dxTagBox(options: string): any; + dxTagBox(options: string, ...params: any[]): any; + dxTagBox(options: DevExpress.ui.dxTagBoxOptions): JQuery; +} +interface JQuery { + dxTextArea(): JQuery; + dxTextArea(options: "instance"): DevExpress.ui.dxTextArea; + dxTextArea(options: string): any; + dxTextArea(options: string, ...params: any[]): any; + dxTextArea(options: DevExpress.ui.dxTextAreaOptions): JQuery; +} +interface JQuery { + dxTextBox(): JQuery; + dxTextBox(options: "instance"): DevExpress.ui.dxTextBox; + dxTextBox(options: string): any; + dxTextBox(options: string, ...params: any[]): any; + dxTextBox(options: DevExpress.ui.dxTextBoxOptions): JQuery; +} +interface JQuery { + dxTileView(): JQuery; + dxTileView(options: "instance"): DevExpress.ui.dxTileView; + dxTileView(options: string): any; + dxTileView(options: string, ...params: any[]): any; + dxTileView(options: DevExpress.ui.dxTileViewOptions): JQuery; +} +interface JQuery { + dxToast(): JQuery; + dxToast(options: "instance"): DevExpress.ui.dxToast; + dxToast(options: string): any; + dxToast(options: string, ...params: any[]): any; + dxToast(options: DevExpress.ui.dxToastOptions): JQuery; +} +interface JQuery { + dxToolbar(): JQuery; + dxToolbar(options: "instance"): DevExpress.ui.dxToolbar; + dxToolbar(options: string): any; + dxToolbar(options: string, ...params: any[]): any; + dxToolbar(options: DevExpress.ui.dxToolbarOptions): JQuery; +} +interface JQuery { + dxTooltip(): JQuery; + dxTooltip(options: "instance"): DevExpress.ui.dxTooltip; + dxTooltip(options: string): any; + dxTooltip(options: string, ...params: any[]): any; + dxTooltip(options: DevExpress.ui.dxTooltipOptions): JQuery; +} +interface JQuery { + dxTreeView(): JQuery; + dxTreeView(options: "instance"): DevExpress.ui.dxTreeView; + dxTreeView(options: string): any; + dxTreeView(options: string, ...params: any[]): any; + dxTreeView(options: DevExpress.ui.dxTreeViewOptions): JQuery; +} +interface JQuery { + dxValidationGroup(): JQuery; + dxValidationGroup(options: "instance"): DevExpress.ui.dxValidationGroup; + dxValidationGroup(options: string): any; + dxValidationGroup(options: string, ...params: any[]): any; + dxValidationGroup(options: DevExpress.ui.dxValidationGroupOptions): JQuery; +} +interface JQuery { + dxValidationSummary(): JQuery; + dxValidationSummary(options: "instance"): DevExpress.ui.dxValidationSummary; + dxValidationSummary(options: string): any; + dxValidationSummary(options: string, ...params: any[]): any; + dxValidationSummary(options: DevExpress.ui.dxValidationSummaryOptions): JQuery; +} +interface JQuery { + dxValidator(): JQuery; + dxValidator(options: "instance"): DevExpress.ui.dxValidator; + dxValidator(options: string): any; + dxValidator(options: string, ...params: any[]): any; + dxValidator(options: DevExpress.ui.dxValidatorOptions): JQuery; +} +interface JQuery { + dxBarGauge(): JQuery; + dxBarGauge(options: "instance"): DevExpress.viz.dxBarGauge; + dxBarGauge(options: string): any; + dxBarGauge(options: string, ...params: any[]): any; + dxBarGauge(options: DevExpress.viz.gauges.dxBarGaugeOptions): JQuery; +} +interface JQuery { + dxBullet(): JQuery; + dxBullet(options: "instance"): DevExpress.viz.dxBullet; + dxBullet(options: string): any; + dxBullet(options: string, ...params: any[]): any; + dxBullet(options: DevExpress.viz.sparklines.dxBulletOptions): JQuery; +} +interface JQuery { + dxChart(): JQuery; + dxChart(options: "instance"): DevExpress.viz.dxChart; + dxChart(options: string): any; + dxChart(options: string, ...params: any[]): any; + dxChart(options: DevExpress.viz.charts.dxChartOptions): JQuery; +} +interface JQuery { + dxCircularGauge(): JQuery; + dxCircularGauge(options: "instance"): DevExpress.viz.dxCircularGauge; + dxCircularGauge(options: string): any; + dxCircularGauge(options: string, ...params: any[]): any; + dxCircularGauge(options: DevExpress.viz.gauges.dxCircularGaugeOptions): JQuery; +} +interface JQuery { + dxLinearGauge(): JQuery; + dxLinearGauge(options: "instance"): DevExpress.viz.dxLinearGauge; + dxLinearGauge(options: string): any; + dxLinearGauge(options: string, ...params: any[]): any; + dxLinearGauge(options: DevExpress.viz.gauges.dxLinearGaugeOptions): JQuery; +} +interface JQuery { + dxPieChart(): JQuery; + dxPieChart(options: "instance"): DevExpress.viz.dxPieChart; + dxPieChart(options: string): any; + dxPieChart(options: string, ...params: any[]): any; + dxPieChart(options: DevExpress.viz.charts.dxPieChartOptions): JQuery; +} +interface JQuery { + dxPolarChart(): JQuery; + dxPolarChart(options: "instance"): DevExpress.viz.dxPolarChart; + dxPolarChart(options: string): any; + dxPolarChart(options: string, ...params: any[]): any; + dxPolarChart(options: DevExpress.viz.charts.dxPolarChartOptions): JQuery; +} +interface JQuery { + dxRangeSelector(): JQuery; + dxRangeSelector(options: "instance"): DevExpress.viz.dxRangeSelector; + dxRangeSelector(options: string): any; + dxRangeSelector(options: string, ...params: any[]): any; + dxRangeSelector(options: DevExpress.viz.rangeSelector.dxRangeSelectorOptions): JQuery; +} +interface JQuery { + dxSparkline(): JQuery; + dxSparkline(options: "instance"): DevExpress.viz.dxSparkline; + dxSparkline(options: string): any; + dxSparkline(options: string, ...params: any[]): any; + dxSparkline(options: DevExpress.viz.sparklines.dxSparklineOptions): JQuery; +} +interface JQuery { + dxTreeMap(): JQuery; + dxTreeMap(options: "instance"): DevExpress.viz.dxTreeMap; + dxTreeMap(options: string): any; + dxTreeMap(options: string, ...params: any[]): any; + dxTreeMap(options: DevExpress.viz.treeMap.dxTreeMapOptions): JQuery; +} +interface JQuery { + dxVectorMap(): JQuery; + dxVectorMap(options: "instance"): DevExpress.viz.dxVectorMap; + dxVectorMap(options: string): any; + dxVectorMap(options: string, ...params: any[]): any; + dxVectorMap(options: DevExpress.viz.map.dxVectorMapOptions): JQuery; +} declare module DevExpress { /** Formats values. */ export interface Format { @@ -68,9 +530,9 @@ declare module DevExpress { export function resetGroup(): void; /** Validates the rules that are defined within the dxValidator objects that are registered for the specified ViewModel. */ export function validateModel(model: Object): ValidationGroupValidationResult; - /** Registers all the dxValidator objects extending fields of the specified ViewModel. */ + /** Registers all the Validator objects extending fields of the specified ViewModel. */ export function registerModelForValidation(model: Object): void; - /** Unregisters all the dxValidator objects extending fields of the specified ViewModel. */ + /** Unregisters all the Validator objects extending fields of the specified ViewModel. */ export function unregisterModelForValidation(model: Object): void; } export var hardwareBackButton: JQueryCallback; @@ -78,10 +540,7 @@ declare module DevExpress { export function processHardwareBackButton(): void; /** Hides the last displayed overlay widget. */ export function hideTopOverlay(): boolean; - /** - * Specifies whether or not the entire application/site supports right-to-left representation. - * @deprecated Use the config(config) method instead. - */ + /** * Specifies whether or not the entire application/site supports right-to-left representation. * @deprecated Use the config(config) method instead. */ export var rtlEnabled: boolean; /** Gets the current global configuration object. */ export function config(): Object; @@ -265,6 +724,8 @@ declare module DevExpress { height?: any; /** Specifies the width of the widget. */ width?: any; + /** Specifies the attributes to be attached to the widget's root element. */ + elementAttr?: Object; /** A bag for holding any options that require two-way binding (Angular approach specific) */ bindingOptions?: { [key: string]: any; }; } @@ -312,6 +773,9 @@ declare module DevExpress { key?: any; } export interface LoadOptions { + searchValue?: Object; + searchExpr?: Object; + searchOperation?: Object; filter?: Object; sort?: Object; select?: Object; @@ -682,25 +1146,34 @@ declare module DevExpress { /** Creates a Query instance for accessing the remote service specified by a URL. */ export function query(url: string, queryOptions: Object): Query; /** This section describes the utility objects provided by the DevExtreme data layer. */ - export var utils: { + export module utils { /** Compiles a getter function from the getter expression. */ - compileGetter(expr: any): Function; + export function compileGetter(expr: any): Function; /** Compiles a setter function from the setter expression. */ - compileSetter(expr: any): Function; - odata: { + export function compileSetter(expr: any): Function; + export module odata { /** Holds key value converters for OData. */ - keyConverters: { - String(value: any): string; - Int32(value: any): number; - Int64(value: any): EdmLiteral; - Guid(value: any): Guid; - Boolean(value: any): boolean; - Single(value: any): EdmLiteral; - Decimal(value: any): EdmLiteral; - }; + export module keyConverters { + export function String(value: any): string; + export function Int32(value: any): number; + export function Int64(value: any): EdmLiteral; + export function Guid(value: any): Guid; + export function Boolean(value: any): boolean; + export function Single(value: any): EdmLiteral; + export function Decimal(value: any): EdmLiteral; + } } } } + /** An object that serves as a namespace for the methods that are used to localize an application. */ + export module localization { + /** Gets the current locale identifier. */ + export function locale(): string; + /** Sets the current locale identifier. */ + export function locale(locale: string): void; + /** Loads DevExtreme messages. */ + export function loadMessages(messages: any): void; + } /** An object that serves as a namespace for DevExtreme UI widgets as well as for methods implementing UI logic in DevExtreme sites/applications. */ export module ui { export interface WidgetOptions extends DOMComponentOptions { @@ -760,6 +1233,10 @@ declare module DevExpress { selectedItem?: Object; /** An array of currently selected item objects. */ selectedItems?: Array; + /** Specifies an array of currently selected item keys. */ + selectedItemKeys?: Array; + /** Specifies which data field provides keys for widget items. */ + keyExpr?: any; /** A handler for the itemDeleting event. */ onItemDeleting?: Function; /** A handler for the itemDeleted event. */ @@ -767,8 +1244,13 @@ declare module DevExpress { /** A handler for the itemReordered event. */ onItemReordered?: Function; } + export interface DataHelperMixin { + /** Allows you to get the DataSource instance. */ + getDataSource(): DevExpress.data.DataSource; + } /** The base class for widgets containing an item collection. */ - export class CollectionWidget extends Widget { + export class CollectionWidget extends Widget implements DataHelperMixin + { constructor(element: JQuery, options?: CollectionWidgetOptions); constructor(element: HTMLElement, options?: CollectionWidgetOptions); selectItem(itemElement: any): void; @@ -776,6 +1258,7 @@ declare module DevExpress { deleteItem(itemElement: any): JQueryPromise; isItemSelected(itemElement: any): boolean; reorderItem(itemElement: any, toItemElement: any): JQueryPromise; + getDataSource(): DevExpress.data.DataSource; } export interface DataExpressionMixinOptions { /** A data source used to fetch data to be displayed by the widget. */ @@ -794,6 +1277,8 @@ declare module DevExpress { export interface EditorOptions extends WidgetOptions { /** The currently specified value. */ value?: Object; + /** The value to be assigned to the name attribute of the underlying `` element. */ + name?: string; /** A handler for the valueChanged event. */ onValueChanged?: Function; /** A Boolean value specifying whether or not the widget is read-only. */ @@ -840,14 +1325,14 @@ declare module DevExpress { export function setTemplateEngine(options: Object): void; } /** An object that serves as a namespace for utility methods that can be helpful when working with the DevExtreme framework and UI widgets. */ - export var utils: { + export module utils { /** Sets parameters for the viewport meta tag. */ - initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void; + export function initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void; /** Requests that the browser call a specified function to update animation before the next repaint. */ - requestAnimationFrame(callback: Function): number; + export function requestAnimationFrame(callback: Function): number; /** Cancels an animation frame request scheduled with the requestAnimationFrame method. */ - cancelAnimationFrame(requestID: number): void; - }; + export function cancelAnimationFrame(requestID: number): void; + } /** An object that serves as a namespace for DevExtreme Data Visualization Widgets. */ export module viz { /** Applies a theme for the entire page with several DevExtreme visualization widgets. */ @@ -897,15 +1382,18 @@ declare module DevExpress.ui { export class dxValidator extends DOMComponent implements validationEngine.IValidator { constructor(element: JQuery, options?: dxValidatorOptions); constructor(element: Element, options?: dxValidatorOptions); - /** Validates the value of the editor that is controlled by the current dxValidator object against the list of the specified validation rules. */ + /** Validates the value of the editor that is controlled by the current Validator object against the list of the specified validation rules. */ validate(): validationEngine.ValidatorValidationResult; - /** Resets the value and validation result of the editor associated with the current dxValidator object. */ + /** Resets the value and validation result of the editor associated with the current Validator object. */ reset(): void; + /** Sets focus to the editor associated with the current Validator object. */ + focus(): void; } + export interface dxValidationGroupOptions extends DOMComponentOptions { } /** The widget that is used in the Knockout and AngularJS approaches to combine the editors to be validated. */ export class dxValidationGroup extends DOMComponent { - constructor(element: JQuery); - constructor(element: Element); + constructor(element: JQuery, options?: dxValidationGroupOptions); + constructor(element: Element, options?: dxValidationGroupOptions); /** Validates rules of the validators that belong to the current validation group. */ validate(): validationEngine.ValidationGroupValidationResult; /** Resets the value and validation result of the editors that are included to the current validation group. */ @@ -969,10 +1457,7 @@ declare module DevExpress.ui { valueChangeEvent?: string; /** Specifies whether or not the widget supports searching. */ searchEnabled?: boolean; - /** - * Specifies whether or not the widget displays items by pages. - * @deprecated Use the DataSource paging opportunities instead. - */ + /** * Specifies whether or not the widget displays items by pages. * @deprecated Use the DataSource paging opportunities instead. */ pagingEnabled?: boolean; /** The text or HTML markup displayed by the widget if the item collection is empty. */ noDataText?: string; @@ -983,9 +1468,10 @@ declare module DevExpress.ui { onContentReady?: Function; } /** A base class for drop-down list widgets. */ - export class dxDropDownList extends dxDropDownEditor { + export class dxDropDownList extends dxDropDownEditor implements DataHelperMixin { constructor(element: JQuery, options?: dxDropDownListOptions); constructor(element: Element, options?: dxDropDownListOptions); + getDataSource(): DevExpress.data.DataSource; } export interface dxToolbarOptions extends CollectionWidgetOptions { /** The template used to render menu items. */ @@ -1059,8 +1545,9 @@ declare module DevExpress.ui { valueChangeEvent?: string; /** Specifies whether or not the widget checks the inner text for spelling mistakes. */ spellcheck?: boolean; - /** Specifies HTML attributes applied to the inner input element of the widget. */ attr?: Object; + /** Specifies the attributes to be passed on to the underlying `` element. */ + inputAttr?: Object; /** The read-only option that holds the text displayed by the widget input element. */ text?: string; focusStateEnabled?: boolean; @@ -1075,6 +1562,7 @@ declare module DevExpress.ui { maskInvalidMessage?: string; /** Specifies whether the value option holds only characters entered by a user or prompt characters as well. */ useMaskedValue?: boolean; + name?: string; } /** A base class for text editing widgets. */ export class dxTextEditor extends Editor { @@ -1278,6 +1766,7 @@ declare module DevExpress.ui { activeStateEnabled?: boolean; /** Specifies the radio group layout. */ layout?: string; + name?: string; } /** A widget that enables a user to select one item within a list of items represented by radio buttons. */ export class dxRadioGroup extends CollectionWidget { @@ -1356,6 +1845,20 @@ declare module DevExpress.ui { target?: any; /** Specifies the width of the widget. */ width?: any; + /** Specifies options for displaying the widget. */ + showEvent?: { + /** Specifies the event names on which the widget is shown. */ + name?: String; + /** The time span after which the widget is shown. */ + delay?: Number; + }; + /** Specifies options of popover hiding. */ + hideEvent?: { + /** Specifies the event names on which the widget is hidden. */ + name?: String; + /** The time span after which the popover is hidden. */ + delay?: Number; + }; } /** A widget that displays the required content in a popup window. */ export class dxPopover extends dxPopup { @@ -1628,10 +2131,7 @@ declare module DevExpress.ui { shading?: boolean; /** Specifies whether to display the Cancel button in the lookup window. */ showCancelButton?: boolean; - /** - * A Boolean value specifying whether the widget loads the next page automatically when you reach the bottom of the list or when a button is clicked. - * @deprecated Use the pageLoadMode option instead. - */ + /** * A Boolean value specifying whether the widget loads the next page automatically when you reach the bottom of the list or when a button is clicked. * @deprecated Use the pageLoadMode option instead. */ showNextButton?: boolean; /** The title of the lookup window. */ title?: string; @@ -1751,6 +2251,8 @@ declare module DevExpress.ui { showSelectionControls?: boolean; /** Specifies item selection mode. */ selectionMode?: string; + /** Specifies the mode in which all items are selected. */ + selectAllMode?: string; selectAllText?: string; /** A handler for the selectAllValueChanged event. */ onSelectAllValueChanged?: Function; @@ -1898,17 +2400,11 @@ declare module DevExpress.ui { min?: any; /** The text displayed by the widget when the widget value is not yet specified. This text is also used as a title of the date picker. */ placeholder?: string; - /** - * Specifies whether or not a user can pick out a date using the drop-down calendar. - * @deprecated Use the pickerType option instead. - */ + /** * Specifies whether or not a user can pick out a date using the drop-down calendar. * @deprecated Use the pickerType option instead. */ useCalendar?: boolean; /** An object or a value, specifying the date and time currently selected using the date box. */ value?: any; - /** - * Specifies whether or not the widget uses the native HTML input element. - * @deprecated Use the pickerType option instead. - */ + /** * Specifies whether or not the widget uses the native HTML input element. * @deprecated Use the pickerType option instead. */ useNative?: boolean; /** Specifies the interval between neighboring values in the popup list in minutes. */ interval?: number; @@ -1940,6 +2436,7 @@ declare module DevExpress.ui { value?: boolean; /** Specifies the text displayed by the check box. */ text?: string; + name?: string; } /** A check box widget. */ export class dxCheckBox extends Editor { @@ -1968,6 +2465,7 @@ declare module DevExpress.ui { minZoomLevel?: string; /** The template to be used for rendering calendar cells. */ cellTemplate?: any; + name?: string; } /** A calendar widget. */ export class dxCalendar extends Editor { @@ -1990,6 +2488,8 @@ declare module DevExpress.ui { type?: string; /** Specifies the name of the validation group to be accessed in the click event handler. */ validationGroup?: string; + /** Specifies whether the button must submit an HTML form. */ + useSubmitBehavior?: boolean; } /** A button widget. */ export class dxButton extends Widget { @@ -2134,8 +2634,6 @@ declare module DevExpress.ui { min?: number; /** The maximum value the widget can accept. */ max?: number; - /** The current widget value. */ - value?: number; } /** A base class for track bar widgets. */ export class dxTrackBar extends Editor { @@ -2149,18 +2647,18 @@ declare module DevExpress.ui { showStatus?: boolean; /** A handler for the complete event. */ onComplete?: Function; + /** The current widget value. */ + value?: number; } /** A widget used to indicate progress. */ export class dxProgressBar extends dxTrackBar { constructor(element: JQuery, options?: dxProgressBarOptions); constructor(element: Element, options?: dxProgressBarOptions); } - export interface dxSliderOptions extends dxTrackBarOptions { + export interface dxSliderBaseOptions extends dxTrackBarOptions { activeStateEnabled?: boolean; /** The slider step size. */ step?: number; - /** The current slider value. */ - value?: number; /** Specifies whether or not to highlight a range selected within the widget. */ showRange?: boolean; /** Specifies the size of a step by which a slider handle is moved when a user uses the Page up or Page down keyboard shortcuts. */ @@ -2185,17 +2683,27 @@ declare module DevExpress.ui { /** Specifies a format for labels. */ format?: any; }; + name?: string; + } + export interface dxSliderOptions extends dxSliderBaseOptions { + /** The current slider value. */ + value?: number; } /** A widget that allows a user to select a numeric value within a given range. */ export class dxSlider extends dxTrackBar { constructor(element: JQuery, options?: dxSliderOptions); constructor(element: Element, options?: dxSliderOptions); } - export interface dxRangeSliderOptions extends dxSliderOptions { + export interface dxRangeSliderOptions extends dxSliderBaseOptions { /** The left edge of the interval currently selected using the range slider. */ start?: number; /** The right edge of the interval currently selected using the range slider. */ end?: number; + /** The value to be assigned to the name attribute of the underlying `` element. */ + startName?: string; + /** The value to be assigned to the name attribute of the underlying `` element. */ + endName?: string; + value?: Array; } /** A widget that enables a user to select a range of numeric values. */ export class dxRangeSlider extends dxSlider { @@ -2226,10 +2734,12 @@ declare module DevExpress.ui { /** Specifies the number of columns spanned by the item. */ colSpan?: number; } + /** This article describes configuration options of an empty form item. */ export interface dxFormEmptyItem extends dxFormItem { /** Specifies the form item name. */ name?: string; } + /** This article describes configuration options of a simple form item. */ export interface dxFormSimpleItem extends dxFormItem { /** Specifies the path to the formData object field bound to the current form item. */ dataField?: string; @@ -2261,6 +2771,7 @@ declare module DevExpress.ui { /** The count of columns for a large screen size. */ lg?: number; } + /** This article describes configuration options of a group form item. */ export interface dxFormGroupItem extends dxFormItem { /** Specifies the group caption. */ caption?: string; @@ -2297,6 +2808,7 @@ declare module DevExpress.ui { /** The template to be used for rendering the tab content. */ template?: any; } + /** This article describes configuration options of a tabbed form item. */ export interface dxFormTabbedItem extends dxFormItem { /** Holds a configuration object for the TabPanel widget used to display the current form item. */ tabPanelOptions?: Object; @@ -2346,6 +2858,8 @@ declare module DevExpress.ui { items?: Array; /** A Boolean value specifying whether to enable or disable form scrolling. */ scrollingEnabled?: boolean; + /** Gives a name to the internal validation group. */ + validationGroup?: string; onContentReady?: Function; } /** A form widget used to display and edit values of object fields. */ @@ -2391,228 +2905,34 @@ declare module DevExpress.ui { constructor(element: Element, options?: dxDeferRenderingOptions); } } +/* Private plugins. To be removed */ interface JQuery { - dxProgressBar(): JQuery; - dxProgressBar(options: "instance"): DevExpress.ui.dxProgressBar; - dxProgressBar(options: string): any; - dxProgressBar(options: string, ...params: any[]): any; - dxProgressBar(options: DevExpress.ui.dxProgressBarOptions): JQuery; - dxSlider(): JQuery; - dxSlider(options: "instance"): DevExpress.ui.dxSlider; - dxSlider(options: string): any; - dxSlider(options: string, ...params: any[]): any; - dxSlider(options: DevExpress.ui.dxSliderOptions): JQuery; - dxRangeSlider(): JQuery; - dxRangeSlider(options: "instance"): DevExpress.ui.dxRangeSlider; - dxRangeSlider(options: string): any; - dxRangeSlider(options: string, ...params: any[]): any; - dxRangeSlider(options: DevExpress.ui.dxRangeSliderOptions): JQuery; - dxFileUploader(): JQuery; - dxFileUploader(options: "instance"): DevExpress.ui.dxFileUploader; - dxFileUploader(options: string): any; - dxFileUploader(options: string, ...params: any[]): any; - dxFileUploader(options: DevExpress.ui.dxFileUploaderOptions): JQuery; - dxValidator(): JQuery; - dxValidator(options: "instance"): DevExpress.ui.dxValidator; - dxValidator(options: string): any; - dxValidator(options: string, ...params: any[]): any; - dxValidator(options: DevExpress.ui.dxValidatorOptions): JQuery; - dxValidationGroup(): JQuery; - dxValidationGroup(options: "instance"): DevExpress.ui.dxValidationGroup; - dxValidationGroup(options: string): any; - dxValidationGroup(options: string, ...params: any[]): any; - dxValidationSummary(): JQuery; - dxValidationSummary(options: "instance"): DevExpress.ui.dxValidationSummary; - dxValidationSummary(options: string): any; - dxValidationSummary(options: string, ...params: any[]): any; - dxValidationSummary(options: DevExpress.ui.dxValidationSummaryOptions): JQuery; - dxTooltip(): JQuery; - dxTooltip(options: "instance"): DevExpress.ui.dxTooltip; - dxTooltip(options: string): any; - dxTooltip(options: string, ...params: any[]): any; - dxTooltip(options: DevExpress.ui.dxTooltipOptions): JQuery; - dxResizable(): JQuery; - dxResizable(options: "instance"): DevExpress.ui.dxResizable; - dxResizable(options: string): any; - dxResizable(options: string, ...params: any[]): any; - dxResizable(options: DevExpress.ui.dxResizableOptions): JQuery; dxDropDownList(): JQuery; dxDropDownList(options: "instance"): DevExpress.ui.dxDropDownList; dxDropDownList(options: string): any; dxDropDownList(options: string, ...params: any[]): any; dxDropDownList(options: DevExpress.ui.dxDropDownListOptions): JQuery; - dxToolbar(): JQuery; - dxToolbar(options: "instance"): DevExpress.ui.dxToolbar; - dxToolbar(options: string): any; - dxToolbar(options: string, ...params: any[]): any; - dxToolbar(options: DevExpress.ui.dxToolbarOptions): JQuery; - dxToast(): JQuery; - dxToast(options: "instance"): DevExpress.ui.dxToast; - dxToast(options: string): any; - dxToast(options: string, ...params: any[]): any; - dxToast(options: DevExpress.ui.dxToastOptions): JQuery; dxTextEditor(): JQuery; dxTextEditor(options: "instance"): DevExpress.ui.dxTextEditor; dxTextEditor(options: string): any; dxTextEditor(options: string, ...params: any[]): any; dxTextEditor(options: DevExpress.ui.dxTextEditorOptions): JQuery; - dxTextBox(): JQuery; - dxTextBox(options: "instance"): DevExpress.ui.dxTextBox; - dxTextBox(options: string): any; - dxTextBox(options: string, ...params: any[]): any; - dxTextBox(options: DevExpress.ui.dxTextBoxOptions): JQuery; - dxTextArea(): JQuery; - dxTextArea(options: "instance"): DevExpress.ui.dxTextArea; - dxTextArea(options: string): any; - dxTextArea(options: string, ...params: any[]): any; - dxTextArea(options: DevExpress.ui.dxTextAreaOptions): JQuery; - dxTabs(): JQuery; - dxTabs(options: "instance"): DevExpress.ui.dxTabs; - dxTabs(options: string): any; - dxTabs(options: string, ...params: any[]): any; - dxTabs(options: DevExpress.ui.dxTabsOptions): JQuery; - dxTabPanel(): JQuery; - dxTabPanel(options: "instance"): DevExpress.ui.dxTabPanel; - dxTabPanel(options: string): any; - dxTabPanel(options: string, ...params: any[]): any; - dxTabPanel(options: DevExpress.ui.dxTabPanelOptions): JQuery; - dxSelectBox(): JQuery; - dxSelectBox(options: "instance"): DevExpress.ui.dxSelectBox; - dxSelectBox(options: string): any; - dxSelectBox(options: string, ...params: any[]): any; - dxSelectBox(options: DevExpress.ui.dxSelectBoxOptions): JQuery; - dxTagBox(): JQuery; - dxTagBox(options: "instance"): DevExpress.ui.dxTagBox; - dxTagBox(options: string): any; - dxTagBox(options: string, ...params: any[]): any; - dxTagBox(options: DevExpress.ui.dxTagBoxOptions): JQuery; - dxScrollView(): JQuery; - dxScrollView(options: "instance"): DevExpress.ui.dxScrollView; - dxScrollView(options: string): any; - dxScrollView(options: string, ...params: any[]): any; - dxScrollView(options: DevExpress.ui.dxScrollViewOptions): JQuery; dxScrollable(): JQuery; dxScrollable(options: "instance"): DevExpress.ui.dxScrollable; dxScrollable(options: string): any; dxScrollable(options: string, ...params: any[]): any; dxScrollable(options: DevExpress.ui.dxScrollableOptions): JQuery; - dxRadioGroup(): JQuery; - dxRadioGroup(options: "instance"): DevExpress.ui.dxRadioGroup; - dxRadioGroup(options: string): any; - dxRadioGroup(options: string, ...params: any[]): any; - dxRadioGroup(options: DevExpress.ui.dxRadioGroupOptions): JQuery; - dxPopup(): JQuery; - dxPopup(options: "instance"): DevExpress.ui.dxPopup; - dxPopup(options: string): any; - dxPopup(options: string, ...params: any[]): any; - dxPopup(options: DevExpress.ui.dxPopupOptions): JQuery; - dxPopover(): JQuery; - dxPopover(options: "instance"): DevExpress.ui.dxPopover; - dxPopover(options: string): any; - dxPopover(options: string, ...params: any[]): any; - dxPopover(options: DevExpress.ui.dxPopoverOptions): JQuery; dxOverlay(): JQuery; dxOverlay(options: "instance"): DevExpress.ui.dxOverlay; dxOverlay(options: string): any; dxOverlay(options: string, ...params: any[]): any; dxOverlay(options: DevExpress.ui.dxOverlayOptions): JQuery; - dxNumberBox(): JQuery; - dxNumberBox(options: "instance"): DevExpress.ui.dxNumberBox; - dxNumberBox(options: string): any; - dxNumberBox(options: string, ...params: any[]): any; - dxNumberBox(options: DevExpress.ui.dxNumberBoxOptions): JQuery; - dxNavBar(): JQuery; - dxNavBar(options: "instance"): DevExpress.ui.dxNavBar; - dxNavBar(options: string): any; - dxNavBar(options: string, ...params: any[]): any; - dxNavBar(options: DevExpress.ui.dxNavBarOptions): JQuery; - dxMultiView(): JQuery; - dxMultiView(options: "instance"): DevExpress.ui.dxMultiView; - dxMultiView(options: string): any; - dxMultiView(options: string, ...params: any[]): any; - dxMultiView(options: DevExpress.ui.dxMultiViewOptions): JQuery; - dxMap(): JQuery; - dxMap(options: "instance"): DevExpress.ui.dxMap; - dxMap(options: string): any; - dxMap(options: string, ...params: any[]): any; - dxMap(options: DevExpress.ui.dxMapOptions): JQuery; - dxLookup(): JQuery; - dxLookup(options: "instance"): DevExpress.ui.dxLookup; - dxLookup(options: string): any; - dxLookup(options: string, ...params: any[]): any; - dxLookup(options: DevExpress.ui.dxLookupOptions): JQuery; - dxLoadPanel(): JQuery; - dxLoadPanel(options: "instance"): DevExpress.ui.dxLoadPanel; - dxLoadPanel(options: string): any; - dxLoadPanel(options: string, ...params: any[]): any; - dxLoadPanel(options: DevExpress.ui.dxLoadPanelOptions): JQuery; - dxLoadIndicator(): JQuery; - dxLoadIndicator(options: "instance"): DevExpress.ui.dxLoadIndicator; - dxLoadIndicator(options: string): any; - dxLoadIndicator(options: string, ...params: any[]): any; - dxLoadIndicator(options: DevExpress.ui.dxLoadIndicatorOptions): JQuery; - dxList(): JQuery; - dxList(options: "instance"): DevExpress.ui.dxList; - dxList(options: string): any; - dxList(options: string, ...params: any[]): any; - dxList(options: DevExpress.ui.dxListOptions): JQuery; - dxGallery(): JQuery; - dxGallery(options: "instance"): DevExpress.ui.dxGallery; - dxGallery(options: string): any; - dxGallery(options: string, ...params: any[]): any; - dxGallery(options: DevExpress.ui.dxGalleryOptions): JQuery; dxDropDownEditor(): JQuery; dxDropDownEditor(options: "instance"): DevExpress.ui.dxDropDownEditor; dxDropDownEditor(options: string): any; dxDropDownEditor(options: string, ...params: any[]): any; dxDropDownEditor(options: DevExpress.ui.dxDropDownEditorOptions): JQuery; - dxDateBox(): JQuery; - dxDateBox(options: "instance"): DevExpress.ui.dxDateBox; - dxDateBox(options: string): any; - dxDateBox(options: string, ...params: any[]): any; - dxDateBox(options: DevExpress.ui.dxDateBoxOptions): JQuery; - dxCheckBox(): JQuery; - dxCheckBox(options: "instance"): DevExpress.ui.dxCheckBox; - dxCheckBox(options: string): any; - dxCheckBox(options: string, ...params: any[]): any; - dxCheckBox(options: DevExpress.ui.dxCheckBoxOptions): JQuery; - dxBox(): JQuery; - dxBox(options: "instance"): DevExpress.ui.dxBox; - dxBox(options: string): any; - dxBox(options: string, ...params: any[]): any; - dxBox(options: DevExpress.ui.dxBoxOptions): JQuery; - dxButton(): JQuery; - dxButton(options: "instance"): DevExpress.ui.dxButton; - dxButton(options: string): any; - dxButton(options: string, ...params: any[]): any; - dxButton(options: DevExpress.ui.dxButtonOptions): JQuery; - dxCalendar(): JQuery; - dxCalendar(options: "instance"): DevExpress.ui.dxCalendar; - dxCalendar(options: string): any; - dxCalendar(options: string, ...params: any[]): any; - dxCalendar(options: DevExpress.ui.dxCalendarOptions): JQuery; - dxAccordion(): JQuery; - dxAccordion(options: "instance"): DevExpress.ui.dxAccordion; - dxAccordion(options: string): any; - dxAccordion(options: string, ...params: any[]): any; - dxAccordion(options: DevExpress.ui.dxAccordionOptions): JQuery; - dxResponsiveBox(): JQuery; - dxResponsiveBox(options: "instance"): DevExpress.ui.dxResponsiveBox; - dxResponsiveBox(options: string): any; - dxResponsiveBox(options: string, ...params: any[]): any; - dxResponsiveBox(options: DevExpress.ui.dxResponsiveBoxOptions): JQuery; - dxAutocomplete(): JQuery; - dxAutocomplete(options: "instance"): DevExpress.ui.dxAutocomplete; - dxAutocomplete(options: string): any; - dxAutocomplete(options: string, ...params: any[]): any; - dxAutocomplete(options: DevExpress.ui.dxAutocompleteOptions): JQuery; - dxForm(): JQuery; - dxForm(options: "instance"): DevExpress.ui.dxForm; - dxForm(options: string): any; - dxForm(options: string, ...params: any[]): any; - dxForm(options: DevExpress.ui.dxFormOptions): JQuery; } - declare module DevExpress.ui { export interface dxTileViewOptions extends CollectionWidgetOptions { /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ @@ -2645,6 +2965,7 @@ declare module DevExpress.ui { onText?: string; /** A Boolean value specifying whether the current switch state is "On" or "Off". */ value?: boolean; + name?: string; } /** A switch widget. */ export class dxSwitch extends Editor { @@ -2812,43 +3133,6 @@ declare module DevExpress.ui { toggle(showing: boolean): JQueryPromise; } } -interface JQuery { - dxTileView(): JQuery; - dxTileView(options: "instance"): DevExpress.ui.dxTileView; - dxTileView(options: string): any; - dxTileView(options: string, ...params: any[]): any; - dxTileView(options: DevExpress.ui.dxTileViewOptions): JQuery; - dxSwitch(): JQuery; - dxSwitch(options: "instance"): DevExpress.ui.dxSwitch; - dxSwitch(options: string): any; - dxSwitch(options: string, ...params: any[]): any; - dxSwitch(options: DevExpress.ui.dxSwitchOptions): JQuery; - dxSlideOut(): JQuery; - dxSlideOut(options: "instance"): DevExpress.ui.dxSlideOut; - dxSlideOut(options: string): any; - dxSlideOut(options: string, ...params: any[]): any; - dxSlideOut(options: DevExpress.ui.dxSlideOutOptions): JQuery; - dxPivot(): JQuery; - dxPivot(options: "instance"): DevExpress.ui.dxPivot; - dxPivot(options: string): any; - dxPivot(options: string, ...params: any[]): any; - dxPivot(options: DevExpress.ui.dxPivotOptions): JQuery; - dxPanorama(): JQuery; - dxPanorama(options: "instance"): DevExpress.ui.dxPanorama; - dxPanorama(options: string): any; - dxPanorama(options: string, ...params: any[]): any; - dxPanorama(options: DevExpress.ui.dxPanoramaOptions): JQuery; - dxActionSheet(): JQuery; - dxActionSheet(options: "instance"): DevExpress.ui.dxActionSheet; - dxActionSheet(options: string): any; - dxActionSheet(options: string, ...params: any[]): any; - dxActionSheet(options: DevExpress.ui.dxActionSheetOptions): JQuery; - dxDropDownMenu(): JQuery; - dxDropDownMenu(options: "instance"): DevExpress.ui.dxDropDownMenu; - dxDropDownMenu(options: string): any; - dxDropDownMenu(options: string, ...params: any[]): any; - dxDropDownMenu(options: DevExpress.ui.dxDropDownMenuOptions): JQuery; -} declare module DevExpress.data { export interface XmlaStoreOptions { /** The HTTP address to an XMLA OLAP server. */ @@ -2884,7 +3168,7 @@ declare module DevExpress.data { value?: any; totalValue?: any; }) => void; - /** Specifies the function that determines how to split data from the data source into ranges for header items. Cannot be used for the XmlaStore store type. */ + /** Specifies the function that determines how to split data from the data source into ranges for header items. Cannot be used for the XmlaStore store type and along with remote operations. */ selector?: (data: Object) => any; /** Type of the area where the field is located. */ area?: string; @@ -2918,10 +3202,7 @@ declare module DevExpress.data { format?: any; /** Specifies a callback function that returns the text to be displayed in the cells of a field. */ customizeText?: (cellInfo: { value: any; valueText: string }) => string; - /** - * Specifies a precision for formatted field values. - * @deprecated Use the format | precision option instead. - */ + /** * Specifies a precision for formatted field values. * @deprecated Use the format | precision option instead. */ precision?: number; /** Specifies how to sort the header items. */ sortingMethod?: (a: Object, b: Object) => number; @@ -2989,6 +3270,8 @@ declare module DevExpress.data { filter?: Object; /** An array of pivot grid fields. */ fields?: Array; + /** Specifies whether or not all the operations (filtering, grouping and summary calculation) are performed remotely. */ + remoteOperations?: boolean; /** A handler for the changed event. */ onChanged?: () => void; /** A handler for the loadingChanged event. */ @@ -3052,6 +3335,34 @@ declare module DevExpress.data { } } declare module DevExpress.ui { + export interface dxSchedulerViewOptions { + /** The name of the view. */ + type?: string; + /** The first day of a week. */ + firstDayOfWeek?: number; + /** The resource kinds by which appointments are grouped. */ + groups?: Array; + /** The start hour of the view time scale. */ + startDayHour?: number; + /** The end hour of the view time scale. */ + endDayHour?: number; + /** The cell duration in minutes. */ + cellDuration?: number; + /** Specifies the number of dates that can be shown at a time in the agenda view. */ + agendaDuration?: number; + /** The template to be used for rendering appointments. */ + appointmentTemplate?: any; + /** The template to be used for rendering an appointment tooltip. */ + appointmentTooltipTemplate?: any; + /** The template to be used for rendering table cells. */ + dataCellTemplate?: any; + /** The template to be used for rendering time scale items. */ + timeCellTemplate?: any; + /** The template to be used for rendering date scale items. */ + dateCellTemplate?: any; + /** The template to be used for rendering resource headers. */ + resourceCellTemplate?: any; + } export interface dxSchedulerOptions extends WidgetOptions { /** Specifies a date displayed on the current scheduler view by default. */ currentDate?: any; @@ -3069,8 +3380,16 @@ declare module DevExpress.ui { appointmentTemplate?: any; /** The template to be used for rendering an appointment tooltip. */ appointmentTooltipTemplate?: any; + /** The template to be used for rendering table cells. */ + dataCellTemplate?: any; + /** The template to be used for rendering time scale items. */ + timeCellTemplate?: any; + /** The template to be used for rendering date scale items. */ + dateCellTemplate?: any; + /** The template to be used for rendering resource headers. */ + resourceCellTemplate?: any; /** Lists the views to be available within the scheduler's View Selector. */ - views?: Array; + views?: Array; /** Specifies the resource kinds by which the scheduler's appointments are grouped in a timetable. */ groups?: Array; /** Specifies a start hour in the scheduler view's time interval. */ @@ -3100,10 +3419,7 @@ declare module DevExpress.ui { resources?: Array<{ /** Indicates whether or not several resources of this kind can be assigned to an appointment. */ allowMultiple?: boolean; - /** - * Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. - * @deprecated Use the useColorAsDefault option instead. - */ + /** * Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. * @deprecated Use the useColorAsDefault option instead. */ mainColor?: boolean; /** Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. */ useColorAsDefault?: boolean; @@ -3113,13 +3429,12 @@ declare module DevExpress.ui { displayExpr?: any; /** Specifies the resource object field that is used as a value of the Resource editor in the Appointment popup window. */ valueExpr?: any; - /** - * The name of the appointment object field that specifies a resource of this kind. - * @deprecated Use the fieldExpr option instead. - */ + /** * The name of the appointment object field that specifies a resource of this kind. * @deprecated Use the fieldExpr option instead. */ field?: string; /** The name of the appointment object field that specifies a resource of this kind. */ fieldExpr?: string; + /** Specifies the resource object field that is used as a resource color. */ + colorExpr?: string; /** Specifies the label of the Appointment popup window field that allows end users to assign a resource of this kind. */ label?: string; }>; @@ -3178,7 +3493,9 @@ declare module DevExpress.ui { noDataText?: string; } /** A widget that displays scheduled data using different views and provides the capability to load, add and edit appointments. */ - export class dxScheduler extends Widget { + export class dxScheduler extends Widget + implements DataHelperMixin + { constructor(element: JQuery, options?: dxSchedulerOptions); constructor(element: Element, options?: dxSchedulerOptions); /** Add the appointment defined by the object passed as a parameter to the data associated with the widget. */ @@ -3189,12 +3506,21 @@ declare module DevExpress.ui { deleteAppointment(appointment: Object): void; /** Scrolls the scheduler work space to the specified time of the specified day. */ scrollToTime(hours: number, minutes: number, date: Date): void; - /** Displayes the Appointment Details popup. */ + /** Displays the Appointment Details popup. */ showAppointmentPopup(appointmentData: Object, createNewAppointment?: boolean, currentAppointmentData?: Object): void; + /** Hides an appointment details popup. */ + hideAppointmentPopup(saveChanges?: boolean): void; + /** Displays the appointment tooltip for the specified target element. */ + showAppointmentTooltip(appointmentData: Object, target?: JQuery, currentAppointmentData?: Object): void; + showAppointmentTooltip(appointmentData: Object, target?: Element, currentAppointmentData?: Object): void; + showAppointmentTooltip(appointmentData: Object, target?: string, currentAppointmentData?: Object): void; + /** Hides an appointment tooltip. */ + hideAppointmentTooltip(): void; /** Returns the start date of the current view. */ getStartViewDate(): Date; /** Returns the end date of the current view. */ getEndViewDate(): Date; + getDataSource(): DevExpress.data.DataSource; } export interface dxColorBoxOptions extends dxDropDownEditorOptions { /** Specifies the text displayed on the button that applies changes and closes the drop-down editor. */ @@ -3215,7 +3541,7 @@ declare module DevExpress.ui { export interface HierarchicalCollectionWidgetOptions extends CollectionWidgetOptions { /** Specifies the name of the data source item field whose value is displayed by the widget. */ displayExpr?: any; - /** Specifies the name of the data source item field used as a key. */ + /** Specifies which data field provides keys for TreeView items. */ keyExpr?: any; /** Specifies the name of the data source item field whose value defines whether or not the corresponding widget items is selected. */ selectedExpr?: any; @@ -3235,10 +3561,7 @@ declare module DevExpress.ui { dataStructure?: string; /** Specifies whether or not a user can expand all tree view items by the "*" hot key. */ expandAllEnabled?: boolean; - /** - * Specifies whether or not a check box is displayed at each tree view item. - * @deprecated Use the showCheckBoxesMode options instead. - */ + /** * Specifies whether or not a check box is displayed at each tree view item. * @deprecated Use the showCheckBoxesMode options instead. */ showCheckBoxes?: boolean; /** Specifies the current check boxes display mode. */ showCheckBoxesMode?: string; @@ -3248,10 +3571,7 @@ declare module DevExpress.ui { selectNodesRecursive?: boolean; /** Specifies whether or not all parent nodes of an initially expanded node are displayed expanded. */ expandNodesRecursive?: boolean; - /** - * Specifies whether the "Select All" check box is displayed over the tree view. - * @deprecated Use the showCheckBoxesMode options instead. - */ + /** * Specifies whether the "Select All" check box is displayed over the tree view. * @deprecated Use the showCheckBoxesMode options instead. */ selectAllEnabled?: boolean; /** Specifies whether or not an item becomes selected if a user clicks it. */ selectByClick?: boolean; @@ -3281,6 +3601,18 @@ declare module DevExpress.ui { onItemContextMenu?: Function; onItemRendered?: Function; onItemHold?: Function; + /** Allows you to load nodes manually. */ + createChildren?: Function; + } + export interface dxTreeViewNode { + children: Array; + disabled: boolean; + expanded: boolean; + itemData: Object; + key: any; + parent: dxTreeViewNode; + selected: boolean; + text: string; } /** A widget displaying specified data items as a tree. */ export class dxTreeView extends HierarchicalCollectionWidget { @@ -3317,11 +3649,8 @@ declare module DevExpress.ui { cssClass?: string; /** Holds an array of menu items. */ items?: Array; - /** - * Specifies whether or not an item becomes selected if an end-user clicks it. - * @deprecated Use the selectByClick option instead. - */ - selectionByClick?: boolean; + /** * Specifies whether or not an item becomes selected if an end-user clicks it. * @deprecated Use the selectByClick option instead. */ + selectionByClick?: boolean; /** Specifies whether or not an item becomes selected if a user clicks it. */ selectByClick?: boolean; /** Specifies the selection mode supported by the menu. */ @@ -3383,13 +3712,15 @@ declare module DevExpress.ui { constructor(element: Element, options?: dxMenuOptions); } export interface dxContextMenuOptions extends dxMenuBaseOptions { - /** Holds an object that specifies options of alternative menu invocation. */ - alternativeInvocationMode?: { - /** Specifies whether or not an alternative invocation mode is enabled. */ - enabled?: Boolean; - /** Specifies the element used to invoke the context menu. */ - invokingElement?: any; + /** Specifies options for displaying the widget. */ + showEvent?: { + /** Specifies the event names on which the widget is shown. */ + name?: String; + /** The time span after which the widget is shown. */ + delay?: Number; }; + /** A Boolean value specifying whether or not the widget is closed if a user clicks outside of the context menu. */ + closeOnOutsideClick?: any; /** A handler for the hidden event. */ onHidden?: Function; /** A handler for the hiding event. */ @@ -3429,6 +3760,8 @@ declare module DevExpress.ui { sorting?: boolean; /** Specifies whether or not grouping must be performed on the server side. */ grouping?: boolean; + /** Specifies whether or not paging by groups must be peformed on the server side. */ + groupPaging?: boolean; /** Specifies whether or not summaries calculation must be performed on the server side. */ summary?: boolean; } @@ -3440,6 +3773,7 @@ declare module DevExpress.ui { groupIndex: number; isExpanded: boolean; isSelected: boolean; + isEditing: boolean; values: Array; } export interface dxDataGridColumn { @@ -3472,7 +3806,7 @@ declare module DevExpress.ui { /** Specifies a callback function to be invoked after the cell value is edited by an end-user and before the new value is saved to the data source. */ setCellValue?: (rowData: Object, value: any) => void; /** Specifies a callback function that defines filters for customary calculated grid cells. */ - calculateFilterExpression?: (filterValue: any, selectedFilterOperation: string, target: string) => Array; + calculateFilterExpression?: (filterValue: any, selectedFilterOperation: string, target: string) => any; /** Specifies a caption for a column. */ caption?: string; /** Specifies a custom template for grid column cells. */ @@ -3539,10 +3873,7 @@ declare module DevExpress.ui { /** Specifies how header filter values should be combined into groups. */ groupInterval?: any; }; - /** - * Specifies a precision for formatted values displayed in a column. - * @deprecated Use the format | precision option instead. - */ + /** * Specifies a precision for formatted values displayed in a column. * @deprecated Use the format | precision option instead. */ precision?: number; /** Specifies the default filter operation of a column. */ selectedFilterOperation?: string; @@ -3586,6 +3917,8 @@ declare module DevExpress.ui { onRowValidating?: (e: Object) => void; /** A handler for the contextMenuPreparing event. */ onContextMenuPreparing?: (e: Object) => void; + /** A handler for the toolbarPreparing event. */ + onToolbarPreparing?: (e: Object) => void; /** A handler for the initNewRow event. */ onInitNewRow?: (e: { data: Object }) => void; /** A handler for the rowInserted event. */ @@ -3742,16 +4075,28 @@ declare module DevExpress.ui { applyFilterText?: string; /** Specifies descriptions for filter operations. */ operationDescriptions?: { - "=": string; - "<>": string; - "<": string; - "<=": string; - ">": string; - ">=": string; - "startswith": string; - "contains": string; - "notcontains": string; - "endswith": string; + /** Description for the '=' operation. */ + equal?: string; + /** Description for the '<>' operation. */ + notEqual?: string; + /** Description for the '<' operation. */ + lessThan?: string; + /** Description for the '<=' operation. */ + lessThanOrEqual?: string; + /** Description for the '>' operation. */ + greaterThan?: string; + /** Description for the '>=' operation. */ + greaterThanOrEqual?: string; + /** Description for the 'startswith' operation. */ + startsWith?: string; + /** Description for the 'contains' operation. */ + contains?: string; + /** Description for the 'notcontains' operation. */ + notContains?: string; + /** Description for the 'endswith' operation. */ + endsWith?: string; + /** Description for the 'between' operation. */ + between?: string; }; /** Specifies text for the reset operation in a filter list. */ resetOperationText?: string; @@ -3884,7 +4229,7 @@ declare module DevExpress.ui { /** Sets a search string for the search panel. */ text?: string; }; - /** Specifies the operations that must be performed on the server side. */ + /** Specifies the operations that must be performed server side. */ remoteOperations?: any; /** Allows you to sort groups according to the values of group summary items. */ sortByGroupSummaryInfo?: Array<{ @@ -3931,8 +4276,10 @@ declare module DevExpress.ui { exportSelectedRows?: string; } }; - /** Specifies the keys of the records that must appear selected initially. */ + /** Specifies the keys of the records that must appear initially selected. */ selectedRowKeys?: Array; + /** Specifies filters for the records that must appear initially selected. */ + selectionFilter?: Object; /** Specifies options of runtime selection. */ selection?: { /** Specifies the checkbox row display policy in the multiple mode. */ @@ -3941,6 +4288,11 @@ declare module DevExpress.ui { allowSelectAll?: boolean; /** Specifies the selection mode. */ mode?: string; + maxFilterLengthInRequest?: number; + /** Specifies the mode in which all the records are selected. */ + selectAllMode?: string; + /** Specifies whether or not deferred row selection is enabled. */ + deferred?: boolean; }; /** A handler for the dataErrorOccured event. */ onDataErrorOccurred?: (e: { error: Error }) => void; @@ -4043,10 +4395,7 @@ declare module DevExpress.ui { }) => string; /** Specifies a pattern for the summary item text. */ displayFormat?: string; - /** - * Specifies a precision for the summary item value of a numeric format. - * @deprecated Use the valueFormat | precision option instead. - */ + /** * Specifies a precision for the summary item value of a numeric format. * @deprecated Use the valueFormat | precision option instead. */ precision?: number; /** Specifies whether or not a summary item must be displayed in the group footer. */ showInGroupFooter?: boolean; @@ -4078,10 +4427,7 @@ declare module DevExpress.ui { }) => string; /** Specifies a pattern for the summary item text. */ displayFormat?: string; - /** - * Specifies a precision for the summary item value of a numeric format. - * @deprecated Use the valueFormat | precision option instead. - */ + /** * Specifies a precision for the summary item value of a numeric format. * @deprecated Use the valueFormat | precision option instead. */ precision?: number; /** Specifies the column that must hold the summary item. */ showInColumn?: string; @@ -4107,7 +4453,7 @@ declare module DevExpress.ui { wordWrapEnabled?: boolean; } /** A data grid widget. */ - export class dxDataGrid extends Widget { + export class dxDataGrid extends Widget implements DataHelperMixin { constructor(element: JQuery, options?: dxDataGridOptions); constructor(element: Element, options?: dxDataGridOptions); /** Ungroups grid records. */ @@ -4118,6 +4464,8 @@ declare module DevExpress.ui { getCellElement(rowIndex: number, dataField: string): any; /** Allows you to obtain a cell by its row index and the visible index of its column. */ getCellElement(rowIndex: number, visibleColumnIndex: number): any; + /** Allows you to obtain a row element by its index. */ + getRowElement(rowIndex: number): any; /** Returns the current state of the grid. */ state(): Object; /** Sets the grid state. */ @@ -4154,6 +4502,12 @@ declare module DevExpress.ui { columnOption(id: any): Object; /** Sets several options of a column at once. */ columnOption(id: any, options: Object): void; + /** Gets an array of visible columns. */ + getVisibleColumns(): Array; + /** Gets an array of visible columns at a specific hierarchical level of column headers. */ + getVisibleColumns(headerLevel?: number): Array; + /** Gets an array of visible rows. */ + getVisibleRows(): Array; /** Sets a specific cell into the editing state. */ editCell(rowIndex: number, visibleColumnIndex: number): void; /** Sets a specific cell into the editing state. */ @@ -4188,20 +4542,19 @@ declare module DevExpress.ui { filter(filterExpr?: any): void; /** Returns a filter expression applied to the grid's data source using the filter(filterExpr) method. */ filter(): any; - /** Returns a filter expression applied to the grid using all possible scenarious. */ + /** Returns a filter expression applied to the grid using all possible scenarios. */ getCombinedFilter(): any; + /** Returns a filter expression applied to the grid using all possible scenarios. */ + getCombinedFilter(returnDataField?: boolean): any; /** Gets the keys of currently selected grid records. */ - getSelectedRowKeys(): Array; - /** Gets the data objects of currently selected grid records. */ - getSelectedRowsData(): Array; + getSelectedRowKeys(): any; + /** Gets the data objects of the currently selected grid records. */ + getSelectedRowsData(): any; /** Hides the column chooser panel. */ hideColumnChooser(): void; /** Adds a new data row to a grid. */ addRow(): void; - /** - * Adds a new data row to a grid. - * @deprecated Use the addRow() method instead. - */ + /** * Adds a new data row to a grid. * @deprecated Use the addRow() method instead. */ insertRow(): void; /** Returns the key corresponding to the passed data object. */ keyOf(obj: Object): any; @@ -4217,10 +4570,7 @@ declare module DevExpress.ui { refresh(): JQueryPromise; /** Removes a specific row from a grid. */ deleteRow(rowIndex: number): void; - /** - * Removes a specific row from a grid. - * @deprecated Use the deleteRow(rowIndex) method instead. - */ + /** * Removes a specific row from a grid. * @deprecated Use the deleteRow(rowIndex) method instead. */ removeRow(rowIndex: number): void; /** Saves changes made in a grid. */ saveEditData(): JQueryPromise; @@ -4228,7 +4578,7 @@ declare module DevExpress.ui { searchByText(text: string): void; /** Selects all grid records. */ selectAll(): void; - /** Deselects the rows that are currently selected within the applied filter. */ + /** Deselects the currently selected rows. */ deselectAll(): void; /** Selects specific grid records. */ selectRows(keys: Array, preserve: boolean): void; @@ -4236,8 +4586,8 @@ declare module DevExpress.ui { deselectRows(keys: Array): void; /** Selects grid rows by indexes. */ selectRowsByIndexes(indexes: Array): void; - /** Allows you to find out whether a row is selected or not. */ - isRowSelected(key: any): boolean; + /** Allows you to find out whether or not the row with a specified data object is selected. */ + isRowSelected(arg: any): boolean; /** Invokes the column chooser panel. */ showColumnChooser(): void; startSelectionWithCheckboxes(): boolean; @@ -4257,6 +4607,11 @@ declare module DevExpress.ui { updateDimensions(): void; /** Focuses the specified cell element in the grid. */ focus(element?: JQuery): void; + getDataSource(): DevExpress.data.DataSource; + /** Gets instance of the Scrollable widget. */ + getScrollable(): dxScrollable; + /** Redraws the specified rows. */ + repaintRows(rowIndexes: Array): void; } export interface dxPivotGridOptions extends WidgetOptions { onContentReady?: Function; @@ -4492,53 +4847,6 @@ declare module DevExpress.ui { getDataSource(): DevExpress.data.PivotGridDataSource; } } -interface JQuery { - dxTreeView(): JQuery; - dxTreeView(options: "instance"): DevExpress.ui.dxTreeView; - dxTreeView(options: string): any; - dxTreeView(options: string, ...params: any[]): any; - dxTreeView(options: DevExpress.ui.dxTreeViewOptions): JQuery; - dxMenuBase(): JQuery; - dxMenuBase(options: "instance"): DevExpress.ui.dxMenuBase; - dxMenuBase(options: string): any; - dxMenuBase(options: string, ...params: any[]): any; - dxMenuBase(options: DevExpress.ui.dxMenuBaseOptions): JQuery; - dxMenu(): JQuery; - dxMenu(options: "instance"): DevExpress.ui.dxMenu; - dxMenu(options: string): any; - dxMenu(options: string, ...params: any[]): any; - dxMenu(options: DevExpress.ui.dxMenuOptions): JQuery; - dxContextMenu(): JQuery; - dxContextMenu(options: "instance"): DevExpress.ui.dxContextMenu; - dxContextMenu(options: string): any; - dxContextMenu(options: string, ...params: any[]): any; - dxContextMenu(options: DevExpress.ui.dxContextMenuOptions): JQuery; - dxColorBox(): JQuery; - dxColorBox(options: "instance"): DevExpress.ui.dxColorBox; - dxColorBox(options: string): any; - dxColorBox(options: string, ...params: any[]): any; - dxColorBox(options: DevExpress.ui.dxColorBoxOptions): JQuery; - dxDataGrid(): JQuery; - dxDataGrid(options: "instance"): DevExpress.ui.dxDataGrid; - dxDataGrid(options: string): any; - dxDataGrid(options: string, ...params: any[]): any; - dxDataGrid(options: DevExpress.ui.dxDataGridOptions): JQuery; - dxPivotGrid(): JQuery; - dxPivotGrid(options: "instance"): DevExpress.ui.dxPivotGrid; - dxPivotGrid(options: string): any; - dxPivotGrid(options: string, ...params: any[]): any; - dxPivotGrid(options: DevExpress.ui.dxPivotGridOptions): JQuery; - dxPivotGridFieldChooser(): JQuery; - dxPivotGridFieldChooser(options: "instance"): DevExpress.ui.dxPivotGridFieldChooser; - dxPivotGridFieldChooser(options: string): any; - dxPivotGridFieldChooser(options: string, ...params: any[]): any; - dxPivotGridFieldChooser(options: DevExpress.ui.dxPivotGridFieldChooserOptions): JQuery; - dxScheduler(): JQuery; - dxScheduler(options: "instance"): DevExpress.ui.dxScheduler; - dxScheduler(options: string): any; - dxScheduler(options: string, ...params: any[]): any; - dxScheduler(options: DevExpress.ui.dxSchedulerOptions): JQuery; -} declare module DevExpress.framework { /** An object used to store information on the views displayed in an application. */ export class ViewCache { @@ -4960,10 +5268,7 @@ declare module DevExpress.viz.core { paddingLeftRight?: number; /** Generates space above and below the text displayed by a tooltip. */ paddingTopBottom?: number; - /** - * Specifies the precision of formatted values in a tooltip. - * @deprecated Use the tooltip | format | precision option instead. - */ + /** * Specifies the precision of formatted values in a tooltip. * @deprecated Use the tooltip | format | precision option instead. */ precision?: number; /** Specifies the appearance of the tooltip's shadow. */ shadow?: { @@ -5092,35 +5397,17 @@ declare module DevExpress.viz.core { } } declare module DevExpress.viz { - /** - * Applies a theme for the entire page with several DevExtreme visualization widgets. - * @deprecated Use the DevExpress.viz.currentTheme(theme) method instead. - */ + /** * Applies a theme for the entire page with several DevExtreme visualization widgets. * @deprecated Use the DevExpress.viz.currentTheme(theme) method instead. */ export function currentTheme(theme: string): void; - /** - * Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets. - * @deprecated Use the DevExpress.viz.currentTheme(platform, colorScheme) method instead. - */ + /** * Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets. * @deprecated Use the DevExpress.viz.currentTheme(platform, colorScheme) method instead. */ export function currentTheme(platform: string, colorScheme: string): void; - /** - * Registers a new theme based on the existing one. - * @deprecated Use the DevExpress.viz.registerTheme(customTheme, baseTheme) method instead. - */ + /** * Registers a new theme based on the existing one. * @deprecated Use the DevExpress.viz.registerTheme(customTheme, baseTheme) method instead. */ export function registerTheme(customTheme: Object, baseTheme: string): void; - /** - * Applies a predefined or registered custom palette to all visualization widgets at once. - * @deprecated Use the DevExpress.viz.currentPalette(paletteName) method instead. - */ + /** * Applies a predefined or registered custom palette to all visualization widgets at once. * @deprecated Use the DevExpress.viz.currentPalette(paletteName) method instead. */ export function currentPalette(paletteName: string): void; - /** - * Obtains the color sets of a predefined or registered palette. - * @deprecated Use the DevExpress.viz.getPalette(paletteName) method instead. - */ + /** * Obtains the color sets of a predefined or registered palette. * @deprecated Use the DevExpress.viz.getPalette(paletteName) method instead. */ export function getPalette(paletteName: string): Object; - /** - * Registers a new palette. - * @deprecated Use the DevExpress.viz.registerPalette(paletteName, palette) method instead. - */ + /** * Registers a new palette. * @deprecated Use the DevExpress.viz.registerPalette(paletteName, palette) method instead. */ export function registerPalette(paletteName: string, palette: Object): void; } declare module DevExpress.viz.charts { @@ -5277,10 +5564,7 @@ declare module DevExpress.viz.charts { export interface BaseSeriesConfigLabel { /** Specifies a format for arguments displayed by point labels. */ argumentFormat?: any; - /** - * Specifies a precision for formatted point arguments displayed in point labels. - * @deprecated Use the series | label | argumentFormat | precision instead. - */ + /** * Specifies a precision for formatted point arguments displayed in point labels. * @deprecated Use the series | label | argumentFormat | precision instead. */ argumentPrecision?: number; /** Specifies a background color for point labels. */ backgroundColor?: string; @@ -5302,10 +5586,7 @@ declare module DevExpress.viz.charts { /** Specifies a format for the text displayed by point labels. */ format?: any; position?: string; - /** - * Specifies a precision for formatted point values displayed in point labels. - * @deprecated Use the series | label | format | precision option instead. - */ + /** * Specifies a precision for formatted point values displayed in point labels. * @deprecated Use the series | label | format | precision option instead. */ precision?: number; /** Specifies the angle used to rotate point labels from their initial position. */ rotationAngle?: number; @@ -5323,10 +5604,7 @@ declare module DevExpress.viz.charts { horizontalOffset?: number; /** Along with horizontalOffset, shifts point labels from their initial positions. */ verticalOffset?: number; - /** - * Specifies a precision for the percentage values displayed in the labels of a full-stacked-like series. - * @deprecated Use the series | label | format | percentPrecision instead. - */ + /** * Specifies a precision for the percentage values displayed in the labels of a full-stacked-like series. * @deprecated Use the series | label | format | percentPrecision instead. */ percentPrecision?: number; } export interface BaseCommonSeriesConfig { @@ -5580,10 +5858,7 @@ declare module DevExpress.viz.charts { export interface PieSeriesConfigLabel extends BaseSeriesConfigLabel { /** Specifies how to shift labels from their initial position in a radial direction in pixels. */ radialOffset?: number; - /** - * Specifies a precision for the percentage values displayed in labels. - * @deprecated Use the series | label | format | percentPrecision instead. - */ + /** * Specifies a precision for the percentage values displayed in labels. * @deprecated Use the series | label | format | percentPrecision instead. */ percentPrecision?: number; } /** An object that defines configuration options for chart series. */ @@ -5607,10 +5882,7 @@ declare module DevExpress.viz.charts { /** Specifies the hatching options to be applied when a point is hovered over. */ hatching?: viz.core.Hatching; }; - /** - * Specifies the fraction of the inner radius relative to the total radius in the series of the 'doughnut' type. - * @deprecated Use the innerRadius option instead. - */ + /** * Specifies the fraction of the inner radius relative to the total radius in the series of the 'doughnut' type. * @deprecated Use the innerRadius option instead. */ innerRadius?: number; /** An object defining the label configuration options. */ label?: PieSeriesConfigLabel; @@ -5618,10 +5890,7 @@ declare module DevExpress.viz.charts { maxLabelCount?: number; /** Specifies a minimal size of a displayed pie segment. */ minSegmentSize?: number; - /** - * Specifies the direction in which the PieChart series points are located. - * @deprecated Use the segmentsDirection option instead. - */ + /** * Specifies the direction in which the PieChart series points are located. * @deprecated Use the segmentsDirection option instead. */ segmentsDirection?: string; /**

Specifies the chart elements to highlight when the series is selected.

*/ selectionMode?: string; @@ -5645,10 +5914,7 @@ declare module DevExpress.viz.charts { /** Specifies how many segments must not be grouped. */ topCount?: number; }; - /** - * Specifies a start angle for a pie chart in arc degrees. - * @deprecated Use the startAngle option instead. - */ + /** * Specifies a start angle for a pie chart in arc degrees. * @deprecated Use the startAngle option instead. */ startAngle?: number; /**

Specifies the name of the data source field that provides data about a point.

*/ tagField?: string; @@ -5656,17 +5922,11 @@ declare module DevExpress.viz.charts { valueField?: string; } export interface CommonPieSeriesSettings extends CommonPieSeriesConfig { - /** - * Specifies the type of the pie chart series. - * @deprecated Use the type option instead. - */ + /** * Specifies the type of the pie chart series. * @deprecated Use the type option instead. */ type?: string; } export interface PieSeriesConfig extends CommonPieSeriesConfig { - /** - * Sets the series type. - * @deprecated Use the type option instead. - */ + /** * Sets the series type. * @deprecated Use the type option instead. */ type?: string; /** Specifies the name that identifies the series. */ name?: string; @@ -5879,10 +6139,7 @@ declare module DevExpress.viz.charts { customizeText?: (argument: { value: any; valueText: string }) => string; /** Specifies a format for the text displayed by axis labels. */ format?: any; - /** - * Specifies a precision for the formatted value displayed in the axis labels. - * @deprecated Use the valueAxis | label | format | precision option instead. - */ + /** * Specifies a precision for the formatted value displayed in the axis labels. * @deprecated Use the valueAxis | label | format | precision option instead. */ precision?: number; } export interface ChartAxisLabel extends ChartCommonAxisLabel, AxisLabel { } @@ -6018,15 +6275,9 @@ declare module DevExpress.viz.charts { export interface BaseChartTooltip extends viz.core.Tooltip { /** Specifies a format for arguments of the chart's series points. */ argumentFormat?: any; - /** - * Specifies a precision for formatted arguments displayed in tooltips. - * @deprecated Use the tooltip | argumentFormat | precision option instead. - */ + /** * Specifies a precision for formatted arguments displayed in tooltips. * @deprecated Use the tooltip | argumentFormat | precision option instead. */ argumentPrecision?: number; - /** - * Specifies a precision for a percent value displayed in tooltips for stacked series and PieChart series. - * @deprecated Use the tooltip | format | percentPrecision option instead. - */ + /** * Specifies a precision for a percent value displayed in tooltips for stacked series and PieChart series. * @deprecated Use the tooltip | format | percentPrecision option instead. */ percentPrecision?: number; } export interface BaseChartOptions extends viz.core.BaseWidgetOptions, viz.core.MarginOptions, viz.core.RedrawOnResizeOptions, viz.core.TitleOptions, viz.core.LoadingIndicatorOptions, viz.core.ExportOptions { @@ -6047,7 +6298,7 @@ declare module DevExpress.viz.charts { customizePoint?: (pointInfo: Object) => Object; /** Specifies the origin of data for the widget. */ dataSource?: any; - /** Specifies options of a Chart's or PieChart's legend. */ + /** Specifies options of a Chart's (PieChart's) legend. */ legend?: core.BaseLegend; /** Sets the name of the palette to be used in the chart. Alternatively, an array of colors can be set as a custom palette to be used within this chart. */ palette?: any; @@ -6101,6 +6352,8 @@ declare module DevExpress.viz.charts { getSeriesByName(seriesName: string): BaseSeries; /** Gets a series within the chart's series collection by its position number. */ getSeriesByPos(seriesIndex: number): BaseSeries; + /** Returns the DataSource instance. */ + getDataSource(): DevExpress.data.DataSource; /** Hides all widget tooltips. */ hideTooltip(): void; showLoadingIndicator(): void; @@ -6199,9 +6452,9 @@ declare module DevExpress.viz.charts { /** Specifies the width of the crosshair lines. */ width?: number; /** Configures the horizontal crosshair line individually. */ - horizontalLine?: CrosshaierWithLabel; + horizontalLine?: CrosshairWithLabel; /** Configures the vertical crosshair line individually. */ - verticalLine?: CrosshaierWithLabel; + verticalLine?: CrosshairWithLabel; /** Configures the crosshair labels. */ label?: { /** Paints the background of the crosshair labels. */ @@ -6212,10 +6465,7 @@ declare module DevExpress.viz.charts { font?: viz.core.Font; /** Formats the point value/argument before it will be displayed in the crosshair label. */ format?: any; - /** - * Specifies a precision for formatted values. - * @deprecated Use the crosshair | label | format | precision option instead. - */ + /** * Specifies a precision for formatted values. * @deprecated Use the crosshair | label | format | precision option instead. */ precision?: number; /** Customizes the text displayed by the crosshair labels. */ customizeText?: (info: { value: any; valueText: string; point: ChartPoint; }) => string; @@ -6272,7 +6522,7 @@ declare module DevExpress.viz.charts { position?: string; }; } - interface CrosshaierWithLabel extends viz.core.DashedBorderWithOpacity { + interface CrosshairWithLabel extends viz.core.DashedBorderWithOpacity { /** Configures the label that belongs to the horizontal crosshair line. */ label?: { /** Paints the background of the label that belongs to the horizontal crosshair line. */ @@ -6283,10 +6533,7 @@ declare module DevExpress.viz.charts { font?: viz.core.Font; /** Formats the point value before it will be displayed in the crosshair label. */ format?: any; - /** - * Specifies a precision for formatted values. - * @deprecated Use the crosshair | horizontalLine | label | format | precision option instead. - */ + /** * Specifies a precision for formatted values. * @deprecated Use the crosshair | horizontalLine | label | format | precision option instead. */ precision?: number; /** Customizes the text displayed by the label that belongs to the horizontal crosshair line. */ customizeText?: (info: { value: any; valueText: string; point: ChartPoint; }) => string; @@ -6367,10 +6614,7 @@ declare module DevExpress.viz { export class dxPieChart extends DevExpress.viz.charts.BaseChart { constructor(element: JQuery, options?: DevExpress.viz.charts.dxPieChartOptions); constructor(element: Element, options?: DevExpress.viz.charts.dxPieChartOptions); - /** - * Provides access to the PieChart series. - * @deprecated Use the getAllSeries() method instead. - */ + /** * Provides access to the PieChart series. * @deprecated Use the getAllSeries() method instead. */ getSeries(): DevExpress.viz.charts.PieSeries; } /** A chart widget displaying data in a polar coordinate system. */ @@ -6379,17 +6623,6 @@ declare module DevExpress.viz { constructor(element: Element, options?: DevExpress.viz.charts.dxPolarChartOptions); } } -interface JQuery { - dxChart(options?: DevExpress.viz.charts.dxChartOptions): JQuery; - dxChart(methodName: string, ...params: any[]): any; - dxChart(methodName: "instance"): DevExpress.viz.dxChart; - dxPieChart(options?: DevExpress.viz.charts.dxPieChartOptions): JQuery; - dxPieChart(methodName: string, ...params: any[]): any; - dxPieChart(methodName: "instance"): DevExpress.viz.dxPieChart; - dxPolarChart(options?: DevExpress.viz.charts.dxPolarChartOptions): JQuery; - dxPolarChart(methodName: string, ...params: any[]): any; - dxPolarChart(methodName: "instance"): DevExpress.viz.dxPolarChart; -} declare module DevExpress.viz.gauges { export interface BaseRangeContainer { /** Specifies a range container's background color. */ @@ -6410,22 +6643,13 @@ declare module DevExpress.viz.gauges { export interface ScaleTick { /** Specifies the color of the scale's minor ticks. */ color?: string; - /** - * Specifies an array of custom minor ticks. - * @deprecated Use the scale | customMinorTicks option instead. - */ + /** * Specifies an array of custom minor ticks. * @deprecated Use the scale | customMinorTicks option instead. */ customTickValues?: Array; /** Specifies the length of the scale's minor ticks. */ length?: number; - /** - * Indicates whether automatically calculated minor ticks are visible or not. - * @deprecated This feature is no longer available. - */ + /** * Indicates whether automatically calculated minor ticks are visible or not. * @deprecated This feature is no longer available. */ showCalculatedTicks?: boolean; - /** - * Specifies an interval between minor ticks. - * @deprecated Use the scale | minorTickInterval option instead. - */ + /** * Specifies an interval between minor ticks. * @deprecated Use the scale | minorTickInterval option instead. */ tickInterval?: number; /** Indicates whether scale minor ticks are visible or not. */ visible?: boolean; @@ -6433,10 +6657,7 @@ declare module DevExpress.viz.gauges { width?: number; } export interface ScaleMajorTick extends ScaleTick { - /** - * Specifies whether or not to expand the current major tick interval if labels overlap each other. - * @deprecated Use the overlappingBehavior | useAutoArrangement option instead. - */ + /** * Specifies whether or not to expand the current major tick interval if labels overlap each other. * @deprecated Use the overlappingBehavior | useAutoArrangement option instead. */ useTicksAutoArrangement?: boolean; } export interface ScaleMinorTick extends ScaleTick { @@ -6459,10 +6680,7 @@ declare module DevExpress.viz.gauges { font?: viz.core.Font; /** Specifies a format for the text displayed in scale labels. */ format?: any; - /** - * Specifies a precision for the formatted value displayed in the scale labels. - * @deprecated Use the scale | label | format | precision option instead. - */ + /** * Specifies a precision for the formatted value displayed in the scale labels. * @deprecated Use the scale | label | format | precision option instead. */ precision?: number; /** Specifies whether or not scale labels are visible on the gauge. */ visible?: boolean; @@ -6470,25 +6688,13 @@ declare module DevExpress.viz.gauges { export interface BaseScale { /** Specifies the end value for the scale of the gauge. */ endValue?: number; - /** - * Specifies whether or not to hide the first scale label. - * @deprecated This feature is no longer available. - */ + /** * Specifies whether or not to hide the first scale label. * @deprecated This feature is no longer available. */ hideFirstLabel?: boolean; - /** - * Specifies whether or not to hide the first major tick on the scale. - * @deprecated This feature is no longer available. - */ + /** * Specifies whether or not to hide the first major tick on the scale. * @deprecated This feature is no longer available. */ hideFirstTick?: boolean; - /** - * Specifies whether or not to hide the last scale label. - * @deprecated This feature is no longer available. - */ + /** * Specifies whether or not to hide the last scale label. * @deprecated This feature is no longer available. */ hideLastLabel?: boolean; - /** - * Specifies whether or not to hide the last major tick on the scale. - * @deprecated This feature is no longer available. - */ + /** * Specifies whether or not to hide the last major tick on the scale. * @deprecated This feature is no longer available. */ hideLastTick?: boolean; /** Specifies an interval between major ticks. */ tickInterval?: number; @@ -6500,10 +6706,7 @@ declare module DevExpress.viz.gauges { customMinorTicks?: Array; /** Specifies common options for scale labels. */ label?: BaseScaleLabel; - /** - * Specifies options of the gauge's major ticks. - * @deprecated Use the tick option instead. - */ + /** * Specifies options of the gauge's major ticks. * @deprecated Use the tick option instead. */ majorTick?: ScaleMajorTick; /** Specifies options of the gauge's major ticks. */ tick?: { @@ -6542,10 +6745,7 @@ declare module DevExpress.viz.gauges { format?: any; /** Specifies the range bar's label indent in pixels. */ indent?: number; - /** - * Specifies a precision for the formatted value displayed by an indicator. - * @deprecated Use the text | format | precision option instead. - */ + /** * Specifies a precision for the formatted value displayed by an indicator. * @deprecated Use the text | format | precision option instead. */ precision?: number; }; offset?: number; @@ -6573,20 +6773,11 @@ declare module DevExpress.viz.gauges { export interface SharedGaugeOptions extends viz.core.MarginOptions, viz.core.RedrawOnResizeOptions, viz.core.TitleOptions, viz.core.LoadingIndicatorOptions, viz.core.ExportOptions { /** Specifies animation options. */ animation?: viz.core.Animation; - /** - * Specifies a subtitle for the widget. - * @deprecated Use the title | subtitle option instead. - */ + /** * Specifies a subtitle for the widget. * @deprecated Use the title | subtitle option instead. */ subtitle?: { - /** - * Specifies font options for the subtitle. - * @deprecated Use the title | subtitle | font option instead. - */ + /** * Specifies font options for the subtitle. * @deprecated Use the title | subtitle | font option instead. */ font?: viz.core.Font; - /** - * Specifies a text for the subtitle. - * @deprecated Use the title | subtitle | text option instead. - */ + /** * Specifies a text for the subtitle. * @deprecated Use the title | subtitle | text option instead. */ text?: string; }; /** Configures tooltips. */ @@ -6723,10 +6914,7 @@ declare module DevExpress.viz.gauges { format?: any; /** Specifies the distance between the upper bar and bar labels in pixels. */ indent?: number; - /** - * Specifies a precision for the formatted value displayed by labels. - * @deprecated Use the label | format | precision option instead. - */ + /** * Specifies a precision for the formatted value displayed by labels. * @deprecated Use the label | format | precision option instead. */ precision?: number; /** Specifies whether bar labels appear on a gauge or not. */ visible?: boolean; @@ -6764,17 +6952,6 @@ declare module DevExpress.viz { values(values: Array): void; } } -interface JQuery { - dxLinearGauge(options?: DevExpress.viz.gauges.dxLinearGaugeOptions): JQuery; - dxLinearGauge(methodName: string, ...params: any[]): any; - dxLinearGauge(methodName: "instance"): DevExpress.viz.dxLinearGauge; - dxCircularGauge(options?: DevExpress.viz.gauges.dxCircularGaugeOptions): JQuery; - dxCircularGauge(methodName: string, ...params: any[]): any; - dxCircularGauge(methodName: "instance"): DevExpress.viz.dxCircularGauge; - dxBarGauge(options?: DevExpress.viz.gauges.dxBarGaugeOptions): JQuery; - dxBarGauge(methodName: string, ...params: any[]): any; - dxBarGauge(methodName: "instance"): DevExpress.viz.dxBarGauge; -} declare module DevExpress.viz.rangeSelector { export interface dxRangeSelectorOptions extends viz.core.BaseWidgetOptions, viz.core.MarginOptions, viz.core.RedrawOnResizeOptions, viz.core.TitleOptions, viz.core.LoadingIndicatorOptions, viz.core.ExportOptions { /** Specifies the options for the range selector's background. */ @@ -6797,8 +6974,10 @@ declare module DevExpress.viz.rangeSelector { allowSlidersSwap?: boolean; /** Indicates whether or not animation is enabled. */ animationEnabled?: boolean; - /** Specifies when to call the onSelectedRangeChanged function. */ + /** * Specifies when to call the onSelectedRangeChanged function. * @deprecated Use the callValueChanged option instead. */ callSelectedRangeChanged?: string; + /** Specifies when to call the onValueChanged function. */ + callValueChanged?: string; /** Indicates whether or not an end user can specify the range using a mouse, without the use of sliders. */ manualRangeSelectionEnabled?: boolean; /** Indicates whether or not an end user can shift the selected range to the required location on a scale by clicking. */ @@ -6871,10 +7050,7 @@ declare module DevExpress.viz.rangeSelector { font?: viz.core.Font; /** Specifies a format for the text displayed in scale labels. */ format?: any; - /** - * Specifies a precision for the formatted value displayed in the scale labels. - * @deprecated Use the scale | label | format | precision option instead. - */ + /** * Specifies a precision for the formatted value displayed in the scale labels. * @deprecated Use the scale | label | format | precision option instead. */ precision?: number; /** Specifies a spacing between scale labels and the background bottom edge. */ topIndent?: number; @@ -6883,10 +7059,7 @@ declare module DevExpress.viz.rangeSelector { }; /** Specifies the value to be raised to a power when generating ticks for a logarithmic scale. */ logarithmBase?: number; - /** - * Specifies an interval between major ticks. - * @deprecated Use the tickInterval option instead. - */ + /** * Specifies an interval between major ticks. * @deprecated Use the tickInterval option instead. */ majorTickInterval?: any; /** Specifies an interval between axis ticks. */ tickInterval?: any; @@ -6924,10 +7097,7 @@ declare module DevExpress.viz.rangeSelector { setTicksAtUnitBeginning?: boolean; /** Specifies whether or not to show ticks for the boundary scale values, when neither major ticks nor minor ticks are created for these values. */ showCustomBoundaryTicks?: boolean; - /** - * Indicates whether or not to show minor ticks on the scale. - * @deprecated Use the minorTick | visible option instead. - */ + /** * Indicates whether or not to show minor ticks on the scale. * @deprecated Use the minorTick | visible option instead. */ showMinorTicks?: boolean; /** Specifies the scale's start value. */ startValue?: any; @@ -6957,16 +7127,18 @@ declare module DevExpress.viz.rangeSelector { useTicksAutoArrangement?: boolean; /** Specifies the type of values on the scale. */ valueType?: string; - /** Specifies the order of arguments on a discrete scale. */ - categories?: Array; + /** Specifies the order of arguments on a discrete scale. */ + categories?: Array; }; - /** Specifies the range to be selected when displaying the RangeSelector. */ + /** * Specifies the range to be selected when displaying the RangeSelector. * @deprecated Use the value option instead. */ selectedRange?: { /** Specifies the start value of the range to be selected when displaying the RangeSelector widget on a page. */ startValue?: any; /** Specifies the end value of the range to be selected when displaying the RangeSelector widget on a page. */ endValue?: any; }; + /** The selected range, initial or current. */ + value?: Array; /** Specifies the color of the selected range. */ selectedRangeColor?: string; /** Range selector's indent options. */ @@ -6976,13 +7148,20 @@ declare module DevExpress.viz.rangeSelector { /** Specifies range selector's right indent. */ right?: number; }; - /** A handler for the selectedRangeChanged event. */ + /** * A handler for the selectedRangeChanged event. * @deprecated Use the onValueChanged option instead. */ onSelectedRangeChanged?: (e: { startValue: any; endValue: any; component: dxRangeSelector; element: Element; }) => void; + /** A handler for the valueChanged event. */ + onValueChanged?: (e: { + value: Array; + previousValue: Array; + component: dxRangeSelector; + element: Element; + }) => void; /** Specifies range selector shutter options. */ shutter?: { /** Specifies shutter color. */ @@ -7011,10 +7190,7 @@ declare module DevExpress.viz.rangeSelector { format?: any; /** Specifies the color used for the slider marker text when the currently selected range does not match the minRange and maxRange values. */ invalidRangeColor?: string; - /** - * Specifies the empty space between the marker's border and the marker’s text. - * @deprecated Use the paddingTopBottom and paddingLeftRight options instead. - */ + /** * Specifies the empty space between the marker's border and the marker’s text. * @deprecated Use the paddingTopBottom and paddingLeftRight options instead. */ padding?: number; /** Specifies the empty space between the marker's top and bottom borders and the marker's text. */ paddingTopBottom?: number; @@ -7022,10 +7198,7 @@ declare module DevExpress.viz.rangeSelector { paddingLeftRight?: number; /** Specifies the placeholder height of the slider marker. */ placeholderHeight?: number; - /** - * Specifies in pixels the height and width of the space reserved for the range selector slider markers. - * @deprecated Use the placeholderHeight and indent options instead. - */ + /** * Specifies in pixels the height and width of the space reserved for the range selector slider markers. * @deprecated Use the placeholderHeight and indent options instead. */ placeholderSize?: { /** Specifies the height of the placeholder for the left and right slider markers. */ height?: number; @@ -7037,10 +7210,7 @@ declare module DevExpress.viz.rangeSelector { right?: number; }; }; - /** - * Specifies a precision for the formatted value displayed in slider markers. - * @deprecated Use the sliderMarker | format | precision option instead. - */ + /** * Specifies a precision for the formatted value displayed in slider markers. * @deprecated Use the sliderMarker | format | precision option instead. */ precision?: number; /** Indicates whether or not the slider markers are visible. */ visible?: boolean; @@ -7056,17 +7226,18 @@ declare module DevExpress.viz { hideLoadingIndicator(): void; /** Redraws a widget. */ render(skipChartAnimation?: boolean): void; - /** Returns the currently selected range. */ + /** * Returns the currently selected range. * @deprecated Use the getValue() method instead. */ getSelectedRange(): { startValue: any; endValue: any; }; - /** Sets a specified range. */ + /** * Sets a specified range. * @deprecated Use the setValue(value) method instead. */ setSelectedRange(selectedRange: { startValue: any; endValue: any; }): void; + /** Gets the currently selected range. */ + getValue(): Array; + /** Selects a specific range. */ + setValue(value: Array): void; + /** Returns the DataSource instance. */ + getDataSource(): DevExpress.data.DataSource; } } -interface JQuery { - dxRangeSelector(options?: DevExpress.viz.rangeSelector.dxRangeSelectorOptions): JQuery; - dxRangeSelector(methodName: string, ...params: any[]): any; - dxRangeSelector(methodName: "instance"): DevExpress.viz.dxRangeSelector; -} declare module DevExpress.viz.map { /** This section describes the fields and methods that can be used in code to manipulate the Layer object. */ export interface MapLayer { @@ -7082,6 +7253,8 @@ declare module DevExpress.viz.map { getElements(): Array; /** Deselects all layer elements. */ clearSelection(): void; + /** Returns the DataSource instance. */ + getDataSource(): DevExpress.data.DataSource; } /** This section describes the fields and methods that can be used in code to manipulate the Layer Element object. */ export interface MapLayerElement { @@ -7100,91 +7273,40 @@ declare module DevExpress.viz.map { /** Applies the layer element settings and updates element appearance. */ applySettings(settings: any): void; } - /** - * This section describes the fields and methods that can be used in code to manipulate the Area object. - * @deprecated Use the Layer Element instead. - */ + /** * This section describes the fields and methods that can be used in code to manipulate the Area object. * @deprecated Use the Layer Element instead. */ export interface Area { - /** - * Contains the element type. - * @deprecated Use the Layer | type instead. - */ + /** * Contains the element type. * @deprecated Use the Layer | type instead. */ type: string; - /** - * Return the value of an attribute. - * @deprecated Use the Layer Element | attribute(name, value) method instead. - */ + /** * Return the value of an attribute. * @deprecated Use the Layer Element | attribute(name, value) method instead. */ attribute(name: string): any; - /** - * Provides information about the selection state of an area. - * @deprecated Use the Layer Element | selected() method instead. - */ + /** * Provides information about the selection state of an area. * @deprecated Use the Layer Element | selected() method instead. */ selected(): boolean; - /** - * Sets a new selection state for an area. - * @deprecated Use the Layer Element | selected(state) method instead. - */ + /** * Sets a new selection state for an area. * @deprecated Use the Layer Element | selected(state) method instead. */ selected(state: boolean): void; - /** - * Applies the area settings specified as a parameter and updates the area appearance. - * @deprecated Use the Layer Element | applySettings(settings) method instead. - */ + /** * Applies the area settings specified as a parameter and updates the area appearance. * @deprecated Use the Layer Element | applySettings(settings) method instead. */ applySettings(settings: any): void; } - /** - * This section describes the fields and methods that can be used in code to manipulate the Markers object. - * @deprecated Use the Layer Element instead. - */ + /** * This section describes the fields and methods that can be used in code to manipulate the Markers object. * @deprecated Use the Layer Element instead. */ export interface Marker { - /** - * Contains the descriptive text accompanying the map marker. - * @deprecated Get the text using the Layer Element | attribute(name) method. The name parameter value for text is set at the dataField option. - */ + /** * Contains the descriptive text accompanying the map marker. * @deprecated Get the text using the Layer Element | attribute(name) method. The name parameter value for text is set at the dataField option. */ text: string; - /** - * Contains the type of the element. - * @deprecated Use the Layer | type instead. - */ + /** * Contains the type of the element. * @deprecated Use the Layer | type instead. */ type: string; - /** - * Contains the URL of an image map marker. - * @deprecated Get the image URL using the Layer Element | attribute(name) method. The name parameter value for the image URL is set at the dataField option. - */ + /** * Contains the URL of an image map marker. * @deprecated Get the image URL using the Layer Element | attribute(name) method. The name parameter value for the image URL is set at the dataField option. */ url: string; - /** - * Contains the value of a bubble map marker. - * @deprecated Get the bubble value using the Layer Element | attribute(name) method. The name parameter for the bubble value is set at the dataField option. - */ + /** * Contains the value of a bubble map marker. * @deprecated Get the bubble value using the Layer Element | attribute(name) method. The name parameter for the bubble value is set at the dataField option. */ value: number; - /** - * Contains the values of a pie map marker. - * @deprecated Get the pie values using the Layer Element | attribute(name) method. The name parameter for pie values is set at the dataField option. - */ + /** * Contains the values of a pie map marker. * @deprecated Get the pie values using the Layer Element | attribute(name) method. The name parameter for pie values is set at the dataField option. */ values: Array; - /** - * Returns the value of an attribute. - * @deprecated Use the Layer Element | attribute(name, value) method instead. - */ + /** * Returns the value of an attribute. * @deprecated Use the Layer Element | attribute(name, value) method instead. */ attribute(name: string): any; - /** - * Returns the coordinates of a specific marker. - * @deprecated Use the Layer Element | coordinates() method instead. - */ + /** * Returns the coordinates of a specific marker. * @deprecated Use the Layer Element | coordinates() method instead. */ coordinates(): Array; - /** - * Provides information about the selection state of a marker. - * @deprecated Use the Layer Element | selected() method instead. - */ + /** * Provides information about the selection state of a marker. * @deprecated Use the Layer Element | selected() method instead. */ selected(): boolean; - /** - * Sets a new selection state for a marker. - * @deprecated Use the Layer Element | selected(state) method instead. - */ + /** * Sets a new selection state for a marker. * @deprecated Use the Layer Element | selected(state) method instead. */ selected(state: boolean): void; - /** - * Applies the marker settings specified as a parameter and updates marker appearance. - * @deprecated Use the Layer Element | applySettings(settings) method instead. - */ + /** * Applies the marker settings specified as a parameter and updates marker appearance. * @deprecated Use the Layer Element | applySettings(settings) method instead. */ applySettings(settings: any): void; } export interface MapLayerSettings { @@ -7253,241 +7375,103 @@ declare module DevExpress.viz.map { }; } export interface AreaSettings { - /** - * Specifies the width of the area border in pixels. - * @deprecated Use the layers | borderWidth option instead. - */ + /** * Specifies the width of the area border in pixels. * @deprecated Use the layers | borderWidth option instead. */ borderWidth?: number; - /** - * Specifies a color for the area border. - * @deprecated Use the layers | borderColor option instead. - */ + /** * Specifies a color for the area border. * @deprecated Use the layers | borderColor option instead. */ borderColor?: string; - /** - * Specifies a color for an area. - * @deprecated Use the layers | color option instead. - */ + /** * Specifies a color for an area. * @deprecated Use the layers | color option instead. */ color?: string; - /** - * Specifies the function that customizes each area individually. - * @deprecated Use the layers | customize option instead. - */ + /** * Specifies the function that customizes each area individually. * @deprecated Use the layers | customize option instead. */ customize?: (areaInfo: Area) => AreaSettings; - /** - * Specifies a color for the area border when the area is hovered over. - * @deprecated Use the layers | hoveredBorderColor option instead. - */ + /** * Specifies a color for the area border when the area is hovered over. * @deprecated Use the layers | hoveredBorderColor option instead. */ hoveredBorderColor?: string; - /** - * Specifies the pixel-measured width of the area border when the area is hovered over. - * @deprecated Use the layers | hoveredBorderWidth option instead. - */ + /** * Specifies the pixel-measured width of the area border when the area is hovered over. * @deprecated Use the layers | hoveredBorderWidth option instead. */ hoveredBorderWidth?: number; - /** - * Specifies a color for an area when this area is hovered over. - * @deprecated Use the layers | hoveredColor option instead. - */ + /** * Specifies a color for an area when this area is hovered over. * @deprecated Use the layers | hoveredColor option instead. */ hoveredColor?: string; - /** - * Specifies whether or not to change the appearance of an area when it is hovered over. - * @deprecated Use the layers | hoverEnabled option instead. - */ + /** * Specifies whether or not to change the appearance of an area when it is hovered over. * @deprecated Use the layers | hoverEnabled option instead. */ hoverEnabled?: boolean; - /** - * Configures area labels. - * @deprecated Use the layers | label option instead. - */ + /** * Configures area labels. * @deprecated Use the layers | label option instead. */ label?: { - /** - * Specifies the data field that provides data for area labels. - * @deprecated Use the layers | label | dataField option instead. - */ + /** * Specifies the data field that provides data for area labels. * @deprecated Use the layers | label | dataField option instead. */ dataField?: string; - /** - * Enables area labels. - * @deprecated Use the layers | label | enabled option instead. - */ + /** * Enables area labels. * @deprecated Use the layers | label | enabled option instead. */ enabled?: boolean; - /** - * Specifies font options for area labels. - * @deprecated Use the layers | label | font option instead. - */ + /** * Specifies font options for area labels. * @deprecated Use the layers | label | font option instead. */ font?: viz.core.Font; }; - /** - * Specifies the name of the palette or a custom range of colors to be used for coloring a map. - * @deprecated Use the layers | palette option instead. - */ + /** * Specifies the name of the palette or a custom range of colors to be used for coloring a map. * @deprecated Use the layers | palette option instead. */ palette?: any; - /** - * Specifies the number of colors in a palette. - * @deprecated Use the layers | paletteSize option instead. - */ + /** * Specifies the number of colors in a palette. * @deprecated Use the layers | paletteSize option instead. */ paletteSize?: number; - /** - * Allows you to paint areas with similar attributes in the same color. - * @deprecated Use the layers | colorGroups option instead. - */ + /** * Allows you to paint areas with similar attributes in the same color. * @deprecated Use the layers | colorGroups option instead. */ colorGroups?: Array; - /** - * Specifies the field that provides data to be used for coloring areas. - * @deprecated Use the layers | colorGroupingField option instead. - */ + /** * Specifies the field that provides data to be used for coloring areas. * @deprecated Use the layers | colorGroupingField option instead. */ colorGroupingField?: string; - /** - * Specifies a color for the area border when the area is selected. - * @deprecated Use the layers | selectedBorderColor option instead. - */ + /** * Specifies a color for the area border when the area is selected. * @deprecated Use the layers | selectedBorderColor option instead. */ selectedBorderColor?: string; - /** - * Specifies a color for an area when this area is selected. - * @deprecated Use the layers | selectedColor option instead. - */ + /** * Specifies a color for an area when this area is selected. * @deprecated Use the layers | selectedColor option instead. */ selectedColor?: string; - /** - * Specifies the pixel-measured width of the area border when the area is selected. - * @deprecated Use the layers | selectedBorderWidth option instead. - */ + /** * Specifies the pixel-measured width of the area border when the area is selected. * @deprecated Use the layers | selectedBorderWidth option instead. */ selectedBorderWidth?: number; - /** - * Specifies whether single or multiple areas can be selected on a vector map. - * @deprecated Use the layers | selectionMode option instead. - */ + /** * Specifies whether single or multiple areas can be selected on a vector map. * @deprecated Use the layers | selectionMode option instead. */ selectionMode?: string; } export interface MarkerSettings { - /** - * Specifies a color for the marker border. - * @deprecated Use the layers | borderColor option instead. - */ + /** * Specifies a color for the marker border. * @deprecated Use the layers | borderColor option instead. */ borderColor?: string; - /** - * Specifies the width of the marker border in pixels. - * @deprecated Use the layers | borderWidth option instead. - */ + /** * Specifies the width of the marker border in pixels. * @deprecated Use the layers | borderWidth option instead. */ borderWidth?: number; - /** - * Specifies a color for a marker of the dot or bubble type. - * @deprecated Use the layers | color option instead. - */ + /** * Specifies a color for a marker of the dot or bubble type. * @deprecated Use the layers | color option instead. */ color?: string; - /** - * Specifies the function that customizes each marker individually. - * @deprecated Use the layers | customize option instead. - */ + /** * Specifies the function that customizes each marker individually. * @deprecated Use the layers | customize option instead. */ customize?: (markerInfo: Marker) => MarkerSettings; - /** - * Specifies the pixel-measured width of the marker border when the marker is hovered over. - * @deprecated Use the layers | hoveredBorderWidth option instead. - */ + /** * Specifies the pixel-measured width of the marker border when the marker is hovered over. * @deprecated Use the layers | hoveredBorderWidth option instead. */ hoveredBorderWidth?: number; - /** - * Specifies a color for the marker border when the marker is hovered over. - * @deprecated Use the layers | hoveredBorderColor option instead. - */ + /** * Specifies a color for the marker border when the marker is hovered over. * @deprecated Use the layers | hoveredBorderColor option instead. */ hoveredBorderColor?: string; - /** - * Specifies a color for a marker of the dot or bubble type when this marker is hovered over. - * @deprecated Use the layers | hoveredColor option instead. - */ + /** * Specifies a color for a marker of the dot or bubble type when this marker is hovered over. * @deprecated Use the layers | hoveredColor option instead. */ hoveredColor?: string; - /** - * Specifies whether or not to change the appearance of a marker when it is hovered over. - * @deprecated Use the layers | hoverEnabled option instead. - */ + /** * Specifies whether or not to change the appearance of a marker when it is hovered over. * @deprecated Use the layers | hoverEnabled option instead. */ hoverEnabled?: boolean; - /** - * Specifies marker label options. - * @deprecated Use the layers | label option instead. - */ + /** * Specifies marker label options. * @deprecated Use the layers | label option instead. */ label?: { - /** - * Enables marker labels. - * @deprecated Use the layers | label | enabled option instead. - */ + /** * Enables marker labels. * @deprecated Use the layers | label | enabled option instead. */ enabled?: boolean; - /** - * Specifies font options for marker labels. - * @deprecated Use the layers | label | font option instead. - */ + /** * Specifies font options for marker labels. * @deprecated Use the layers | label | font option instead. */ font?: viz.core.Font; }; - /** - * Specifies the pixel-measured diameter of the marker that represents the biggest value. Setting this option makes sense only if you use markers of the bubble type. - * @deprecated Use the layers | maxSize option instead. - */ + /** * Specifies the pixel-measured diameter of the marker that represents the biggest value. Setting this option makes sense only if you use markers of the bubble type. * @deprecated Use the layers | maxSize option instead. */ maxSize?: number; - /** - * Specifies the pixel-measured diameter of the marker that represents the smallest value. Setting this option makes sense only if you use markers of the bubble type. - * @deprecated Use the layers | minSize option instead. - */ + /** * Specifies the pixel-measured diameter of the marker that represents the smallest value. Setting this option makes sense only if you use markers of the bubble type. * @deprecated Use the layers | minSize option instead. */ minSize?: number; - /** - * Specifies the opacity of markers. Setting this option makes sense only if you use markers of the bubble type. - * @deprecated Use the layers | opacity option instead. - */ + /** * Specifies the opacity of markers. Setting this option makes sense only if you use markers of the bubble type. * @deprecated Use the layers | opacity option instead. */ opacity?: number; - /** - * Specifies the pixel-measured width of the marker border when the marker is selected. - * @deprecated Use the layers | selectedBorderWidth option instead. - */ + /** * Specifies the pixel-measured width of the marker border when the marker is selected. * @deprecated Use the layers | selectedBorderWidth option instead. */ selectedBorderWidth?: number; - /** - * Specifies a color for the marker border when the marker is selected. - * @deprecated Use the layers | selectedBorderColor option instead. - */ + /** * Specifies a color for the marker border when the marker is selected. * @deprecated Use the layers | selectedBorderColor option instead. */ selectedBorderColor?: string; - /** - * Specifies a color for a marker of the dot or bubble type when this marker is selected. - * @deprecated Use the layers | selectedColor option instead. - */ + /** * Specifies a color for a marker of the dot or bubble type when this marker is selected. * @deprecated Use the layers | selectedColor option instead. */ selectedColor?: string; - /** - * Specifies whether a single or multiple markers can be selected on a vector map. - * @deprecated Use the layers | selectionMode option instead. - */ + /** * Specifies whether a single or multiple markers can be selected on a vector map. * @deprecated Use the layers | selectionMode option instead. */ selectionMode?: string; - /** - * Specifies the size of markers. Setting this option makes sense for any type of marker except bubble. - * @deprecated Use the layers | size option instead. - */ + /** * Specifies the size of markers. Setting this option makes sense for any type of marker except bubble. * @deprecated Use the layers | size option instead. */ size?: number; - /** - * Specifies the type of markers to be used on the map. - * @deprecated Use the layers | elementType option instead. - */ + /** * Specifies the type of markers to be used on the map. * @deprecated Use the layers | elementType option instead. */ type?: string; - /** - * Specifies the name of a palette or a custom set of colors to be used for coloring markers of the pie type. - * @deprecated Use the layers | palette option instead. - */ + /** * Specifies the name of a palette or a custom set of colors to be used for coloring markers of the pie type. * @deprecated Use the layers | palette option instead. */ palette?: any; - /** - * Allows you to paint markers with similar attributes in the same color. - * @deprecated Use the layers | colorGroups option instead. - */ + /** * Allows you to paint markers with similar attributes in the same color. * @deprecated Use the layers | colorGroups option instead. */ colorGroups?: Array; - /** - * Specifies the field that provides data to be used for coloring markers. - * @deprecated Use the layers | colorGroupingField option instead. - */ + /** * Specifies the field that provides data to be used for coloring markers. * @deprecated Use the layers | colorGroupingField option instead. */ colorGroupingField?: string; - /** - * Allows you to display bubbles with similar attributes in the same size. - * @deprecated Use the layers | sizeGroups option instead. - */ + /** * Allows you to display bubbles with similar attributes in the same size. * @deprecated Use the layers | sizeGroups option instead. */ sizeGroups?: Array; - /** - * Specifies the field that provides data to be used for sizing bubble markers. - * @deprecated Use the layers | sizeGroupingField option instead. - */ + /** * Specifies the field that provides data to be used for sizing bubble markers. * @deprecated Use the layers | sizeGroupingField option instead. */ sizeGroupingField?: string; } export interface dxVectorMapOptions extends viz.core.BaseWidgetOptions, viz.core.RedrawOnResizeOptions, viz.core.TitleOptions, viz.core.LoadingIndicatorOptions, viz.core.ExportOptions { - /** - * An object specifying options for the map areas. - * @deprecated Use the "area" type element of the layers array. - */ + /** * An object specifying options for the map areas. * @deprecated Use the "area" type element of the layers array. */ areaSettings?: AreaSettings; /** Specifies the options for the map background. */ background?: { @@ -7519,20 +7503,11 @@ declare module DevExpress.viz.map { /** Specifies the opacity of the control bar. */ opacity?: number; }; - /** - * Specifies a data source for the map area. - * @deprecated Use the layers | dataSource option instead. - */ + /** * Specifies a data source for the map area. * @deprecated Use the layers | dataSource option instead. */ mapData?: any; - /** - * Specifies a data source for the map markers. - * @deprecated Use the layers | dataSource option instead. - */ + /** * Specifies a data source for the map markers. * @deprecated Use the layers | dataSource option instead. */ markers?: any; - /** - * An object specifying options for the map markers. - * @deprecated Use the "marker" type element of the layers array. - */ + /** * An object specifying options for the map markers. * @deprecated Use the "marker" type element of the layers array. */ markerSettings?: MarkerSettings; /** Configures tooltips. */ tooltip?: viz.core.Tooltip; @@ -7582,29 +7557,17 @@ declare module DevExpress.viz.map { element: Element; target: MapLayerElement; }) => void; - /** - * A handler for the areaClick event. - * @deprecated Use the onClick option instead. - */ + /** * A handler for the areaClick event. * @deprecated Use the onClick option instead. */ onAreaClick?: any; - /** - * A handler for the areaSelectionChanged event. - * @deprecated Use the onSelectionChanged option instead. - */ + /** * A handler for the areaSelectionChanged event. * @deprecated Use the onSelectionChanged option instead. */ onAreaSelectionChanged?: (e: { target: Area; component: dxVectorMap; element: Element; }) => void; - /** - * A handler for the markerClick event. - * @deprecated Use the onClick option instead. - */ + /** * A handler for the markerClick event. * @deprecated Use the onClick option instead. */ onMarkerClick?: any; - /** - * A handler for the markerSelectionChanged event. - * @deprecated Use the onSelecitonChanged option instead. - */ + /** * A handler for the markerSelectionChanged event. * @deprecated Use the onSelecitonChanged option instead. */ onMarkerSelectionChanged?: (e: { target: Marker; component: dxVectorMap; @@ -7644,7 +7607,7 @@ declare module DevExpress.viz.map { add(name: string, projection: Object): void; } } -declare module DevExpress.viz{ +declare module DevExpress.viz { /** A vector map widget. */ export class dxVectorMap extends viz.core.BaseWidget implements viz.core.LoadingIndicatorMethods { constructor(element: JQuery, options?: DevExpress.viz.map.dxVectorMapOptions); @@ -7655,15 +7618,9 @@ declare module DevExpress.viz{ center(): Array; /** Sets the coordinates of the map center. */ center(centerCoordinates: Array): void; - /** - * Deselects all the selected areas on a map. The areas are displayed in their initial style after. - * @deprecated Use the layer's clearSelection() method instead. - */ + /** * Deselects all the selected areas on a map. The areas are displayed in their initial style after. * @deprecated Use the layer's clearSelection() method instead. */ clearAreaSelection(): void; - /** - * Deselects all the selected markers on a map. The markers are displayed in their initial style after. - * @deprecated Use the layer's clearSelection() method instead. - */ + /** * Deselects all the selected markers on a map. The markers are displayed in their initial style after. * @deprecated Use the layer's clearSelection() method instead. */ clearMarkerSelection(): void; /** Deselects all the selected area and markers on a map at once. The areas and markers are displayed in their initial style after. */ clearSelection(): void; @@ -7675,15 +7632,9 @@ declare module DevExpress.viz{ getLayerByIndex(index: number): DevExpress.viz.map.MapLayer; /** Gets the layer by its name. */ getLayerByName(name: string): DevExpress.viz.map.MapLayer; - /** - * Returns an array with all the map areas. - * @deprecated Use the layer's getElements() method instead. - */ + /** * Returns an array with all the map areas. * @deprecated Use the layer's getElements() method instead. */ getAreas(): Array; - /** - * Returns an array with all the map markers. - * @deprecated Use the layer's getElements() method instead. - */ + /** * Returns an array with all the map markers. * @deprecated Use the layer's getElements() method instead. */ getMarkers(): Array; /** Gets the current coordinates of the map viewport. */ viewport(): Array; @@ -7695,22 +7646,11 @@ declare module DevExpress.viz{ zoomFactor(zoomFactor: number): void; } } -interface JQuery { - dxVectorMap(options?: DevExpress.viz.map.dxVectorMapOptions): JQuery; - dxVectorMap(methodName: string, ...params: any[]): any; - dxVectorMap(methodName: "instance"): DevExpress.viz.dxVectorMap; -} declare module DevExpress.viz.sparklines { export interface SparklineTooltip extends viz.core.Tooltip { - /** - * Specifies how a tooltip is horizontally aligned relative to the graph. - * @deprecated Tooltip alignment is no longer useful because the tooltips are aligned automatically. - */ + /** * Specifies how a tooltip is horizontally aligned relative to the graph. * @deprecated Tooltip alignment is no longer useful because the tooltips are aligned automatically. */ horizontalAlignment?: string; - /** - * Specifies how a tooltip is vertically aligned relative to the graph. - * @deprecated Tooltip alignment is no longer useful because the tooltips are aligned automatically. - */ + /** * Specifies how a tooltip is vertically aligned relative to the graph. * @deprecated Tooltip alignment is no longer useful because the tooltips are aligned automatically. */ verticalAlignment?: string; } export interface BaseSparklineOptions extends viz.core.BaseWidgetOptions, viz.core.MarginOptions { @@ -7807,16 +7747,10 @@ declare module DevExpress.viz { export class dxSparkline extends DevExpress.viz.sparklines.BaseSparkline { constructor(element: JQuery, options?: DevExpress.viz.sparklines.dxSparklineOptions); constructor(element: Element, options?: DevExpress.viz.sparklines.dxSparklineOptions); + /** Returns the DataSource instance. */ + getDataSource(): DevExpress.data.DataSource; } } -interface JQuery { - dxBullet(options?: DevExpress.viz.sparklines.dxBulletOptions): JQuery; - dxBullet(methodName: string, ...params: any[]): any; - dxBullet(methodName: "instance"): DevExpress.viz.dxBullet; - dxSparkline(options?: DevExpress.viz.sparklines.dxSparklineOptions): JQuery; - dxSparkline(methodName: string, ...params: any[]): any; - dxSparkline(methodName: "instance"): DevExpress.viz.dxSparkline; -} declare module DevExpress.viz.treeMap { export interface dxTreeMapOptions extends viz.core.BaseWidgetOptions, viz.core.RedrawOnResizeOptions, viz.core.TitleOptions, viz.core.LoadingIndicatorOptions, viz.core.ExportOptions { /** Specifies the origin of data for the widget. */ @@ -7837,6 +7771,8 @@ declare module DevExpress.viz.treeMap { layoutAlgorithm?: any; /** Specifies the direction in which the items will be laid out. */ layoutDirection?: string; + /** Decides whether those labels that overflow their tile/group should be hidden or truncated with ellipsis. */ + resolveLabelOverflow?: string; /** Configures tiles. */ tile?: { /** Configures the tile borders. */ @@ -8043,10 +7979,7 @@ declare module DevExpress.viz { resetDrillDown(): void; showLoadingIndicator(): void; hideLoadingIndicator(): void; + /** Returns the DataSource instance. */ + getDataSource(): DevExpress.data.DataSource; } } -interface JQuery { - dxTreeMap(options?: DevExpress.viz.treeMap.dxTreeMapOptions): JQuery; - dxTreeMap(methodName: string, ...params: any[]): any; - dxTreeMap(methodName: "instance"): DevExpress.viz.dxTreeMap; -} diff --git a/discontinuous-range/discontinuous-range-tests.ts b/discontinuous-range/discontinuous-range-tests.ts index 9f93b0a061..8b31d11b11 100644 --- a/discontinuous-range/discontinuous-range-tests.ts +++ b/discontinuous-range/discontinuous-range-tests.ts @@ -5,12 +5,12 @@ const rangeOne: DiscontinuousRange = new DiscontinuousRange(3); const rangeTwo: DiscontinuousRange = new DiscontinuousRange(3, 5); // add -const resultOne: DiscontinuousRange = rangeOne.add(6,10); +const resultOne: DiscontinuousRange = rangeOne.add(6, 10); const resultTwo: DiscontinuousRange = rangeTwo.add(11); const resultThree: DiscontinuousRange = rangeOne.add(rangeTwo); // subtract -const resultFour: DiscontinuousRange = rangeOne.subtract(7,8); +const resultFour: DiscontinuousRange = rangeOne.subtract(7, 8); const resultFive: DiscontinuousRange = rangeTwo.subtract(11); const resultSix: DiscontinuousRange = rangeOne.subtract(rangeTwo); diff --git a/dockerode/dockerode-tests.ts b/dockerode/dockerode-tests.ts new file mode 100644 index 0000000000..3bd1c30097 --- /dev/null +++ b/dockerode/dockerode-tests.ts @@ -0,0 +1,58 @@ +import * as Docker from 'dockerode'; + +// Code samples from Dockerode 'Getting started' +const docker = new Docker(); +const docker1 = new Docker({ socketPath: '/var/run/docker.sock' }); +const docker2 = new Docker({ host: 'http://192.168.1.10', port: 3000 }); +const docker3 = new Docker({ protocol: 'http', host: '127.0.0.1', port: 3000 }); +const docker4 = new Docker({ host: '127.0.0.1', port: 3000 }); + +const docker5 = new Docker({ + host: '192.168.1.10', + port: process.env.DOCKER_PORT || 2375, + ca: 'ca', + cert: 'cert', + key: 'key' +}); + +const docker6 = new Docker({ + protocol: 'https', // you can enforce a protocol + host: '192.168.1.10', + port: process.env.DOCKER_PORT || 2375, + ca: 'ca', + cert: 'cert', + key: 'key' +}); + +const container = docker.getContainer('container-id'); +container.inspect((err, data) => { + // NOOP +}); + +container.start((err, data) => { + // NOOP +}); + +container.remove((err, data) => { + // NOOP +}); + +docker.listContainers((err, containers) => { + containers.forEach(container => { + docker + .getContainer(container.Id) + .stop((err, data) => { + // NOOP + }); + }); +}); + +docker.buildImage('archive.tar', { t: 'imageName' }, (err, response) => { + // NOOP +}); + +docker.createContainer({ Tty: true }, (err, container) => { + container.start((err, data) => { + // NOOP + }); +}); \ No newline at end of file diff --git a/dockerode/index.d.ts b/dockerode/index.d.ts new file mode 100644 index 0000000000..c317d5d32e --- /dev/null +++ b/dockerode/index.d.ts @@ -0,0 +1,643 @@ +// Type definitions for dockerode 2.3 +// Project: https://github.com/apocas/dockerode +// Definitions by: Carl Winkler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as stream from 'stream'; +import * as events from 'events'; + + +declare namespace Dockerode { + interface Container { + inspect(options: {}, callback: Callback): void; + inspect(callback: Callback): void; + inspect(options?: {}): { id: string }; + + rename(options: {}, callback: Callback): void; + + update(options: {}, callback: Callback): void; + + top(options: {}, callback: Callback): void; + top(callback: Callback): void; + + changes(callback: Callback): void; + + export(callback: Callback): void; + + start(options: {}, callback: Callback): void; + start(callback: Callback): void; + + pause(options: {}, callback: Callback): void; + pause(callback: Callback): void; + + unpause(options: {}, callback: Callback): void; + unpause(callback: Callback): void; + + exec(options: {}, callback: Callback): void; + + commit(options: {}, callback: Callback): void; + commit(callback: Callback): void; + + stop(options: {}, callback: Callback): void; + stop(callback: Callback): void; + + restart(options: {}, callback: Callback): void; + restart(callback: Callback): void; + + kill(options: {}, callback: Callback): void; + kill(callback: Callback): void; + + resize(options: {}, callback: Callback): void; + resize(callback: Callback): void; + + wait(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + /** Deprecated since RAPI v1.20 */ + copy(options: {}, callback: Callback): void; + /** Deprecated since RAPI v1.20 */ + copy(callback: Callback): void; + + getArchive(options: {}, callback: Callback): void; + + infoArchive(options: {}, callback: Callback): void; + + /** @param file Filename (will read synchronously), Buffer or stream */ + putArchive(file: string | Buffer | NodeJS.ReadableStream, options: {}, callback: Callback): void; + + logs(options: { stdout?: boolean, stderr?: boolean, follow?: boolean, since?: number, details?: boolean, tail?: number, timestamps?: boolean }, callback: Callback): void; + logs(callback: Callback): void; + + stats(options: {}, callback: Callback): void; + stats(callback: Callback): void; + + attach(options: {}, callback: Callback): void; + + modem: any; + id?: string; + } + + interface Image { + inspect(callback: Callback): void; + + history(callback: Callback): void; + + get(callback: Callback): void; + + push(options: {}, callback: Callback): void; + push(callback: Callback): void; + + tag(options: {}, callback: Callback): void; + tag(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Volume { + inspect(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + modem: any; + name?: string; + } + + interface Service { + inspect(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + update(options: {}, callback: Callback): void; + + modem: any; + id?: string; + } + + interface Task { + inspect(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Node { + inspect(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Network { + inspect(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + connect(options: {}, callback: Callback): void; + connect(callback: Callback): void; + + disconnect(options: {}, callback: Callback): void; + disconnect(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Exec { + inspect(callback: Callback): void; + + start(options: {}, callback: Callback): void; + + resize(options: {}, callback: Callback): void; + + modem: any; + id?: string; + } + + interface ImageInfo { + Id: string; + ParentId: string; + RepoTags: string[]; + RepoDigests?: string[]; + Created: number; + Size: number; + VirtualSize: number; + Labels: { [label: string]: string }; + } + + interface ContainerInfo { + Id: string; + Names: string[]; + Image: string; + ImageID: string; + Command: string; + Created: number; + Ports: Port[]; + Labels: { [label: string]: string }; + Status: string; + HostConfig: { + NetworkMode: string; + }; + NetworkSettings: { + Networks: { [networkType: string]: NetworkInfo } + }; + } + + interface Port { + IP: string; + PrivatePort: number; + PublicPort: number; + Type: string; + } + + interface NetworkInfo { + IPAMConfig?: any; + Links?: any; + Aliases?: any; + NetworkID: string; + EndpointID: string; + Gateway: string; + IPAddress: string; + IPPrefixLen: number; + IPv6Gateway: string; + GlobalIPv6Address: string; + GlobalIPv6PrefixLen: number; + MacAddress: string; + } + + interface ContainerInspectInfo { + Id: string; + Created: string; + Path: string; + Args: string[]; + State: { + Status: string; + Running: boolean; + Paused: boolean; + Restarting: boolean; + OOMKilled: boolean; + Dead: boolean; + Pid: number; + ExitCode: number; + Error: string; + StartedAt: string; + FinishedAt: string; + }; + Image: string; + ResolvConfPath: string; + HostnamePath: string; + HostsPath: string; + LogPath: string; + Name: string; + RestartCount: number; + Driver: string; + MountLabel: string; + ProcessLabel: string; + AppArmorProfile: string; + ExecIDs?: any; + HostConfig: HostConfig; + GraphDriver: { + Name: string; + Data: { + DeviceId: string; + DeviceName: string; + DeviceSize: string; + } + }; + Mounts: Array<{ + Source: string; + Destination: string; + Mode: string; + RW: boolean; + Propagation: string; + }>; + Config: { + Hostname: string; + Domainname: string; + User: string; + AttachStdin: boolean; + AttachStdout: boolean; + AttachStderr: boolean; + ExposedPorts: { [portAndProtocol: string]: {} }; + Tty: boolean; + OpenStdin: boolean; + StdinOnce: boolean; + Env: string[]; + Cmd: string[]; + Image: string; + Volumes: { [volume: string]: {} }; + WorkingDir: string; + Entrypoint?: any; + OnBuild?: any; + Labels: { [label: string]: string } + }; + NetworkSettings: { + Bridge: string; + SandboxID: string; + HairpinMode: boolean; + LinkLocalIPv6Address: string; + LinkLocalIPv6PrefixLen: number; + Ports: { + [portAndProtocol: string]: { + HostIp: string; + HostPort: string; + } + }; + SandboxKey: string; + SecondaryIPAddresses?: any; + SecondaryIPv6Addresses?: any; + EndpointID: string; + Gateway: string; + GlobalIPv6Address: string; + GlobalIPv6PrefixLen: number; + IPAddress: string; + IPPrefixLen: number; + IPv6Gateway: string; + MacAddress: string; + Networks: { + [type: string]: { + IPAMConfig?: any; + Links?: any; + Aliases?: any; + NetworkID: string; + EndpointID: string; + Gateway: string; + IPAddress: string; + IPPrefixLen: number; + IPv6Gateway: string; + GlobalIPv6Address: string; + GlobalIPv6PrefixLen: number; + MacAddress: string; + } + } + }; + } + + interface HostConfig { + Binds: string[]; + ContainerIDFile: string; + LogConfig: { + Type: string; + Config: any; + }; + NetworkMode: string; + PortBindings?: any; + RestartPolicy: { + Name: string; + MaximumRetryCount: number; + }; + VolumeDriver: string; + VolumesFrom?: any; + CapAdd?: any; + CapDrop?: any; + Dns: any[]; + DnsOptions: any[]; + DnsSearch: any[]; + ExtraHosts?: any; + IpcMode: string; + Links?: any; + OomScoreAdj: number; + PidMode: string; + Privileged: boolean; + PublishAllPorts: boolean; + ReadonlyRootfs: boolean; + SecurityOpt?: any; + UTSMode: string; + ShmSize: number; + ConsoleSize: number[]; + Isolation: string; + CpuShares: number; + CgroupParent: string; + BlkioWeight: number; + BlkioWeightDevice?: any; + BlkioDeviceReadBps?: any; + BlkioDeviceWriteBps?: any; + BlkioDeviceReadIOps?: any; + BlkioDeviceWriteIOps?: any; + CpuPeriod: number; + CpuQuota: number; + CpusetCpus: string; + CpusetMems: string; + Devices?: any; + KernelMemory: number; + Memory: number; + MemoryReservation: number; + MemorySwap: number; + MemorySwappiness: number; + OomKillDisable: boolean; + PidsLimit: number; + Ulimits?: any; + } + + interface ImageInspectInfo { + Id: string; + RepoTags: string[]; + RepoDigests: string[]; + Parent: string; + Comment: string; + Created: string; + Container: string; + ContainerConfig: + { + Hostname: string; + Domainname: string; + User: string; + AttachStdin: boolean; + AttachStdout: boolean; + AttachStderr: boolean; + ExposedPorts: { [portAndProtocol: string]: {} }; + Tty: boolean; + OpenStdin: boolean; + StdinOnce: boolean; + Env: string[]; + Cmd: string[]; + ArgsEscaped: boolean; + Image: string; + Volumes: { [path: string]: {} }, + WorkingDir: string; + Entrypoint?: any; + OnBuild?: any[]; + Labels: { [label: string]: string } + }; + DockerVersion: string; + Author: string; + Config: + { + Hostname: string; + Domainname: string; + User: string; + AttachStdin: boolean; + AttachStdout: boolean; + AttachStderr: boolean; + ExposedPorts: { [portAndProtocol: string]: {} } + Tty: boolean; + OpenStdin: boolean; + StdinOnce: boolean; + Env: string[]; + Cmd: string[]; + ArgsEscaped: boolean; + Image: string; + Volumes: { [path: string]: {} }, + WorkingDir: string; + Entrypoint?: any; + OnBuild: any[]; + Labels: { [label: string]: string } + }; + Architecture: string; + Os: string; + Size: number; + VirtualSize: number; + GraphDriver: + { + Name: string; + Data: + { + DeviceId: string; + DeviceName: string; + DeviceSize: string; + } + }; + } + + interface ContainerCreateOptions { + name?: string; + Hostname?: string; + Domainname?: string; + User?: string; + AttachStdin?: boolean; + AttachStdout?: boolean; + AttachStderr?: boolean; + Tty?: boolean; + OpenStdin?: boolean; + StdinOnce?: boolean; + Env?: string[]; + Cmd?: string[]; + Entrypoint?: string; + Image?: string; + Labels?: { [label: string]: string }; + Volumes?: { [volume: string]: {} }; + WorkingDir?: string; + NetworkDisabled?: boolean; + MacAddress?: boolean; + ExposedPorts?: { [port: string]: {} }; + StopSignal?: string; + HostConfig?: { + Binds?: string[]; + Links?: string[]; + Memory?: number; + MemorySwap?: number; + MemoryReservation?: number; + KernelMemory?: number; + CpuPercent?: number; + CpuShares?: number; + CpuPeriod?: number; + CpuQuota?: number; + CpusetMems?: string; + MaximumIOps?: number; + MaxmimumIOBps?: number; + BlkioWeightDevice?: Array<{}>; + BlkioDeviceReadBps?: Array<{}>; + BlkioDeviceReadIOps?: Array<{}>; + BlkioDeviceWriteBps?: Array<{}>; + BlkioDeviceWriteIOps?: Array<{}>; + MemorySwappiness?: number; + OomKillDisable?: boolean; + OomScoreAdj?: number; + PidMode?: string; + PidsLimit?: number; + PortBindings?: { [portAndProtocol: string]: Array<{ [index: string]: string }> }; + PublishAllPorts?: boolean; + Privileged?: boolean; + ReadonlyRootfs?: boolean; + Dns?: string[]; + DnsOptions?: string[]; + DnsSearch?: string[]; + ExtraHosts?: any; + VolumesFrom?: string[]; + CapAdd?: string[]; + CapDrop?: string[]; + GroupAdd?: string[]; + RestartPolicy?: { [index: string]: number | string }; + NetworkMode?: string; + Devices?: any[]; + Sysctls?: { [index: string]: string }; + Ulimits?: Array<{}>; + LogConfig?: { [index: string]: string | {} }; + SecurityOpt?: { [index: string]: any }; + CgroupParent?: string; + VolumeDriver?: string; + ShmSize?: number; + }; + NetworkingConfig?: { + EndpointsConfig?: { + [index: string]: any; + isolated_nw?: { + [index: string]: any; + IPAMConfig?: { + IPv4Address?: string; + IPv6Adress?: string; + LinkLocalIPs?: string[]; + } + Links?: string[]; + Aliases?: string[]; + } + } + }; + } + + interface DockerOptions { + socketPath?: string; + host?: string; + port?: number; + ca?: string; + cert?: string; + key?: string; + protocol?: "https" | "http"; + timeout?: number; + } +} + +type Callback = (error?: any, result?: T) => void; + +declare class Dockerode { + constructor(options?: Dockerode.DockerOptions); + + createContainer(options: Dockerode.ContainerCreateOptions, callback: Callback): void; + + createImage(options: {}, callback: Callback): void; + createImage(auth: any, options: {}, callback: Callback): void; + + loadImage(file: string, options: {}, callback: Callback): void; + loadImage(file: string, callback: Callback): void; + + importImage(file: string, options: {}, callback: Callback): void; + importImage(file: string, callback: Callback): void; + + checkAuth(options: any, callback: Callback): void; + + buildImage(file: string | NodeJS.ReadableStream, options: {}, callback: Callback): void; + buildImage(file: string | NodeJS.ReadableStream, callback: Callback): void; + + getContainer(id: string): Dockerode.Container; + + getImage(name: string): Dockerode.Image; + + getVolume(name: string): Dockerode.Volume; + + getService(id: string): Dockerode.Service; + + getTask(id: string): Dockerode.Task; + + getNode(id: string): Dockerode.Node; + + getNetwork(id: string): Dockerode.Network; + + getExec(id: string): Dockerode.Exec; + + listContainers(options: {}, callback: Callback): void; + listContainers(callback: Callback): void; + + listImages(options: {}, callback: Callback): void; + listImages(callback: Callback): void; + + listServices(options: {}, callback: Callback): void; + listServices(callback: Callback): void; + + listNodes(options: {}, callback: Callback): void; + listNodes(callback: Callback): void; + + listTasks(options: {}, callback: Callback): void; + listTasks(callback: Callback): void; + + listVolumes(options: {}, callback: Callback): void; + listVolumes(callback: Callback): void; + + listNetworks(options: {}, callback: Callback): void; + listNetworks(callback: Callback): void; + + createVolume(options: {}, callback: Callback): void; + + createService(options: {}, callback: Callback): void; + + createNetwork(options: {}, callback: Callback): void; + + searchImages(options: {}, callback: Callback): void; + + info(callback: Callback): void; + + version(callback: Callback): void; + + ping(callback: Callback): void; + + getEvents(options: {}, callback: Callback): void; + getEvents(callback: Callback): void; + + pull(repoTag: string, options: {}, callback: Callback, auth?: {}): Dockerode.Image; + + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, createOptions: {}, startOptions: {}, callback: Callback): events.EventEmitter; + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, startOptions: {}, callback: Callback): events.EventEmitter; + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, callback: Callback): events.EventEmitter; + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, createOptions: {}, callback: Callback): events.EventEmitter; + + swarmInit(options: {}, callback: Callback): void; + + swarmJoin(options: {}, callback: Callback): void; + + swarmLeave(options: {}, callback: Callback): void; + + swarmUpdate(options: {}, callback: Callback): void; + + modem: any; +} + +export = Dockerode; diff --git a/ecmarkup/tsconfig.json b/dockerode/tsconfig.json similarity index 93% rename from ecmarkup/tsconfig.json rename to dockerode/tsconfig.json index 2a9343d5ec..2a83a71968 100644 --- a/ecmarkup/tsconfig.json +++ b/dockerode/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "ecmarkup-tests.ts" + "dockerode-tests.ts" ] } \ No newline at end of file diff --git a/dockerode/tslint.json b/dockerode/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/dockerode/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/documentdb/documentdb-tests.ts b/documentdb/documentdb-tests.ts index 34d6b5236b..f4a06d3fb7 100644 --- a/documentdb/documentdb-tests.ts +++ b/documentdb/documentdb-tests.ts @@ -55,6 +55,31 @@ docDBClient.createStoredProcedure('collection', procedure, undefined, (error, re } }); +var userDefinedFunction: docDB.UserDefinedFunction = { + id: 'udf1', + body: function () { + console.log('foo'); + } +}; + +docDBClient.createUserDefinedFunction('collection', userDefinedFunction, undefined, (error, result) => { + if (error) { + throw new Error(error.body); + } + else { + console.log('Created function: ' + result.id); + } +}); + +docDBClient.queryUserDefinedFunctions('collection', "SELECT * FROM root", undefined).toArray((error, results) => { + if (error) { + throw new Error(error.body); + } + else { + console.log('Number of functions in collection: ' + results.length); + } +}); + var trigger: docDB.Trigger = { id: 'trigger-one', body: function () { diff --git a/documentdb/index.d.ts b/documentdb/index.d.ts index 406affe2c8..048825b492 100644 --- a/documentdb/index.d.ts +++ b/documentdb/index.d.ts @@ -154,6 +154,10 @@ interface ProcedureMeta extends AbstractMeta { body: string; } +/** Represents the meta data for a user-defined function. */ +interface UserDefinedFunctionMeta extends AbstractMeta { +} + /** Represents the meta data for a trigger. */ interface TriggerMeta extends AbstractMeta { body: string; @@ -181,6 +185,13 @@ export interface Procedure extends UniqueId { body(...params: any[]): void; } +/** Represents a DocumentDB user-defined function. */ +export interface UserDefinedFunction extends UniqueId { + + /** The function representing the user-defined function. */ + body(...params: any[]): void; +} + /** Represents a DocumentDB trigger. */ export interface Trigger extends UniqueId { /** The type of the trigger. Should be either 'pre' or 'post'. */ @@ -290,6 +301,19 @@ export declare class DocumentClient { */ public createStoredProcedure(collectionLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback): void; + /** + * Create a UserDefinedFunction. + *

+ * DocumentDB supports JavaScript UDFs which can be used inside queries, stored procedures and triggers.
+ * For additional details, refer to the server-side JavaScript API documentation. + *

+ * @param collectionLink - The self-link of the collection. + * @param udf - Represents the body of the userDefinedFunction. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createUserDefinedFunction(collectionLink: string, udf: UserDefinedFunction, options: RequestOptions, callback: RequestCallback): void; + /** * Create a trigger. *

@@ -349,6 +373,15 @@ export declare class DocumentClient { */ public queryStoredProcedures(collectionLink: string, query: string | SqlQuerySpec): QueryIterator; + /** + * Query the user-defined functions for the collection. + * @param collectionLink - The self-link of the collection. + * @param query - A SQL query string. + * @param [options] - Represents the feed options. + * @returns - An instance of queryIterator to handle reading feed. + */ + public queryUserDefinedFunctions(collectionLink: string, query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator; + /** * Query the documents for the collection. * @param collectionLink - The self-link of the collection. diff --git a/dookie/dookie-tests.ts b/dookie/dookie-tests.ts index d2fa907669..44cd6ec7ac 100644 --- a/dookie/dookie-tests.ts +++ b/dookie/dookie-tests.ts @@ -1,8 +1,8 @@ import {push, pull} from './index'; -(async ()=>{ +(async () => { - await push('mongodb://localhost:27017/test', {test:[{ok:1},{ok:2}]}); + await push('mongodb://localhost:27017/test', {test: [{ok: 1}, {ok: 2}]}); })(); diff --git a/dookie/tsconfig.json b/dookie/tsconfig.json index d795a39145..0c926cf7ff 100644 --- a/dookie/tsconfig.json +++ b/dookie/tsconfig.json @@ -1,6 +1,9 @@ { "compilerOptions": { "module": "commonjs", + "lib": [ + "es6" + ], "target": "es6", "noImplicitAny": true, "noImplicitThis": true, @@ -17,4 +20,4 @@ "index.d.ts", "dookie-tests.ts" ] -} +} \ No newline at end of file diff --git a/dot-object/dot-object-tests.ts b/dot-object/dot-object-tests.ts index 603a66c57e..a553c6c68d 100644 --- a/dot-object/dot-object-tests.ts +++ b/dot-object/dot-object-tests.ts @@ -16,10 +16,10 @@ var src = { } }; -var tgt = {name: 'Brandon'}; +var tgt = { name: 'Brandon' }; dot.copy('stuff.phone', 'wanna.haves.phone', src, tgt, [(arg: any) => { - return arg; + return arg; }]); dot.transfer('stuff.phone', 'wanna.haves.phone', src, tgt); @@ -37,17 +37,17 @@ var row = { }; dot.object(row, (arg: any) => { - return arg; + return arg; }); dot.str('this.is.my.string', 'value', tgt); var newObj = { - some: { - nested: { - value: 'Hi there!' - } - } + some: { + nested: { + value: 'Hi there!' + } + } }; var val = dot.pick('some.nested.value', newObj); @@ -62,4 +62,9 @@ val = dot.remove('some.nested.value', newObj); // or use the alias `del` val = dot.del('some.nested.value', newObj); -var dotWithArrow = new dot('=>'); \ No newline at end of file +// convert object to dot object +var result = {}; +dot.dot({ test: 'something' }, result); +result = dot.dot({ test: 'something' }); + +var dotWithArrow = new dot('=>'); diff --git a/dot-object/index.d.ts b/dot-object/index.d.ts index 953291c631..8bb7d0657c 100644 --- a/dot-object/index.d.ts +++ b/dot-object/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Dot-Object v1.4.1 +// Type definitions for Dot-Object v1.5 // Project: https://github.com/rhalff/dot-object // Definitions by: Niko Kovačič // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,14 +6,14 @@ declare namespace DotObject { interface DotConstructor extends Dot { - new(separator: string): Dot; + new (separator: string): Dot; } interface ModifierFunctionWrapper { (arg: any): any; } - interface Dot { + interface Dot { /** * * Copy a property from one object to another object. @@ -34,11 +34,6 @@ declare namespace DotObject { * Convert object to dotted-key/value pair * * Usage: - * - * var tgt = dot.dot(obj) - * - * or - * * var tgt = {} * dot.dot(obj, tgt) * @@ -46,6 +41,18 @@ declare namespace DotObject { * @param {Object} tgt target object */ dot(obj: any, tgt: any): void + /** + * + * Convert object to dotted-key/value pair + * + * Usage: + * + * var tgt = dot.dot(obj) + * @param {Object} obj source object + * @return {Object} result + */ + dot(obj: any): any + /** * * Remove value from an object using dot notation. @@ -102,7 +109,7 @@ declare namespace DotObject { * @param {Object} obj * @param {Boolean} remove */ - pick(path: string, obj: any, remove?: boolean): void; + pick(path: string, obj: any, remove?: boolean): any; /** * * Remove value from an object using dot notation. @@ -166,4 +173,4 @@ declare var dot: DotObject.DotConstructor; declare module 'dot-object' { export = dot; -} \ No newline at end of file +} diff --git a/dot/tslint.json b/dot/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/dot/tslint.json +++ b/dot/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/draft-js/index.d.ts b/draft-js/index.d.ts index e02044a006..1805a17ab0 100644 --- a/draft-js/index.d.ts +++ b/draft-js/index.d.ts @@ -458,7 +458,7 @@ declare namespace Draft { entityMap: { [key: string]: RawDraftEntity }; } - function convertFromHTMLtoContentBlocks(html: string, DOMBuilder: Function, blockRenderMap?: DraftBlockRenderMap): Array; + function convertFromHTMLtoContentBlocks(html: string, DOMBuilder?: Function, blockRenderMap?: DraftBlockRenderMap): Array; function convertFromRawToDraftState(rawState: RawDraftContentState): ContentState; function convertFromDraftStateToRaw(contentState: ContentState): RawDraftContentState; } diff --git a/dragster/dragster-tests.ts b/dragster/dragster-tests.ts new file mode 100644 index 0000000000..a05d06e1dd --- /dev/null +++ b/dragster/dragster-tests.ts @@ -0,0 +1,7 @@ +import Dragster = require("dragster"); + +var dropzone = document.getElementById("my-dropzone") as HTMLElement; +var dragster = new Dragster(dropzone); + +dragster.removeListeners(); +dragster.reset(); \ No newline at end of file diff --git a/dragster/index.d.ts b/dragster/index.d.ts new file mode 100644 index 0000000000..c02f510084 --- /dev/null +++ b/dragster/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for dragster 0.1 +// Project: https://github.com/bensmithett/dragster +// Definitions by: Zsolt Kovacs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Dragster { + interface Dragster { + removeListeners(): void; + reset(): void; + } + + interface DragsterStatic { + (elem: HTMLElement): Dragster; + new (elem: HTMLElement): Dragster; + } +} + +// Support through imports. +declare var Dragster: Dragster.DragsterStatic; +export = Dragster; + +// Support as a global +export as namespace Dragster; \ No newline at end of file diff --git a/dragster/tsconfig.json b/dragster/tsconfig.json new file mode 100644 index 0000000000..9740d729a0 --- /dev/null +++ b/dragster/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", + "dragster-tests.ts" + ] +} \ No newline at end of file diff --git a/dragster/tslint.json b/dragster/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/dragster/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/dropkickjs/dropkickjs-tests.ts b/dropkickjs/dropkickjs-tests.ts new file mode 100644 index 0000000000..206554da09 --- /dev/null +++ b/dropkickjs/dropkickjs-tests.ts @@ -0,0 +1,89 @@ +// constructor +var constructorNoOptions = new Dropkick('#my-select'); +var constructorNoOptions2 = new Dropkick(new HTMLSelectElement()); +var constructorOptions = new Dropkick('#my-select', {}); +var constructorOptions2 = new Dropkick(new HTMLSelectElement(), {}); + +// options +var options: DropkickOptions = { + disabled: true, + form: new HTMLFormElement(), + length: 1, + mobile: true, + multiple: true, + options: ['test'], + selectedIndex: 0, + selectedOptions: ['test'], + value: 'test', + change() { }, + close() { }, + open() { }, + initialize: () => { } +}; +var withFullOptions = new Dropkick('#test', options); + +var dk = new Dropkick('#test'); + +// fields (same as options) +var o1 = dk.disabled; +var o2 = dk.form; +var o3 = dk.length; +var o4 = dk.mobile; +var o5 = dk.multiple; +var o6 = dk.options; +var o7 = dk.selectedIndex; +var o8 = dk.selectedOptions; +var o9 = dk.value; + +// methods +dk.add('new'); +dk.add(new HTMLSelectElement()); +dk.add('new', 'old'); +dk.add('new', 1); + +dk.disable(); +dk.disable(false); +dk.disable(4, true); +dk.disable(4); + +dk.dispose(); + +dk.focus(); + +dk.hide(4); +dk.hide(4, false); + +var node = dk.item(4); + +dk.open(); + +dk.refresh(); + +dk.remove(4); + +dk.reset(); +dk.reset(true); + +var words = dk.search("qwer", "fuzzy"); + +var node2 = dk.select(4); +var node3 = dk.select("AL"); +var node4 = dk.select(4, true); + +var node5 = dk.selectOne(4); +var node6 = dk.selectOne(4, true); + +// real life example +var fieldValue = ''; +var selectOptions: DropkickOptions = { + open(this: Dropkick) { + const optionsList = ( this).data.elem.lastChild; // undocumented but useful data field + if (optionsList.scrollWidth > optionsList.offsetWidth) { + optionsList.style.width = optionsList.scrollWidth + 25 + 'px'; + } + }, + change: () => { + fieldValue = select.value; + } +}; +var select = new Dropkick('#select', options); \ No newline at end of file diff --git a/dropkickjs/index.d.ts b/dropkickjs/index.d.ts new file mode 100644 index 0000000000..1e0a4f4acf --- /dev/null +++ b/dropkickjs/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for dropkickjs 2.1 +// Project: http://dropkickjs.com/ +// Definitions by: Dmitry Pesterev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface DropkickOptions { + disabled?: boolean; + form?: Node; + length?: number; + mobile?: boolean; + multiple?: boolean; + options?: string[]; + selectedIndex?: number; + selectedOptions?: string[]; + value?: string; + + change?: () => void; + close?: () => void; + initialize?: () => void; + open?: () => void; +} + +declare class Dropkick { + constructor(id: string|HTMLElement, options?: DropkickOptions); + + add(value: string | Node, before?: number | string): void; + close(): void; + disable(disabled?: boolean): void; + disable(index: number, disabled?: boolean): void; + dispose(): void; + focus(): void; + hide(index: number, hidden?: boolean): void; + item(index: number): Node; + open(): void; + refresh(): void; + remove(index: number): void; + reset(clear?: boolean): void; + search(string: string, mode?: string): string[]; + select(element: number|string, selectDisabled?: boolean): Node; + selectOne(element: number, selectDisabled?: boolean): Node; + + disabled: boolean; + form: Node; + length: number; + mobile: boolean; + multiple: boolean; + options: string[]; + selectedIndex: number; + selectedOptions: string[]; + value: string; +} \ No newline at end of file diff --git a/dropkickjs/tsconfig.json b/dropkickjs/tsconfig.json new file mode 100644 index 0000000000..07855ffa97 --- /dev/null +++ b/dropkickjs/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", + "dropkickjs-tests.ts" + ] +} \ No newline at end of file diff --git a/dropkickjs/tslint.json b/dropkickjs/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/dropkickjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/duplexer2/duplexer2-tests.ts b/duplexer2/duplexer2-tests.ts index d611b69144..cfc945adb7 100644 --- a/duplexer2/duplexer2-tests.ts +++ b/duplexer2/duplexer2-tests.ts @@ -1,7 +1,7 @@ import stream = require("stream"); import duplexer2 = require("duplexer2"); -let writable = new stream.Writable({ objectMode: true }), +const writable = new stream.Writable({ objectMode: true }), readable = new stream.Readable({ objectMode: true }); writable.once("finish", () => { @@ -10,7 +10,7 @@ writable.once("finish", () => { }, 500); }); -let duplex = duplexer2(writable, readable); +const duplex = duplexer2(writable, readable); duplex.on("data", (e: any) => { console.log("got data", JSON.stringify(e)); diff --git a/easeljs/index.d.ts b/easeljs/index.d.ts index a5916a56f2..d47f631728 100644 --- a/easeljs/index.d.ts +++ b/easeljs/index.d.ts @@ -735,6 +735,7 @@ declare namespace createjs { intersection(rect: Rectangle): Rectangle; intersects(rect: Rectangle): boolean; isEmpty(): boolean; + pad(top: number, left: number, bottom: number, right: number): Rectangle; setValues(x?: number, y?: number, width?: number, height?: number): Rectangle; toString(): string; union(rect: Rectangle): Rectangle; diff --git a/ecmarkup/ecmarkup-tests.ts b/ecmarkup/ecmarkup-tests.ts deleted file mode 100644 index f6cb6a6fb6..0000000000 --- a/ecmarkup/ecmarkup-tests.ts +++ /dev/null @@ -1,21 +0,0 @@ -/// - -import * as emu from "ecmarkup"; - -emu.build("string", (path: string) => Promise.resolve("string"), { - contributors: "string", - copyright: true, - date: new Date(), - location: "string", - oldToc: true, - toc: true, - shortname: "string", - stage: "string", - status: "proposal", - title: "string", - version: "string", - verbose: true -}).then((spec: emu.Spec) => { - const output = spec.toHTML(); - const biblio = spec.exportBiblio(); -}); \ No newline at end of file diff --git a/ecmarkup/index.d.ts b/ecmarkup/index.d.ts deleted file mode 100644 index 79a84c63a7..0000000000 --- a/ecmarkup/index.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Type definitions for emarkup v3.3.2 -// Project: http://github.com/bterlson/ecmarkup -// Definitions by: Ron Buckton -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export interface Spec { - spec: this; - location: string; - opts: Options; - rootPath: string; - rootDir: string; - namespace: string; - toHTML(): string; - exportBiblio(): any; -} - -export interface Options { - status?: "proposal" | "draft" | "standard"; - version?: string; - title?: string; - shortname?: string; - stage?: string | null; - copyright?: boolean; - date?: Date; - location?: string; - contributors?: string; - toc?: boolean; - oldToc?: boolean; - verbose?: boolean; -} - -export function build(path: string, fetch: (path: string) => PromiseLike, opts?: Options): PromiseLike; \ No newline at end of file diff --git a/ecurve/ecurve-tests.ts b/ecurve/ecurve-tests.ts index 1c73a7e648..c2214c6905 100644 --- a/ecurve/ecurve-tests.ts +++ b/ecurve/ecurve-tests.ts @@ -7,49 +7,49 @@ import BigInteger = require('bigi'); import cs = require('coinstring'); -var ecparams = ecurve.getCurveByName('secp256k1') -console.log(ecparams.n.toString(16)) +var ecparams = ecurve.getCurveByName('secp256k1'); +console.log(ecparams.n.toString(16)); // => fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 -console.log(ecparams.G.getEncoded().toString('hex')) //getEncoded() returns type 'Buffer' instead of 'BigInteger' +console.log(ecparams.G.getEncoded().toString('hex')); // getEncoded() returns type 'Buffer' instead of 'BigInteger' // => 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 -console.log(ecparams.h.toString(16)) +console.log(ecparams.h.toString(16)); // => 1 -var privateKey = new Buffer("1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd", 'hex') +var privateKey = new Buffer("1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd", 'hex'); -var ecparams = ecurve.getCurveByName('secp256k1') -var curvePt = ecparams.G.multiply(BigInteger.fromBuffer(privateKey)) -var x = curvePt.affineX.toBuffer(32) -var y = curvePt.affineY.toBuffer(32) +var ecparams = ecurve.getCurveByName('secp256k1'); +var curvePt = ecparams.G.multiply(BigInteger.fromBuffer(privateKey)); +var x = curvePt.affineX.toBuffer(32); +var y = curvePt.affineY.toBuffer(32); -var publicKey = Buffer.concat([new Buffer([0x04]), x, y]) -console.log(publicKey.toString('hex')) +var publicKey = Buffer.concat([new Buffer([0x04]), x, y]); +console.log(publicKey.toString('hex')); // => 04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495 -//alternatively -publicKey = curvePt.getEncoded(false) //false forces uncompressed public key -console.log(publicKey.toString('hex')) +// alternatively +publicKey = curvePt.getEncoded(false); // false forces uncompressed public key +console.log(publicKey.toString('hex')); // => 04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495 -//want compressed? -publicKey = curvePt.getEncoded(true) //true forces compressed public key -console.log(publicKey.toString('hex')) +// want compressed? +publicKey = curvePt.getEncoded(true); // true forces compressed public key +console.log(publicKey.toString('hex')); // => 03d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6f -var sha = crypto.createHash('sha256').update(publicKey).digest() -var pubkeyHash = crypto.createHash('rmd160').update(sha).digest() +var sha = crypto.createHash('sha256').update(publicKey).digest(); +var pubkeyHash = crypto.createHash('rmd160').update(sha).digest(); // pubkeyHash of compressed public key -console.log(pubkeyHash.toString('hex')) +console.log(pubkeyHash.toString('hex')); // => a1c2f92a9dacbd2991c3897724a93f338e44bdc1 // address of compressed public key -console.log(cs.encode(pubkeyHash, 0x0)) //<-- 0x0 is for public addresses +console.log(cs.encode(pubkeyHash, 0x0)); // <-- 0x0 is for public addresses // => 1FkKMsKNJqWSDvTvETqcCeHcUQQ64kSC6s -console.log(cs.encode(privateKey, 0x80)) //<--- 0x80 is for private addresses +console.log(cs.encode(privateKey, 0x80)); // <--- 0x80 is for private addresses // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD -console.log(cs.encode(Buffer.concat([privateKey, new Buffer([0])]), 0x80)) // <-- compressed private address +console.log(cs.encode(Buffer.concat([privateKey, new Buffer([0])]), 0x80)); // <-- compressed private address // => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5aqzCxDY \ No newline at end of file diff --git a/elastic.js/elastic.js-tests.ts b/elastic.js/elastic.js-tests.ts index 927cb73d91..b683559490 100644 --- a/elastic.js/elastic.js-tests.ts +++ b/elastic.js/elastic.js-tests.ts @@ -1,4 +1,13 @@ -let body = new elasticjs.Request({}) +import * as elasticjs from 'elastic.js'; + +new elasticjs.Request({}) .query(new elasticjs.MatchQuery('title_field', 'testQuery')) .facet(new elasticjs.TermsFacet('tags').field('tags')) .toJSON(); + +new elasticjs.Request({}) + .query(new elasticjs.MatchAllQuery()) + .filter(new elasticjs.BoolFilter().must([ + new elasticjs.TermFilter('a', 'b'), + new elasticjs.TermFilter('c', 'd')])) + .toJSON(); diff --git a/elastic.js/index.d.ts b/elastic.js/index.d.ts index 99a45f58fa..e8b57c5cb7 100644 --- a/elastic.js/index.d.ts +++ b/elastic.js/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Oleksii Trekhleb // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = elasticjs; + +export as namespace elasticjs; + declare module elasticjs { export interface Facet {} @@ -6761,7 +6765,7 @@ declare module elasticjs { /* Allows you to set a specified filter on this request object. */ - filter(filter: Object): Request; + filter(filter: Filter): Request; /* A search result set could be very large (think Google). Setting the diff --git a/electron/index.d.ts b/electron/index.d.ts index 1812c1cc7a..448df1915f 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -2779,7 +2779,7 @@ declare namespace Electron { * The protocol scheme in the form ‘scheme:’. Currently supported values are ‘http:’ or ‘https:’. * Defaults to ‘http:’. */ - Protocol?: 'http:' | 'https:'; + protocol?: 'http:' | 'https:'; /** * The server host provided as a concatenation of the hostname and the port number ‘hostname:port’. */ diff --git a/ember/ember-tests.ts b/ember/ember-tests.ts index dda0e157c4..91e1f61f6f 100644 --- a/ember/ember-tests.ts +++ b/ember/ember-tests.ts @@ -1,4 +1,4 @@ -var App : any; +var App: any; App = Em.Application.create(); @@ -12,7 +12,7 @@ App.country.get('presidentName'); App.president = Em.Object.create({ firstName: 'Barack', lastName: 'Obama', - fullName: function () { + fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property() }); @@ -33,7 +33,7 @@ declare class MyPerson2 extends Em.Object { } var tom = Person1.create({ name: 'Tom Dale', - helloWorld: function() { + helloWorld() { this.say('Hi my name is ' + this.get('name')); } }); @@ -106,14 +106,13 @@ App.userController = Em.Object.create({ }) }); -Handlebars.registerHelper('highlight', function(property: string, options: any) { - return new Handlebars.SafeString('' + "some value" + ''); -}); +Handlebars.registerHelper('highlight', (property: string, options: any) => + new Handlebars.SafeString('' + "some value" + '')); var coolView = App.CoolView.create(); var Person2 = Em.Object.extend({ - sayHello: function() { + sayHello() { console.log('Hello from ' + this.get('name')); } }); @@ -146,7 +145,7 @@ people2.everyProperty('isHappy', true); people2.someProperty('isHappy', true); // Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html -var promise = new Em.RSVP.Promise(function(resolve: Function, reject: Function) { +var promise = new Em.RSVP.Promise((resolve: Function, reject: Function) => { // on success resolve('ok!'); @@ -154,9 +153,9 @@ var promise = new Em.RSVP.Promise(function(resolve: Function, re reject('no-k!'); }); -promise.then(function(value: any) { +promise.then((value: any) => { // on fulfillment -}, function(reason: any) { +}, (reason: any) => { // on rejection }); diff --git a/ember/tslint.json b/ember/tslint.json index e2cf959984..fcd9410184 100644 --- a/ember/tslint.json +++ b/ember/tslint.json @@ -3,6 +3,7 @@ "rules": { // Heavy use of Function type in this older package. "forbidden-types": false, + "no-misused-new": false, // not sure what this means "no-single-declare-module": false } diff --git a/env-to-object/env-to-object-tests.ts b/env-to-object/env-to-object-tests.ts new file mode 100644 index 0000000000..7bc1db3727 --- /dev/null +++ b/env-to-object/env-to-object-tests.ts @@ -0,0 +1,35 @@ +import * as envToObject from 'env-to-object'; + +const map = { + NODE_ENV: { + keypath: 'env', + type: 'string' + }, + PORT: { + keypath: 'server.port', + type: 'number' + }, + SSL: { + keypath: 'server.ssl', + type: 'boolean' + }, + LOG_LEVEL: { + keypath: 'logger.level', + type: 'string' + }, + INT: { + keypath: 'int', + type: 'integer', + radix: '2' + } +}; + +const result1: any = envToObject(map); +const result2: any = envToObject(map, { + parsers: { + 'my-custom-type': (str: string, opts: any) => { + const foo: any = JSON.parse(str); + return foo; + } + } +}); diff --git a/env-to-object/index.d.ts b/env-to-object/index.d.ts new file mode 100644 index 0000000000..1ec7a3c994 --- /dev/null +++ b/env-to-object/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for env-to-object 1.1 +// Project: https://github.com/kgryte/node-env-to-object#readme +// Definitions by: TANAKA Koichi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace env { + export interface Mappings { + [enviromentVariableName: string]: Mapping; + } + + export type Mapping = IntegerMapping | BooleanMapping | GenericMapping; + + interface GenericMapping { + keypath: string; + type?: string; + [opt: string]: any; + } + + interface IntegerMapping extends GenericMapping { + type: "integer"; + radix: number; + } + + interface BooleanMapping { + type: "boolean"; + strict: boolean; + } + + export interface Parsers { + [parserName: string]: (str: string, opts: any) => any; + } + + export interface Options { + parsers: Parsers; + } +} + +declare function env(map: env.Mappings, options?: env.Options): any; +export = env; diff --git a/env-to-object/tsconfig.json b/env-to-object/tsconfig.json new file mode 100644 index 0000000000..316a2acdf6 --- /dev/null +++ b/env-to-object/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", + "env-to-object-tests.ts" + ] +} \ No newline at end of file diff --git a/env-to-object/tslint.json b/env-to-object/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/env-to-object/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 035f0dfcd7..82a8dc9822 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -1,48 +1,44 @@ -import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme"; import * as React from "react"; -import {Component, ReactElement, HTMLAttributes} from "react"; -import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme"; +import {shallow, mount, render, ShallowWrapper, ReactWrapper} from "enzyme"; +import {Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent} from "react"; // Help classes/interfaces interface MyComponentProps { - propsProperty: any; + stringProp: string; numberProp?: number; } interface StatelessProps { - stateless: any; + stateless: string; } interface MyComponentState { - stateProperty: any; + stateProperty: string; } class MyComponent extends Component { setState(...args: any[]) { + console.log(args); } } const MyStatelessComponent = (props: StatelessProps) => ; -// API -namespace SpyLifecycleTest { - spyLifecycle(MyComponent); -} - // ShallowWrapper namespace ShallowWrapperTest { var shallowWrapper: ShallowWrapper = - shallow(); + shallow(); var reactElement: ReactElement, - objectVal: Object, - boolVal: Boolean, - stringVal: String, + objectVal: {}, + boolVal: boolean, + stringVal: string, numOrStringVal: number | string, - elementWrapper: ShallowWrapper, {}> + elementWrapper: ShallowWrapper, {}>, + statelessWrapper: ShallowWrapper; function test_shallow_options() { - shallow(, { + shallow(, { context: { test: "a", }, @@ -51,11 +47,10 @@ namespace ShallowWrapperTest { } function test_find() { - elementWrapper = shallowWrapper.find('.selector'); shallowWrapper = shallowWrapper.find(MyComponent); - shallowWrapper.find(MyStatelessComponent).props().stateless; - shallowWrapper.find(MyStatelessComponent).shallow(); - shallowWrapper.find({ prop: 'value' }); + statelessWrapper = shallowWrapper.find(MyStatelessComponent); + shallowWrapper = shallowWrapper.find({ prop: 'value' }); + elementWrapper = shallowWrapper.find('.selector'); } function test_findWhere() { @@ -64,15 +59,16 @@ namespace ShallowWrapperTest { } function test_filter() { + shallowWrapper = shallowWrapper.filter(MyComponent); + statelessWrapper = statelessWrapper.filter(MyStatelessComponent); + shallowWrapper = shallowWrapper.filter({ numberProp: 12 }); elementWrapper = shallowWrapper.filter('.selector'); - shallowWrapper = shallowWrapper.filter(MyComponent).shallow(); - shallowWrapper.filter({ prop: 'val' }); } function test_filterWhere() { shallowWrapper = shallowWrapper.filterWhere(wrapper => { - wrapper.props().propsProperty; + wrapper.props().stringProp; return true; }); } @@ -95,11 +91,11 @@ namespace ShallowWrapperTest { function test_dive() { interface TmpProps { - foo: any + foo: any; } interface TmpState { - bar: any + bar: any; } const diveWrapper: ShallowWrapper = shallowWrapper.dive({ context: { foobar: 'barfoo' }}); @@ -122,11 +118,11 @@ namespace ShallowWrapperTest { } function test_isEmpty() { - boolVal = shallowWrapper.isEmpty() + boolVal = shallowWrapper.isEmpty(); } function test_exists() { - boolVal = shallowWrapper.exists() + boolVal = shallowWrapper.exists(); } function test_not() { @@ -135,19 +131,21 @@ namespace ShallowWrapperTest { function test_children() { shallowWrapper = shallowWrapper.children(); - shallowWrapper.children(MyStatelessComponent).props().stateless; - shallowWrapper.children({ prop: 'myprop' }); + shallowWrapper = shallowWrapper.children(MyComponent); + statelessWrapper = shallowWrapper.children(MyStatelessComponent); + shallowWrapper = shallowWrapper.children({ prop: 'value' }); + elementWrapper = shallowWrapper.children('.selector'); } function test_childAt() { const childWrapper: ShallowWrapper = shallowWrapper.childAt(0); interface TmpType1 { - foo: any + foo: any; } interface TmpType2 { - bar: any + bar: any; } const childWrapper2: ShallowWrapper = shallowWrapper.childAt(0); @@ -155,6 +153,10 @@ namespace ShallowWrapperTest { function test_parents() { shallowWrapper = shallowWrapper.parents(); + shallowWrapper = shallowWrapper.parents(MyComponent); + statelessWrapper = shallowWrapper.parents(MyStatelessComponent); + shallowWrapper = shallowWrapper.parents({ prop: 'myprop' }); + elementWrapper = shallowWrapper.parents('.selector'); } function test_parent() { @@ -162,9 +164,10 @@ namespace ShallowWrapperTest { } function test_closest() { - elementWrapper = shallowWrapper.closest('.selector'); shallowWrapper = shallowWrapper.closest(MyComponent); + statelessWrapper = shallowWrapper.closest(MyStatelessComponent); shallowWrapper = shallowWrapper.closest({ prop: 'myprop' }); + elementWrapper = shallowWrapper.closest('.selector'); } function test_shallow() { @@ -175,15 +178,10 @@ namespace ShallowWrapperTest { shallowWrapper = shallowWrapper.unmount(); } - function test_render() { - var cheerioWrapper: CheerioWrapper = shallowWrapper.render(); - } - function test_text() { stringVal = shallowWrapper.text(); } - function test_html() { stringVal = shallowWrapper.html(); } @@ -206,23 +204,28 @@ namespace ShallowWrapperTest { function test_state() { const state: MyComponentState = shallowWrapper.state(); - shallowWrapper.state('key'); - const tmp: String = shallowWrapper.state('key'); + const prop: string = shallowWrapper.state('stateProperty'); + const prop2: number = shallowWrapper.state('key'); + const prop3 = shallowWrapper.state('key'); } function test_context() { shallowWrapper.context(); shallowWrapper.context('key'); - const tmp: String = shallowWrapper.context('key'); + const tmp: string = shallowWrapper.context('key'); } function test_props() { - objectVal = shallowWrapper.props(); + const props: MyComponentProps = shallowWrapper.props(); + const props2: MyComponentProps = shallowWrapper.find(MyComponent).props(); + const props3: StatelessProps = shallowWrapper.find(MyStatelessComponent).props(); + const props4: HTMLAttributes = shallowWrapper.find('.selector').props(); } function test_prop() { - shallowWrapper.prop('key'); - const tmp: String = shallowWrapper.prop('key'); + const tmp: number = shallowWrapper.prop('numberProp'); + const tmp2: string = shallowWrapper.prop('key'); + const tmp3 = shallowWrapper.prop('key'); } function test_key() { @@ -239,7 +242,7 @@ namespace ShallowWrapperTest { } function test_setProps() { - shallowWrapper = shallowWrapper.setProps({ propsProperty: 'foo' }, () => console.log('props updated')); + shallowWrapper = shallowWrapper.setProps({ stringProp: 'foo' }); } function test_setContext() { @@ -259,20 +262,20 @@ namespace ShallowWrapperTest { } function test_type() { - var stringOrFunction: String | Function = shallowWrapper.type(); + const type: string | StatelessComponent | ComponentClass = shallowWrapper.type(); } function test_name() { - var str: String = shallowWrapper.name(); + stringVal = shallowWrapper.name(); } function test_forEach() { shallowWrapper = - shallowWrapper.forEach(wrapper => wrapper.shallow().props().propsProperty); + shallowWrapper.forEach(wrapper => wrapper.shallow().props().stringProp); } function test_map() { - var arrayNumbers: Array = + var arrayNumbers: number[] = shallowWrapper.map(wrapper => wrapper.props().numberProp); } @@ -286,13 +289,15 @@ namespace ShallowWrapperTest { function test_reduceRight() { const total: number = shallowWrapper.reduceRight( - (amount: number, n: ShallowWrapper) => amount + n.prop('amount') + (amount: number, n: ShallowWrapper) => amount + n.prop('numberProp') ); } function test_some() { - boolVal = shallowWrapper.some('.selector'); boolVal = shallowWrapper.some(MyComponent); + boolVal = shallowWrapper.some(MyStatelessComponent); + boolVal = shallowWrapper.some({ prop: 'myprop' }); + boolVal = shallowWrapper.some('.selector'); } function test_someWhere() { @@ -300,8 +305,10 @@ namespace ShallowWrapperTest { } function test_every() { - boolVal = shallowWrapper.every('.selector'); boolVal = shallowWrapper.every(MyComponent); + boolVal = shallowWrapper.every(MyStatelessComponent); + boolVal = shallowWrapper.every({ prop: 'myprop' }); + boolVal = shallowWrapper.every('.selector'); } function test_everyWhere() { @@ -321,13 +328,14 @@ namespace ShallowWrapperTest { // ReactWrapper namespace ReactWrapperTest { var reactWrapper: ReactWrapper = - mount(); + mount(); var reactElement: ReactElement, - objectVal: Object, - boolVal: Boolean, - stringVal: String, - elementWrapper: ReactWrapper, {}> + objectVal: {}, + boolVal: boolean, + stringVal: string, + elementWrapper: ReactWrapper, {}>, + statelessWrapper: ReactWrapper; function test_unmount() { reactWrapper = reactWrapper.unmount(); @@ -336,7 +344,7 @@ namespace ReactWrapperTest { function test_mount() { reactWrapper = reactWrapper.mount(); - mount(, { + mount(, { attachTo: document.getElementById('test'), context: { a: "b" @@ -348,11 +356,11 @@ namespace ReactWrapperTest { reactWrapper = reactWrapper.ref('refName'); interface TmpType1 { - foo: string + foo: string; } interface TmpType2 { - bar: string + bar: string; } const tmp: ReactWrapper = reactWrapper.ref('refName'); @@ -365,8 +373,8 @@ namespace ReactWrapperTest { function test_find() { elementWrapper = reactWrapper.find('.selector'); reactWrapper = reactWrapper.find(MyComponent); - reactWrapper.find(MyStatelessComponent).props().stateless; - reactWrapper.find({ prop: 'myprop' }); + statelessWrapper = reactWrapper.find(MyStatelessComponent); + reactWrapper = reactWrapper.find({ prop: 'myprop' }); } function test_findWhere() { @@ -375,15 +383,16 @@ namespace ReactWrapperTest { } function test_filter() { - elementWrapper = reactWrapper.filter('.selector'); reactWrapper = reactWrapper.filter(MyComponent); - reactWrapper = reactWrapper.filter({ prop: 'myprop' }); + statelessWrapper = statelessWrapper.filter(MyStatelessComponent); + reactWrapper = reactWrapper.filter({ numberProp: 12 }); + elementWrapper = reactWrapper.filter('.selector'); } function test_filterWhere() { reactWrapper = reactWrapper.filterWhere(wrapper => { - wrapper.props().propsProperty; + wrapper.props().stringProp; return true; }); } @@ -421,7 +430,7 @@ namespace ReactWrapperTest { } function test_isEmpty() { - boolVal = reactWrapper.isEmpty() + boolVal = reactWrapper.isEmpty(); } function test_not() { @@ -430,17 +439,21 @@ namespace ReactWrapperTest { function test_children() { reactWrapper = reactWrapper.children(); + reactWrapper = reactWrapper.children(MyComponent); + statelessWrapper = reactWrapper.children(MyStatelessComponent); + reactWrapper = reactWrapper.children({ prop: 'myprop' }); + elementWrapper = reactWrapper.children('.selector'); } function test_childAt() { const childWrapper: ReactWrapper = reactWrapper.childAt(0); interface TmpType1 { - foo: any + foo: any; } interface TmpType2 { - bar: any + bar: any; } const childWrapper2: ReactWrapper = reactWrapper.childAt(0); @@ -448,6 +461,10 @@ namespace ReactWrapperTest { function test_parents() { reactWrapper = reactWrapper.parents(); + reactWrapper = reactWrapper.parents(MyComponent); + statelessWrapper = reactWrapper.parents(MyStatelessComponent); + reactWrapper = reactWrapper.parents({ prop: 'myprop' }); + elementWrapper = reactWrapper.parents('.selector'); } function test_parent() { @@ -455,9 +472,10 @@ namespace ReactWrapperTest { } function test_closest() { - elementWrapper = reactWrapper.closest('.selector'); reactWrapper = reactWrapper.closest(MyComponent); + statelessWrapper = reactWrapper.closest(MyStatelessComponent); reactWrapper = reactWrapper.closest({ prop: 'myprop' }); + elementWrapper = reactWrapper.closest('.selector'); } function test_text() { @@ -485,24 +503,29 @@ namespace ReactWrapperTest { } function test_state() { - reactWrapper.state(); - reactWrapper.state('key'); - const tmp: String = reactWrapper.state('key'); + const state: MyComponentState = reactWrapper.state(); + const prop: string = reactWrapper.state('stateProperty'); + const prop2: number = reactWrapper.state('key'); + const prop3 = reactWrapper.state('key'); } function test_context() { reactWrapper.context(); reactWrapper.context('key'); - const tmp: String = reactWrapper.context('key'); + const tmp: string = reactWrapper.context('key'); } function test_props() { - objectVal = reactWrapper.props(); + const props: MyComponentProps = reactWrapper.props(); + const props2: MyComponentProps = reactWrapper.find(MyComponent).props(); + const props3: StatelessProps = reactWrapper.find(MyStatelessComponent).props(); + const props4: HTMLAttributes = reactWrapper.find('.selector').props(); } function test_prop() { - reactWrapper.prop('key'); - const tmp: String = reactWrapper.prop('key'); + const tmp: number = reactWrapper.prop('numberProp'); + const tmp2: string = reactWrapper.prop('key'); + const tmp3 = reactWrapper.prop('key'); } function test_key() { @@ -519,7 +542,7 @@ namespace ReactWrapperTest { } function test_setProps() { - reactWrapper = reactWrapper.setProps({ propsProperty: 'foo' }); + reactWrapper = reactWrapper.setProps({ stringProp: 'foo' }); } function test_setContext() { @@ -539,40 +562,42 @@ namespace ReactWrapperTest { } function test_type() { - var stringOrFunction: String | Function = reactWrapper.type(); + const type: string | StatelessComponent | ComponentClass = reactWrapper.type(); } function test_name() { - var str: String = reactWrapper.name(); + stringVal = reactWrapper.name(); } function test_forEach() { reactWrapper = - reactWrapper.forEach(wrapper => wrapper.props().propsProperty); + reactWrapper.forEach(wrapper => wrapper.props().stringProp); } function test_map() { - var arrayNumbers: Array = + var arrayNumbers: number[] = reactWrapper.map(wrapper => wrapper.props().numberProp); } function test_reduce() { const total: number = reactWrapper.reduce( - (amount: number, n: ReactWrapper) => amount + n.prop('amount') + (amount: number, n: ReactWrapper) => amount + n.prop('numberProp') ); } function test_reduceRight() { const total: number = reactWrapper.reduceRight( - (amount: number, n: ReactWrapper) => amount + n.prop('amount') + (amount: number, n: ReactWrapper) => amount + n.prop('numberProp') ); } function test_some() { - boolVal = reactWrapper.some('.selector'); boolVal = reactWrapper.some(MyComponent); + boolVal = reactWrapper.some(MyStatelessComponent); + boolVal = reactWrapper.some({ prop: 'myprop' }); + boolVal = reactWrapper.some('.selector'); } function test_someWhere() { @@ -580,8 +605,10 @@ namespace ReactWrapperTest { } function test_every() { - boolVal = reactWrapper.every('.selector'); boolVal = reactWrapper.every(MyComponent); + boolVal = reactWrapper.every(MyStatelessComponent); + boolVal = reactWrapper.every({ prop: 'myprop' }); + boolVal = reactWrapper.every('.selector'); } function test_everyWhere() { @@ -594,239 +621,9 @@ namespace ReactWrapperTest { // CheerioWrapper namespace CheerioWrapperTest { - var cheerioWrapper: CheerioWrapper = - render(); + const wrapper: Cheerio = + shallow(

).render() || + mount(
).render(); - var reactElement: ReactElement, - objectVal: Object, - boolVal: Boolean, - stringVal: String, - elementWrapper: CheerioWrapper, {}> - - function test_find() { - elementWrapper = cheerioWrapper.find('.selector'); - cheerioWrapper = cheerioWrapper.find(MyComponent); - cheerioWrapper.find(MyStatelessComponent).props().stateless; - cheerioWrapper.find({ prop: 'myprop' }); - } - - function test_findWhere() { - cheerioWrapper = - cheerioWrapper.findWhere((aCheerioWrapper: CheerioWrapper) => true); - } - - function test_filter() { - elementWrapper = cheerioWrapper.filter('.selector'); - cheerioWrapper = cheerioWrapper.filter(MyComponent); - cheerioWrapper = cheerioWrapper.filter({ prop: 'myprop' }); - } - - function test_filterWhere() { - cheerioWrapper = - cheerioWrapper.filterWhere(wrapper => { - wrapper.props().propsProperty; - return true; - }); - } - - function test_contains() { - boolVal = cheerioWrapper.contains(
); - } - - function test_containsMatchingElement() { - boolVal = cheerioWrapper.contains(
); - } - - function test_containsAllMatchingElements() { - boolVal = cheerioWrapper.containsAllMatchingElements([
]); - } - - function test_containsAnyMatchingElement() { - boolVal = cheerioWrapper.containsAnyMatchingElements([
]); - } - - function test_equals() { - boolVal = cheerioWrapper.equals(
); - } - - function test_matchesElement() { - boolVal = cheerioWrapper.matchesElement(
); - } - - function test_hasClass() { - boolVal = cheerioWrapper.find('.my-button').hasClass('disabled'); - } - - function test_is() { - boolVal = cheerioWrapper.is('.some-class'); - } - - function test_isEmpty() { - boolVal = cheerioWrapper.isEmpty() - } - - function test_not() { - elementWrapper = cheerioWrapper.find('.foo').not('.bar'); - } - - function test_children() { - cheerioWrapper = cheerioWrapper.children(); - } - - function test_childAt() { - const childWrapper: CheerioWrapper = cheerioWrapper.childAt(0); - - interface TmpType1 { - foo: any - } - - interface TmpType2 { - bar: any - } - - const childWrapper2: CheerioWrapper = cheerioWrapper.childAt(0); - } - - function test_parents() { - cheerioWrapper = cheerioWrapper.parents(); - } - - function test_parent() { - cheerioWrapper = cheerioWrapper.parent(); - } - - function test_closest() { - elementWrapper = cheerioWrapper.closest('.selector'); - cheerioWrapper = cheerioWrapper.closest(MyComponent); - cheerioWrapper = cheerioWrapper.closest({ prop: 'myprop' }); - } - - function test_text() { - stringVal = cheerioWrapper.text(); - } - - function test_html() { - stringVal = cheerioWrapper.html(); - } - - function test_get() { - reactElement = cheerioWrapper.get(1); - } - - function test_at() { - cheerioWrapper = cheerioWrapper.at(1); - } - - function test_first() { - cheerioWrapper = cheerioWrapper.first(); - } - - function test_last() { - cheerioWrapper = cheerioWrapper.last(); - } - - function test_state() { - cheerioWrapper.state(); - cheerioWrapper.state('key'); - const tmp: String = cheerioWrapper.state('key'); - } - - function test_context() { - cheerioWrapper.context(); - cheerioWrapper.context('key'); - const tmp: String = cheerioWrapper.context('key'); - } - - function test_props() { - objectVal = cheerioWrapper.props(); - } - - function test_prop() { - cheerioWrapper.prop('key'); - const tmp: String = cheerioWrapper.prop('key'); - } - - function test_key() { - stringVal = cheerioWrapper.key(); - } - - function test_simulate(...args: any[]) { - cheerioWrapper.simulate('click'); - cheerioWrapper.simulate('click', args); - } - - function test_setState() { - cheerioWrapper = cheerioWrapper.setState({ stateProperty: 'state' }); - } - - function test_setProps() { - cheerioWrapper = cheerioWrapper.setProps({ propsProperty: 'foo' }); - } - - function test_setContext() { - cheerioWrapper = cheerioWrapper.setContext({ name: 'baz' }); - } - - function test_instance() { - var myComponent: MyComponent = cheerioWrapper.instance(); - } - - function test_update() { - cheerioWrapper = cheerioWrapper.update(); - } - - function test_debug() { - stringVal = cheerioWrapper.debug(); - } - - function test_type() { - var stringOrFunction: String | Function = cheerioWrapper.type(); - } - - function test_name() { - var str: String = cheerioWrapper.name(); - } - - function test_forEach() { - cheerioWrapper = - cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper) => { - }); - } - - function test_map() { - var arrayNumbers: Array = - cheerioWrapper.map(wrapper => wrapper.props().numberProp); - } - - function test_reduce() { - const total: number = - cheerioWrapper.reduce( - (amount: number, n: CheerioWrapper) => amount + n.prop('amount') - ); - } - - function test_reduceRight() { - const total: number = - cheerioWrapper.reduceRight( - (amount: number, n: CheerioWrapper) => amount + n.prop('amount') - ); - } - - function test_some() { - boolVal = cheerioWrapper.some('.selector'); - boolVal = cheerioWrapper.some(MyComponent); - } - - function test_someWhere() { - boolVal = cheerioWrapper.someWhere((aCheerioWrapper: CheerioWrapper) => true); - } - - function test_every() { - boolVal = cheerioWrapper.every('.selector'); - boolVal = cheerioWrapper.every(MyComponent); - } - - function test_everyWhere() { - boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper) => true); - } + wrapper.toggleClass('className'); } diff --git a/enzyme/index.d.ts b/enzyme/index.d.ts index 94b60fc199..fc498ca78a 100644 --- a/enzyme/index.d.ts +++ b/enzyme/index.d.ts @@ -1,15 +1,31 @@ -// Type definitions for Enzyme v2.7.0 +// Type definitions for Enzyme 2.7 // Project: https://github.com/airbnb/enzyme -// Definitions by: Marian Palkus , Cap3 , Ivo Stratev , Tom Crockett +// Definitions by: Marian Palkus +// Cap3 +// Ivo Stratev +// Tom Crockett +// jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -import { ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; +/// +import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; export class ElementClass extends Component { } +/* These are purposefully stripped down versions of React.ComponentClass and React.StatelessComponent. + * The optional static properties on them break overload ordering for wrapper methods if they're not + * all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics + */ +interface ComponentClass { + new(props?: Props, context?: any): Component; +} + +type StatelessComponent = (props: Props, context?: any) => JSX.Element; + /** * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the * following three categories: @@ -20,34 +36,12 @@ export class ElementClass extends Component { * 4. A React Stateless component * 5. A React component property map */ -export type EnzymeSelector = string | StatelessComponent | ComponentClass | { [key: string]: any }; -export type EnzymePropSelector = { [key: string]: any }; +export interface EnzymePropSelector { + [key: string]: any; +} +export type EnzymeSelector = string | StatelessComponent | ComponentClass | EnzymePropSelector; interface CommonWrapper { - /** - * Find every node in the render tree that matches the provided selector. - * @param selector The selector to match. - */ - find(component: ComponentClass): CommonWrapper; - find(statelessComponent: StatelessComponent): CommonWrapper; - find(props: EnzymePropSelector): CommonWrapper; - find(selector: string): CommonWrapper; - - /** - * Finds every node in the render tree that returns true for the provided predicate function. - * @param predicate - */ - findWhere(predicate: (wrapper: CommonWrapper) => boolean): CommonWrapper; - - /** - * Removes nodes in the current wrapper that do not match the provided selector. - * @param selector The selector to match. - */ - filter(component: ComponentClass): CommonWrapper; - filter(statelessComponent: StatelessComponent): CommonWrapper; - filter(props: EnzymePropSelector): CommonWrapper; - filter(selector: string): CommonWrapper; - /** * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. * @param predicate @@ -70,13 +64,13 @@ interface CommonWrapper { * Returns whether or not all the given react elements exists in the shallow render tree * @param nodes */ - containsAllMatchingElements(nodes: ReactElement[]): boolean; + containsAllMatchingElements(nodes: Array>): boolean; /** * Returns whether or not one of the given react elements exists in the shallow render tree. * @param nodes */ - containsAnyMatchingElements(nodes: ReactElement[]): boolean; + containsAnyMatchingElements(nodes: Array>): boolean; /** * Returns whether or not the current render tree is equal to the given node, based on the expected value. @@ -117,54 +111,6 @@ interface CommonWrapper { */ not(selector: EnzymeSelector): this; - /** - * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector - * can be provided and it will filter the children by this selector. - * @param [selector] - */ - children(component: ComponentClass): CommonWrapper; - children(statelessComponent: StatelessComponent): CommonWrapper; - children(props: EnzymePropSelector): CommonWrapper; - children(selector: string): CommonWrapper; - children(): CommonWrapper; - - /** - * Returns a new wrapper with child at the specified index. - * @param index - */ - childAt(index: number): CommonWrapper; - childAt(index: number): CommonWrapper; - - /** - * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the - * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. - * - * Note: can only be called on a wrapper of a single node. - * @param [selector] - */ - parents(component: ComponentClass): CommonWrapper; - parents(statelessComponent: StatelessComponent): CommonWrapper; - parents(props: EnzymePropSelector): CommonWrapper; - parents(selector: string): CommonWrapper; - parents(): CommonWrapper; - - /** - * Returns a wrapper with the direct parent of the node in the current wrapper. - */ - parent(): CommonWrapper; - - /** - * Returns a wrapper of the first element that matches the selector by traversing up through the current node's - * ancestors in the tree, starting with itself. - * - * Note: can only be called on a wrapper of a single node. - * @param selector - */ - closest(component: ComponentClass): CommonWrapper; - closest(statelessComponent: StatelessComponent): CommonWrapper; - closest(props: EnzymePropSelector): CommonWrapper; - closest(selector: string): CommonWrapper; - /** * Returns a string of the rendered text of the current render tree. This function should be looked at with * skepticism if being used to test what the actual HTML output of the component will be. If that is what you @@ -208,14 +154,14 @@ interface CommonWrapper { * @param [key] */ state(): S; - state(key: string): any; + state(key: K): S[K]; state(key: string): T; /** * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. */ - context(key?: string): any; - context(key?: string): T; + context(): any; + context(key: string): T; /** * Returns the props hash for the current node of the wrapper. @@ -230,7 +176,7 @@ interface CommonWrapper { * NOTE: can only be called on a wrapper of a single node. * @param key */ - prop(key: string): any; + prop(key: K): P[K]; prop(key: string): T; /** @@ -259,7 +205,7 @@ interface CommonWrapper { * @param state * @param [callback] */ - setState(state: S, callback?: () => void): this; + setState(state: Pick, callback?: () => void): this; /** * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test @@ -273,7 +219,7 @@ interface CommonWrapper { * @param props * @param [callback] */ - setProps(props: P, callback?: () => void): this; + setProps(props: Pick): this; /** * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to @@ -283,7 +229,7 @@ interface CommonWrapper { * NOTE: can only be called on a wrapper instance that is also the root instance. * @param state */ - setContext(context: Object): this; + setContext(context: any): this; /** * Gets the instance of the component being rendered as the root node passed into shallow(). @@ -307,14 +253,6 @@ interface CommonWrapper { */ debug(): string; - /** - * Returns the type of the current node of this wrapper. If it's a composite component, this will be the - * component constructor. If it's native DOM node, it will be a string of the tag name. - * - * Note: can only be called on a wrapper of a single node. - */ - type(): string | Function; - /** * Returns the name of the current node of the wrapper. */ @@ -328,7 +266,7 @@ interface CommonWrapper { * @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first * argument, and will be run with a context of the original instance. */ - forEach(fn: (wrapper: this) => any): this; + forEach(fn: (wrapper: this, index: number) => any): this; /** * Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map @@ -338,7 +276,7 @@ interface CommonWrapper { * to the returned array. Should expect a ShallowWrapper as the first argument, and will be run * with a context of the original instance. */ - map(fn: (wrapper: this) => V): V[]; + map(fn: (wrapper: this, index: number) => V): V[]; /** * Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node @@ -380,12 +318,29 @@ interface CommonWrapper { */ everyWhere(fn: (wrapper: this) => boolean): boolean; + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; + + /** + * Renders the component to static markup and returns a Cheerio wrapper around the result. + */ + render(): Cheerio; + + /** + * Returns the type of the current node of this wrapper. If it's a composite component, this will be the + * component constructor. If it's native DOM node, it will be a string of the tag name. + * + * Note: can only be called on a wrapper of a single node. + */ + type(): string | ComponentClass

| StatelessComponent

; + length: number; } export interface ShallowWrapper extends CommonWrapper { shallow(): ShallowWrapper; - render(): CheerioWrapper; unmount(): ShallowWrapper; /** @@ -393,7 +348,7 @@ export interface ShallowWrapper extends CommonWrapper { * @param selector The selector to match. */ find(component: ComponentClass): ShallowWrapper; - find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; + find(statelessComponent: StatelessComponent): ShallowWrapper; find(props: EnzymePropSelector): ShallowWrapper; find(selector: string): ShallowWrapper; @@ -401,16 +356,15 @@ export interface ShallowWrapper extends CommonWrapper { * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ShallowWrapper; - filter(statelessComponent: StatelessComponent): ShallowWrapper; - filter(props: EnzymePropSelector): ShallowWrapper; - filter(selector: string): ShallowWrapper; + filter(component: ComponentClass | StatelessComponent): this; + filter(props: Partial

): this; + filter(selector: string): this; /** * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => boolean): ShallowWrapper; + findWhere(predicate: (wrapper: ShallowWrapper) => boolean): ShallowWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector @@ -418,10 +372,9 @@ export interface ShallowWrapper extends CommonWrapper { * @param [selector] */ children(component: ComponentClass): ShallowWrapper; - children(statelessComponent: StatelessComponent): ShallowWrapper; - children(props: EnzymePropSelector): ShallowWrapper; + children(statelessComponent: StatelessComponent): ShallowWrapper; children(selector: string): ShallowWrapper; - children(): ShallowWrapper; + children(props?: EnzymePropSelector): ShallowWrapper; /** * Returns a new wrapper with child at the specified index. @@ -431,13 +384,13 @@ export interface ShallowWrapper extends CommonWrapper { childAt(index: number): ShallowWrapper; /** - * Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result. - * NOTE: can only be called on wrapper of a single non-DOM component element node. - * @param [options] - */ - dive(options?: ShallowRendererProps): ShallowWrapper; + * Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result. + * NOTE: can only be called on wrapper of a single non-DOM component element node. + * @param [options] + */ + dive(options?: ShallowRendererProps): ShallowWrapper; - /** + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * @@ -445,10 +398,9 @@ export interface ShallowWrapper extends CommonWrapper { * @param [selector] */ parents(component: ComponentClass): ShallowWrapper; - parents(statelessComponent: StatelessComponent): ShallowWrapper; - parents(props: EnzymePropSelector): ShallowWrapper; + parents(statelessComponent: StatelessComponent): ShallowWrapper; parents(selector: string): ShallowWrapper; - parents(): ShallowWrapper; + parents(props?: EnzymePropSelector): ShallowWrapper; /** * Returns a wrapper of the first element that matches the selector by traversing up through the current node's @@ -458,7 +410,7 @@ export interface ShallowWrapper extends CommonWrapper { * @param selector */ closest(component: ComponentClass): ShallowWrapper; - closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(statelessComponent: StatelessComponent): ShallowWrapper; closest(props: EnzymePropSelector): ShallowWrapper; closest(selector: string): ShallowWrapper; @@ -466,17 +418,11 @@ export interface ShallowWrapper extends CommonWrapper { * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ShallowWrapper; - - /** - * Returns true if renderer returned null - */ - isEmptyRender(): boolean; } export interface ReactWrapper extends CommonWrapper { unmount(): ReactWrapper; mount(): ReactWrapper; - render(): CheerioWrapper; /** * Returns a wrapper of the node that matches the provided reference name. @@ -493,7 +439,8 @@ export interface ReactWrapper extends CommonWrapper { * * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. * - * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. + * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. + * It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. */ detach(): void; @@ -502,7 +449,7 @@ export interface ReactWrapper extends CommonWrapper { * @param selector The selector to match. */ find(component: ComponentClass): ReactWrapper; - find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(statelessComponent: StatelessComponent): ReactWrapper; find(props: EnzymePropSelector): ReactWrapper; find(selector: string): ReactWrapper; @@ -510,16 +457,15 @@ export interface ReactWrapper extends CommonWrapper { * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => boolean): ReactWrapper; + findWhere(predicate: (wrapper: ReactWrapper) => boolean): ReactWrapper; /** * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ReactWrapper; - filter(statelessComponent: StatelessComponent): ReactWrapper; - filter(props: EnzymePropSelector): ReactWrapper; - filter(selector: string): ReactWrapper; + filter(component: ComponentClass | StatelessComponent): this; + filter(props: Partial

): this; + filter(selector: string): this; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector @@ -527,10 +473,9 @@ export interface ReactWrapper extends CommonWrapper { * @param [selector] */ children(component: ComponentClass): ReactWrapper; - children(statelessComponent: StatelessComponent): ReactWrapper; - children(props: EnzymePropSelector): ReactWrapper; + children(statelessComponent: StatelessComponent): ReactWrapper; children(selector: string): ReactWrapper; - children(): ReactWrapper; + children(props?: EnzymePropSelector): ReactWrapper; /** * Returns a new wrapper with child at the specified index. @@ -547,10 +492,9 @@ export interface ReactWrapper extends CommonWrapper { * @param [selector] */ parents(component: ComponentClass): ReactWrapper; - parents(statelessComponent: StatelessComponent): ReactWrapper; - parents(props: EnzymePropSelector): ReactWrapper; + parents(statelessComponent: StatelessComponent): ReactWrapper; parents(selector: string): ReactWrapper; - parents(): ReactWrapper; + parents(props?: EnzymePropSelector): ReactWrapper; /** * Returns a wrapper of the first element that matches the selector by traversing up through the current node's @@ -560,7 +504,7 @@ export interface ReactWrapper extends CommonWrapper { * @param selector */ closest(component: ComponentClass): ReactWrapper; - closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(statelessComponent: StatelessComponent): ReactWrapper; closest(props: EnzymePropSelector): ReactWrapper; closest(selector: string): ReactWrapper; @@ -568,15 +512,6 @@ export interface ReactWrapper extends CommonWrapper { * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ReactWrapper; - - /** - * Returns true if renderer returned null - */ - isEmptyRender(): boolean; -} - -export interface CheerioWrapper extends CommonWrapper { - } export interface ShallowRendererProps { @@ -625,8 +560,4 @@ export function mount(node: ReactElement

, options?: MountRendererProps) * @param node * @param [options] */ -export function render(node: ReactElement

, options?: any): CheerioWrapper; - -export function describeWithDOM(description: string, fn: Function): void; - -export function spyLifecycle(component: typeof Component): void; +export function render(node: ReactElement

, options?: any): Cheerio; diff --git a/enzyme/tslint.json b/enzyme/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/enzyme/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/es6-weak-map/es6-weak-map-tests.ts b/es6-weak-map/es6-weak-map-tests.ts new file mode 100644 index 0000000000..68f5ea7f43 --- /dev/null +++ b/es6-weak-map/es6-weak-map-tests.ts @@ -0,0 +1,18 @@ +import WeakMap = require('es6-weak-map'); + +new WeakMap<{}, string>(); + +var tuples: Array<[number, string]> = [ [0, 'foo'], [1, 'bar'] ]; +new WeakMap(tuples); + +var map = new WeakMap<{}, string>(); +var obj = {}; + +map.set(obj, 'foo'); +map.get(obj); +map.has(obj); +map.delete(obj); +map.get(obj); +map.has(obj); +map.set(obj, 'bar'); +map.has(obj); diff --git a/es6-weak-map/index.d.ts b/es6-weak-map/index.d.ts new file mode 100644 index 0000000000..50035420c8 --- /dev/null +++ b/es6-weak-map/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for es6-weak-map 1.2 +// Project: https://github.com/medikoo/es6-weak-map +// Definitions by: Pine Mizune +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = WeakMap; +export as namespace WeakMap; + +interface Iterable { + [Symbol.iterator](): Iterator; +} + +declare class WeakMap { + constructor(); + constructor(iterable: Iterable<[K, V]>); + + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; +} diff --git a/es6-weak-map/tsconfig.json b/es6-weak-map/tsconfig.json new file mode 100644 index 0000000000..4a80116224 --- /dev/null +++ b/es6-weak-map/tsconfig.json @@ -0,0 +1,23 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "es6-weak-map-tests.ts" + ] +} diff --git a/es6-weak-map/tslint.json b/es6-weak-map/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/es6-weak-map/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/expect/expect-tests.ts b/expect/expect-tests.ts index 37ecefb566..3e08e0d747 100644 --- a/expect/expect-tests.ts +++ b/expect/expect-tests.ts @@ -1,12 +1,11 @@ /// -import {Expectation, Extension, Spy, createSpy, isSpy, assert, spyOn, extend, restoreSpies} - from 'expect'; +import {Expectation, Extension, Spy, createSpy, isSpy, assert, spyOn, extend, restoreSpies} from 'expect'; import * as expect from 'expect'; -describe('chaining assertions', function () { - it('should allow chaining for array-like applications', function () { +describe('chaining assertions', () => { + it('should allow chaining for array-like applications', () => { expect([ 1, 2, 'foo', 3 ]) .toExist() .toBeAn(Array) @@ -14,7 +13,7 @@ describe('chaining assertions', function () { .toExclude('bar'); }); - it('should allow chaining for number checking', function () { + it('should allow chaining for number checking', () => { expect(3.14) .toExist() .toBeLessThan(4.2) @@ -24,16 +23,16 @@ describe('chaining assertions', function () { }); }); -describe('createSpy', function () { - describe('when given a function', function () { - it('returns a spy function', function () { +describe('createSpy', () => { + describe('when given a function', () => { + it('returns a spy function', () => { const spy = createSpy(() => { return; }); expect(spy).toBeA(Function); }); }); }); -describe('A spy', function () { +describe('A spy', () => { let targetContext: any, targetArguments: any; const target = { method() { @@ -49,7 +48,7 @@ describe('A spy', function () { targetContext = targetArguments = null; }); - it('is a spy', function () { + it('is a spy', () => { expect(isSpy(spy)).toBe(true); }); @@ -59,15 +58,15 @@ describe('A spy', function () { expect(createSpy((a, b, c) => a * b * c).length).toBe(3); }); - it('has a destroy method', function () { + it('has a destroy method', () => { expect(spy.destroy).toBeA(Function); }); - it('has a restore method', function () { + it('has a restore method', () => { expect(spy.restore).toBeA(Function); }); - it('has a reset method', function () { + it('has a reset method', () => { expect(spy.reset).toBeA(Function); }); @@ -78,90 +77,90 @@ describe('A spy', function () { expect(spy.calls.length).toEqual(0); }); - it('knows how many times it has been called', function () { + it('knows how many times it has been called', () => { spy(); spy(); expect(spy.calls.length).toEqual(2); }); - it('knows the arguments it was called with', function () { + it('knows the arguments it was called with', () => { spy(1, 2, 3); expect(spy).toHaveBeenCalledWith(1, 2, 3); }); - describe('that calls some other function', function () { + describe('that calls some other function', () => { let otherContext: any, otherArguments: any; function otherFn() { otherContext = this; otherArguments = Array.prototype.slice.call(arguments, 0); - }; + } - beforeEach(function () { + beforeEach(() => { spy.andCall(otherFn); otherContext = otherArguments = null; }); - it('calls that function', function () { + it('calls that function', () => { spy(); expect(otherContext).toNotBe(null); }); - it('uses the correct context', function () { + it('uses the correct context', () => { const context = {}; spy.call(context); expect(otherContext).toBe(context); }); - it('passes the arguments through', function () { + it('passes the arguments through', () => { spy(1, 2, 3); expect(otherArguments).toEqual([ 1, 2, 3 ]); }); }); - describe('that calls through', function () { - beforeEach(function () { + describe('that calls through', () => { + beforeEach(() => { spy.andCallThrough(); }); - it('calls the original function', function () { + it('calls the original function', () => { spy(); expect(targetContext).toNotBe(null); }); - it('uses the correct context', function () { + it('uses the correct context', () => { const context = {}; spy.call(context); expect(targetContext).toBe(context); }); - it('passes the arguments through', function () { + it('passes the arguments through', () => { spy(1, 2, 3); expect(targetArguments).toEqual([ 1, 2, 3 ]); }); }); - describe('with a thrown value', function () { - beforeEach(function () { + describe('with a thrown value', () => { + beforeEach(() => { spy.andThrow('hello'); }); - it('throws the correct value', function () { + it('throws the correct value', () => { expect(spy).toThrow('hello'); }); }); - describe('with a return value', function () { - beforeEach(function () { + describe('with a return value', () => { + beforeEach(() => { spy.andReturn('hello'); }); - it('returns the correct value', function () { + it('returns the correct value', () => { expect(spy()).toEqual('hello'); }); }); }); -describe('expect.extend', function () { +describe('expect.extend', () => { const ColorAssertions: Extension = { toBeAColor() { assert( @@ -174,16 +173,16 @@ describe('expect.extend', function () { let assertSpy: Spy<{}>; - beforeEach(function () { + beforeEach(() => { extend(ColorAssertions); assertSpy = spyOn(expect, 'assert'); }); - afterEach(function () { + afterEach(() => { assertSpy.restore(); }); - it('works', function () { + it('works', () => { interface ColorExpectation extends Expectation { toBeAColor(): Expectation; } @@ -192,42 +191,42 @@ describe('expect.extend', function () { }); }); -describe('restoreSpies', function () { - describe('with one spy', function () { - const original = function () { return; }; +describe('restoreSpies', () => { + describe('with one spy', () => { + const original = () => { return; }; const target = { method: original }; - beforeEach(function () { + beforeEach(() => { spyOn(target, 'method'); }); - it('works with spyOn()', function () { + it('works with spyOn()', () => { expect(target.method).toNotEqual(original); restoreSpies(); expect(target.method).toEqual(original); }); - it('is idempotent', function () { + it('is idempotent', () => { expect(target.method).toNotEqual(original); restoreSpies(); restoreSpies(); expect(target.method).toEqual(original); }); - it('can work even on createSpy()', function () { + it('can work even on createSpy()', () => { createSpy(original); restoreSpies(); }); }); - describe('with multiple spies', function () { - const originals = [ function () { return; }, function () { return; } ]; + describe('with multiple spies', () => { + const originals = [ () => { return; }, () => { return; } ]; const targets = [ { method: originals[0] }, { method: originals[1] } ]; - it('still works', function () { + it('still works', () => { spyOn(targets[0], 'method'); spyOn(targets[1], 'method'); @@ -242,119 +241,119 @@ describe('restoreSpies', function () { }); }); -describe('A function that was spied on', function () { +describe('A function that was spied on', () => { const video = { play(...args: any[]) { return; } }; let spy: Spy<{}>; - beforeEach(function () { + beforeEach(() => { spy = spyOn(video, 'play'); video.play('some', 'args'); }); - it('tracks the number of calls', function () { + it('tracks the number of calls', () => { expect(spy.calls.length).toEqual(1); }); - it('tracks the context that was used', function () { + it('tracks the context that was used', () => { expect(spy.calls[0].context).toBe(video); }); - it('tracks the arguments that were used', function () { + it('tracks the arguments that were used', () => { expect(spy.calls[0].arguments).toEqual([ 'some', 'args' ]); }); - it('was called', function () { + it('was called', () => { expect(spy).toHaveBeenCalled(); }); - it('was called with the correct args', function () { + it('was called with the correct args', () => { expect(spy).toHaveBeenCalledWith('some', 'args'); }); - it('can be restored', function () { + it('can be restored', () => { expect(video.play).toEqual(spy); spy.restore(); expect(video.play).toNotEqual(spy); }); }); -describe('A function that was spied on but not called', function () { +describe('A function that was spied on but not called', () => { const video = { - play () { return; } + play() { return; } }; let spy: Spy<{}>; - beforeEach(function () { + beforeEach(() => { spy = spyOn(video, 'play'); }); - it('number of calls to be zero', function () { + it('number of calls to be zero', () => { expect(spy.calls.length).toEqual(0); }); - it('was not called', function () { + it('was not called', () => { expect(spy).toNotHaveBeenCalled(); }); }); -describe('toBeA', function () { - it('requires the value to be a function or string', function () { - expect(function () { +describe('toBeA', () => { + it('requires the value to be a function or string', () => { + expect(() => { expect('actual').toBeA(4); }).toThrow(/must be a function or a string/); }); - it('does not throw when the actual value is an instanceof the constructor', function () { - expect(function () { + it('does not throw when the actual value is an instanceof the constructor', () => { + expect(() => { expect(new Expectation('foo')).toBeA(Expectation); }).toNotThrow(); }); - it('throws when the actual value is not an instanceof the constructor', function () { - expect(function () { + it('throws when the actual value is not an instanceof the constructor', () => { + expect(() => { expect('actual').toBeA(Expectation); }).toThrow(/to be/); }); - it('does not throw when the expected value is the typeof the actual value', function () { - expect(function () { + it('does not throw when the expected value is the typeof the actual value', () => { + expect(() => { expect(4).toBeA('number'); expect(NaN).toBeA('number'); // hahaha }).toNotThrow(); }); - it('throws when the expected value is not the typeof the actual value', function () { - expect(function () { + it('throws when the expected value is not the typeof the actual value', () => { + expect(() => { expect('actual').toBeA('number'); }).toThrow(/to be/); }); - it('does not throw when the actual value is an array', function () { - expect(function () { + it('does not throw when the actual value is an array', () => { + expect(() => { expect([]).toBeAn('array'); }).toNotThrow(); }); - it('throws when the actual value is not an array', function () { - expect(function () { + it('throws when the actual value is not an array', () => { + expect(() => { expect('actual').toBeAn('array'); }).toThrow(/to be/); }); }); -describe('toBeGreaterThan', function () { - it('does not throw when the actual value is greater than the expected value', function () { - expect(function () { +describe('toBeGreaterThan', () => { + it('does not throw when the actual value is greater than the expected value', () => { + expect(() => { expect(3).toBeGreaterThan(2); }).toNotThrow(); }); - it('throws when the actual value is not greater than the expected value', function () { - expect(function () { + it('throws when the actual value is not greater than the expected value', () => { + expect(() => { expect(2).toBeGreaterThan(3); }).toThrow(/to be greater than/); }); @@ -380,15 +379,15 @@ describe('toBeGreaterThanOrEqualTo', () => { }); }); -describe('toBeLessThan', function () { - it('does not throw when the actual value is less than the expected value', function () { - expect(function () { +describe('toBeLessThan', () => { + it('does not throw when the actual value is less than the expected value', () => { + expect(() => { expect(2).toBeLessThan(3); }).toNotThrow(); }); - it('throws when the actual value is not less than the expected value', function () { - expect(function () { + it('throws when the actual value is not less than the expected value', () => { + expect(() => { expect(3).toBeLessThan(2); }).toThrow(/to be less than/); }); @@ -414,47 +413,47 @@ describe('toBeLessThanOrEqualTo', () => { }); }); -describe('toBeTruthy', function () { - it('does not throw on truthy actual values', function () { - expect(function () { +describe('toBeTruthy', () => { + it('does not throw on truthy actual values', () => { + expect(() => { expect(1).toBeTruthy(); expect({ hello: 'world' }).toBeTruthy(); expect([ 1, 2, 3 ]).toBeTruthy(); }).toNotThrow(); }); - it('throws on falsy actual values', function () { - expect(function () { + it('throws on falsy actual values', () => { + expect(() => { expect(0).toBeTruthy(); }).toThrow(); - expect(function () { + expect(() => { expect(null).toBeTruthy(); }).toThrow(); - expect(function () { + expect(() => { expect(undefined).toBeTruthy(); }).toThrow(); }); }); -describe('toBeFalsy', function () { - it('throws on truthy values', function () { - expect(function () { +describe('toBeFalsy', () => { + it('throws on truthy values', () => { + expect(() => { expect(42).toBeFalsy(); }).toThrow(); - expect(function () { + expect(() => { expect({ foo: 'bar' }).toBeFalsy(); }).toThrow(); - expect(function () { + expect(() => { expect([]).toBeFalsy(); }).toThrow(); }); - it('does not throw with falsy actual values', function () { - expect(function () { + it('does not throw with falsy actual values', () => { + expect(() => { expect(0).toBeFalsy(); expect(null).toBeFalsy(); expect(undefined).toBeFalsy(); @@ -462,20 +461,20 @@ describe('toBeFalsy', function () { }); }); -describe('toEqual', function () { - it('works', function () { - expect(function () { +describe('toEqual', () => { + it('works', () => { + expect(() => { expect('actual').toEqual('expected'); }).toThrow(/Expected 'actual' to equal 'expected'/); }); - it('works with objects that have the same keys in different order', function () { + it('works with objects that have the same keys in different order', () => { const a = { a: 'a', b: 'b', c: 'c' }; const b = { b: 'b', c: 'c', a: 'a' }; expect(a).toEqual(b); }); - it('shows diff', function () { + it('shows diff', () => { try { expect('actual').toEqual('expected'); } catch (err) { @@ -486,21 +485,21 @@ describe('toEqual', function () { }); }); -describe('toExclude', function () { - it('requires the actual value to be an array or string', function () { - expect(function () { +describe('toExclude', () => { + it('requires the actual value to be an array or string', () => { + expect(() => { expect(1).toExclude(2); }).toThrow(/must be an array or a string/); }); - it('does not throw when an array does not contain the expected value', function () { - expect(function () { + it('does not throw when an array does not contain the expected value', () => { + expect(() => { expect([ 1, 2, 3 ]).toExclude(4); }).toNotThrow(); }); - it('throws when an array contains the expected value', function () { - expect(function () { + it('throws when an array contains the expected value', () => { + expect(() => { expect([ 1, 2, 3 ]).toExclude(2); }).toThrow(/to exclude/); }); @@ -523,14 +522,14 @@ describe('toExclude', function () { }).toNotThrow(); }); - it('does not throw when an array does not contain the expected value', function () { - expect(function () { + it('does not throw when an array does not contain the expected value', () => { + expect(() => { expect('hello world').toExclude('goodbye'); }).toNotThrow(); }); - it('throws when a string contains the expected value', function () { - expect(function () { + it('throws when a string contains the expected value', () => { + expect(() => { expect('hello world').toExclude('hello'); }).toThrow(/to exclude/); }); @@ -592,47 +591,47 @@ describe('toExcludeKeys', () => { }); }); -describe('toExist', function () { - it('does not throw on truthy actual values', function () { - expect(function () { +describe('toExist', () => { + it('does not throw on truthy actual values', () => { + expect(() => { expect(1).toExist(); expect({ hello: 'world' }).toExist(); expect([ 1, 2, 3 ]).toExist(); }).toNotThrow(); }); - it('throws on falsy actual values', function () { - expect(function () { + it('throws on falsy actual values', () => { + expect(() => { expect(0).toExist(); }).toThrow(); - expect(function () { + expect(() => { expect(null).toExist(); }).toThrow(); - expect(function () { + expect(() => { expect(undefined).toExist(); }).toThrow(); }); }); -describe('toNotExist', function () { - it('throws on truthy values', function () { - expect(function () { +describe('toNotExist', () => { + it('throws on truthy values', () => { + expect(() => { expect(42).toNotExist(); }).toThrow(); - expect(function () { + expect(() => { expect({ foo: 'bar' }).toNotExist(); }).toThrow(); - expect(function () { + expect(() => { expect([]).toNotExist(); }).toThrow(); }); - it('does not throw with falsy actual values', function () { - expect(function () { + it('does not throw with falsy actual values', () => { + expect(() => { expect(0).toNotExist(); expect(null).toNotExist(); expect(undefined).toNotExist(); @@ -1037,11 +1036,11 @@ describe('toNotEqual', () => { expect(a).toNotEqual(b); }); - }; + } }); -describe('withArgs', function () { - const fn = function (arg1: any, arg2: any) { +describe('withArgs', () => { + const fn = (arg1: any, arg2: any) => { if (arg1 === 'first' && typeof arg2 === 'undefined') { throw new Error('first arg found'); } @@ -1050,20 +1049,20 @@ describe('withArgs', function () { } }; - it('invokes actual function with args', function () { - expect(function () { + it('invokes actual function with args', () => { + expect(() => { expect(fn).withArgs('first').toThrow(/first arg found/); }).toNotThrow(); }); - it('can be chained', function () { - expect(function () { + it('can be chained', () => { + expect(() => { expect(fn).withArgs('first').withArgs('second').toThrow(/both args found/); }).toNotThrow(); }); - it('throws when actual is not a function', function () { - expect(function () { + it('throws when actual is not a function', () => { + expect(() => { expect('not a function').withArgs('first'); }).toThrow(/must be a function/); }); diff --git a/express-jwt/index.d.ts b/express-jwt/index.d.ts index e721094edc..4b6883a258 100644 --- a/express-jwt/index.d.ts +++ b/express-jwt/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for express-jwt // Project: https://www.npmjs.org/package/express-jwt -// Definitions by: Wonshik Kim +// Definitions by: Wonshik Kim , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import express = require('express'); @@ -37,3 +37,10 @@ declare namespace jwt { unless?: typeof unless; } } +declare global { + namespace Express { + export interface Request { + user?: any + } + } +} diff --git a/express-mysql-session/express-mysql-session-tests.ts b/express-mysql-session/express-mysql-session-tests.ts new file mode 100644 index 0000000000..b69486dd8d --- /dev/null +++ b/express-mysql-session/express-mysql-session-tests.ts @@ -0,0 +1,13 @@ +import MySQLStore = require('express-mysql-session'); + +const options = { + host: 'localhost', + port: 3306, + user: 'root', + password: '', + database: 'session_test' +}; + +const sessionStore = new MySQLStore(options); + +sessionStore.close(); diff --git a/express-mysql-session/index.d.ts b/express-mysql-session/index.d.ts new file mode 100644 index 0000000000..0e86b9b077 --- /dev/null +++ b/express-mysql-session/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for express-mysql-session 1.2 +// Project: https://github.com/chill117/express-mysql-session#readme +// Definitions by: Akim95 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = MySQLStore; + +declare namespace MySQLStore { + interface Options { + host?: string; + port?: number; + user?: string; + password?: string; + database?: string; + checkExpirationInterval?: number; + expiration?: number; + createDatabaseTable?: boolean; + connectionLimit?: number; + schema?: Schema; + } + interface Schema { + tableName: string; + columnNames: ColumnNames; + } + interface ColumnNames { + session_id: string; + expires: string; + data: string; + } +} + +declare class MySQLStore { + + /** + * @param {MySQLStore.Options} options + * @param {any} connection? + * @param {(error:any)=>void} callback? + */ + constructor(options: MySQLStore.Options, connection?: any, callback?: (error: any) => void); + + /** + * @returns void + */ + setDefaultOptions(): void; + + /** + * @param {(error:any)=>void} callback? + * @returns void + */ + createDatabaseTable(callback?: (error: any) => void): void; + + /** + * @param {string} sessionId + * @param {(error:any,session:any)=>void} callback? + * @returns void + */ + get(sessionId: string, callback?: (error: any, session: any) => void): void; + + /** + * @param {string} sessionId + * @param {any} data + * @param {(error:any)=>void} callback? + * @returns void + */ + set(sessionId: string, data: any, callback?: (error: any) => void): void; + + /** + * @param {string} sessionId + * @param {any} data + * @param {(error:any)=>void} callback? + * @returns void + */ + touch(sessionId: string, data: any, callback?: (error: any) => void): void; + + /** + * @param {string} sessionId + * @param {(error:any)=>void} callback? + * @returns void + */ + destroy(sessionId: string, callback?: (error: any) => void): void; + + /** + * @param {(error:any,count:any)=>void} callback? + * @returns void + */ + length(callback?: (error: any, count: any) => void): void; + + /** + * @param {(error:any)=>void} callback? + * @returns void + */ + clear(callback?: (error: any) => void): void; + + /** + * @param {(error:any)=>void} callback? + * @returns void + */ + clearExpiredSessions(callback?: (error: any) => void): void; + + /** + * @param {number} interval + * @returns void + */ + setExpirationInterval(interval: number): void; + + /** + * @returns void + */ + clearExpirationInterval(): void; + + /** + * @param {()=>void} callback? + * @returns void + */ + close(callback?: () => void): void; + + /** + * @param {any} object + * @param {any} defaultValues + * @param {any} options? + * @returns void + */ + default(object: any, defaultValues: any, options?: any): void; + + /** + * @param {any} object + * @returns void + */ + clone(object: any): void; + + /** + * @param {any} value + * @returns void + */ + isObject(value: any): void; +} diff --git a/express-mysql-session/tsconfig.json b/express-mysql-session/tsconfig.json new file mode 100644 index 0000000000..f897d59bc8 --- /dev/null +++ b/express-mysql-session/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", + "express-mysql-session-tests.ts" + ] +} \ No newline at end of file diff --git a/express-mysql-session/tslint.json b/express-mysql-session/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/express-mysql-session/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/express-rate-limit/express-rate-limit-tests.ts b/express-rate-limit/express-rate-limit-tests.ts new file mode 100644 index 0000000000..761a6d23f8 --- /dev/null +++ b/express-rate-limit/express-rate-limit-tests.ts @@ -0,0 +1,25 @@ +import RateLimit = require("express-rate-limit"); + +var apiLimiter = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + delayMs: 0 // disabled +}); + +var createAccountLimiter = new RateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour window + delayAfter: 1, // begin slowing down responses after the first request + delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request + max: 5, // start blocking after 5 requests + message: "Too many accounts created from this IP, please try again after an hour" +}); + +class SomeStore implements RateLimit.Store { + incr(key: string, cb: RateLimit.StoreIncrementCallback) { } + resetAll() { } + resetKey(key: string) { }; +}; + +var limiterWithStore = new RateLimit({ + store: new SomeStore() +}); diff --git a/express-rate-limit/index.d.ts b/express-rate-limit/index.d.ts new file mode 100644 index 0000000000..38ef8f8b29 --- /dev/null +++ b/express-rate-limit/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for express-rate-limit 2.6 +// Project: https://github.com/nfriedly/express-rate-limit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import express = require("express"); + +declare namespace RateLimit { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + export interface Store { + incr: (key: string, cb: StoreIncrementCallback) => void; + resetAll: () => void; + resetKey: (key: string) => void; + } + + export interface Options { + delayAfter?: number; + delayMs?: number; + handlers?: () => any; + headers?: boolean; + keyGenerator?: () => string; + max?: number; + message?: string; + skip?: () => boolean; + statusCode?: number; + store?: Store; + windowMs?: number; + } +} + +interface RateLimitStatic { + new(options: RateLimit.Options): express.RequestHandler; +} + +declare var RateLimit: RateLimitStatic; +export = RateLimit; diff --git a/express-rate-limit/tsconfig.json b/express-rate-limit/tsconfig.json new file mode 100644 index 0000000000..ca3c32c3bb --- /dev/null +++ b/express-rate-limit/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", + "express-rate-limit-tests.ts" + ] +} diff --git a/express-rate-limit/tslint.json b/express-rate-limit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/express-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts index 62e522a348..63177ebde3 100644 --- a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts +++ b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts @@ -58,7 +58,10 @@ configuration = { configuration = { // ... plugins: [ - new optimize.CommonsChunkPlugin("commons", "commons.js"), + new optimize.CommonsChunkPlugin({ + name: "commons", + filename: "commons.js", + }), new ExtractTextPlugin("[name].css") ] }; diff --git a/extract-zip/extract-zip-tests.ts b/extract-zip/extract-zip-tests.ts index 33b3a714af..b4c35224e7 100644 --- a/extract-zip/extract-zip-tests.ts +++ b/extract-zip/extract-zip-tests.ts @@ -1,7 +1,7 @@ import * as extract from 'extract-zip'; -let str = 'str'; -let num = 0; +const str = 'str'; +const num = 0; let options: extract.Options = { dir: str, diff --git a/fabric/fabric-tests.ts b/fabric/fabric-tests.ts index d0b4ef197b..923b29d896 100644 --- a/fabric/fabric-tests.ts +++ b/fabric/fabric-tests.ts @@ -6,15 +6,15 @@ function sample1() { selection: false, }); - canvas.on('object:moving', function(e: fabric.IEvent) { + canvas.on('object:moving', (e: fabric.IEvent) => { e.target.opacity = 0.5; }); - canvas.on('object:modified', function(e: fabric.IEvent) { + canvas.on('object:modified', (e: fabric.IEvent) => { e.target.opacity = 1; }); for (var i = 0, len = 15; i < len; i++) { - fabric.Image.fromURL('../assets/ladybug.png', function(img) { + fabric.Image.fromURL('../assets/ladybug.png', img => { img.set({ left: fabric.util.getRandomInt(0, 600), top: fabric.util.getRandomInt(0, 500), @@ -36,11 +36,11 @@ function sample2() { var dot: fabric.Circle, i: number, t1: number, t2: number, - startTimer = function() { + startTimer = () => { t1 = new Date().getTime(); return t1; }, - stopTimer = function() { + stopTimer = () => { t2 = new Date().getTime(); return t2 - t1; }, @@ -89,16 +89,16 @@ function sample2() { function sample3() { - var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id) }; + var $: (id: string) => HTMLElement = (id: string) => document.getElementById(id); function applyFilter(index: number, filter: any) { - var obj: fabric.Image = canvas.getActiveObject(); + var obj: fabric.Image = canvas.getActiveObject(); obj.filters[index] = filter; obj.applyFilters(canvas.renderAll.bind(canvas)); } function applyFilterValue(index: number, prop: string, value: any) { - var obj: fabric.Image = canvas.getActiveObject(); + var obj: fabric.Image = canvas.getActiveObject(); if (obj.filters[index]) { obj.applyFilters(canvas.renderAll.bind(canvas)); } @@ -108,24 +108,24 @@ function sample3() { f = fabric.Image.filters; canvas.on({ - 'object:selected': function() { - fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = false; }) + 'object:selected': () => { + fabric.util.toArray(document.getElementsByTagName('input')).forEach(el => { el.disabled = false; }); var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2', 'brightness', 'noise', 'gradient-transparency', 'pixelate', 'blur', 'sharpen']; for (var i = 0; i < filters.length; i++) { - var checkBox = $(filters[i]); - var image = canvas.getActiveObject(); + var checkBox = $(filters[i]); + var image = canvas.getActiveObject(); checkBox.checked = !!image.filters[i]; } }, - 'selection:cleared': function() { - fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = true; }) + 'selection:cleared': () => { + fabric.util.toArray(document.getElementsByTagName('input')).forEach(el => { el.disabled = true; }); } }); - fabric.Image.fromURL('../assets/printio.png', function(img) { + fabric.Image.fromURL('../assets/printio.png', img => { var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9); canvas.add(oImg).renderAll(); canvas.setActiveObject(oImg); @@ -139,8 +139,8 @@ function sample3() { }; $('remove-white').onclick = function(this: HTMLInputElement) { applyFilter(2, this.checked && new f.RemoveWhite({ - threshold: parseInt(($('remove-white-threshold')).value), - distance: parseInt(($('remove-white-distance')).value) + threshold: parseInt(( $('remove-white-threshold')).value, 10), + distance: parseInt(( $('remove-white-distance')).value, 10) })); }; $('remove-white-threshold').onchange = function(this: HTMLInputElement) { @@ -157,7 +157,7 @@ function sample3() { }; $('brightness').onclick = function(this: HTMLInputElement) { applyFilter(5, this.checked && new f.Brightness({ - brightness: parseInt(($('brightness-value')).value, 10) + brightness: parseInt(( $('brightness-value')).value, 10) })); }; $('brightness-value').onchange = function(this: HTMLInputElement) { @@ -165,7 +165,7 @@ function sample3() { }; $('noise').onclick = function(this: HTMLInputElement) { applyFilter(6, this.checked && new f.Noise({ - noise: parseInt(($('noise-value')).value, 10) + noise: parseInt(( $('noise-value')).value, 10) })); }; $('noise-value').onchange = function(this: HTMLInputElement) { @@ -173,7 +173,7 @@ function sample3() { }; $('gradient-transparency').onclick = function(this: HTMLInputElement) { applyFilter(7, this.checked && new f.GradientTransparency({ - threshold: parseInt(($('gradient-transparency-value')).value, 10) + threshold: parseInt(( $('gradient-transparency-value')).value, 10) })); }; $('gradient-transparency-value').onchange = function(this: HTMLInputElement) { @@ -181,7 +181,7 @@ function sample3() { }; $('pixelate').onclick = function(this: HTMLInputElement) { applyFilter(8, this.checked && new f.Pixelate({ - blocksize: parseInt(($('pixelate-value')).value, 10) + blocksize: parseInt(( $('pixelate-value')).value, 10) })); }; $('pixelate-value').onchange = function(this: HTMLInputElement) { @@ -213,7 +213,7 @@ function sample3() { function sample4() { var canvas = new fabric.Canvas('c'); - var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id); }; + var $: (id: string) => HTMLElement = id => document.getElementById(id); var rect = new fabric.Rect({ width: 100, @@ -225,25 +225,25 @@ function sample4() { canvas.add(rect); - var angleControl = $('angle-control'); + var angleControl = $('angle-control'); angleControl.onchange = function(this: HTMLInputElement) { rect.setAngle(+this.value).setCoords(); canvas.renderAll(); }; - var scaleControl = $('scale-control'); + var scaleControl = $('scale-control'); scaleControl.onchange = function(this: HTMLInputElement) { rect.scale(+this.value).setCoords(); canvas.renderAll(); }; - var topControl = $('top-control'); + var topControl = $('top-control'); topControl.onchange = function(this: HTMLInputElement) { rect.setTop(+this.value).setCoords(); canvas.renderAll(); }; - var leftControl = $('left-control'); + var leftControl = $('left-control'); leftControl.onchange = function(this: HTMLInputElement) { rect.setLeft(+this.value).setCoords(); canvas.renderAll(); @@ -274,10 +274,10 @@ declare module "fabric" { } function sample5() { - var makeCircle = function(left: number, top: number, line1?: fabric.Line, line2?: fabric.Line, line3?: fabric.Line, line4?: fabric.Line): fabric.Circle { - var c = new fabric.Circle({ - left: left, - top: top, + var makeCircle = (left: number, top: number, line1?: fabric.Line, line2?: fabric.Line, line3?: fabric.Line, line4?: fabric.Line): fabric.Circle => { + var c = new fabric.Circle({ + left, + top, strokeWidth: 5, radius: 12, fill: '#fff', @@ -290,7 +290,7 @@ function sample5() { c.line4 = line4; c.hasControls = c.hasBorders = false; return c; - } + }; function makeLine(coords: number[]) { return new fabric.Line(coords, { @@ -321,8 +321,8 @@ function sample5() { makeCircle(line6.x2, line6.y2, line6) ); - canvas.on('object:moving', function(e) { - var p = e.target; + canvas.on('object:moving', e => { + var p = e.target; p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top }); p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top }); p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top }); @@ -333,7 +333,7 @@ function sample5() { function sample6() { var canvas = new fabric.Canvas('c'); - fabric.loadSVGFromURL('../assets/135.svg', function(objects) { + fabric.loadSVGFromURL('../assets/135.svg', objects => { var obj = objects[0].scale(0.25); canvas.centerObject(obj); canvas.add(obj); @@ -343,10 +343,10 @@ function sample6() { canvas.add(obj.clone(() => { }).set({ left: 100, top: 400, angle: -15 })); canvas.add(obj.clone(() => { }).set({ left: 480, top: 400, angle: 15 })); - canvas.on('mouse:move', function(options) { + canvas.on('mouse:move', options => { var p = canvas.getPointer(options.e); - canvas.forEachObject(function(obj) { + canvas.forEachObject(obj => { var distX = Math.abs(p.x - obj.left), distY = Math.abs(p.y - obj.top), dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2))); @@ -368,9 +368,9 @@ function sample7() { var canvas = new fabric.Canvas('c', { selection: false }); - setInterval(function() { - fabric.Image.fromURL('../assets/ladybug.png', function(obj) { - var img = obj; + setInterval(() => { + fabric.Image.fromURL('../assets/ladybug.png', obj => { + var img = obj; img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50); img.movingLeft = !!Math.round(Math.random()); canvas.add(img); @@ -379,14 +379,13 @@ function sample7() { var animate = (function animate() { - canvas.forEachObject(function(obj) { - var img = obj; + canvas.forEachObject(obj => { + var img = obj; img.left += (img.movingLeft ? -1 : 1); img.top += 1; if (img.left > 900 || img.top > 500) { canvas.remove(img); - } - else { + } else { img.setAngle(img.getAngle() + 2); } }); @@ -404,7 +403,7 @@ function sample8() { str = '0' + str; } return str; - }; + } var getRandomInt = fabric.util.getRandomInt; @@ -428,19 +427,18 @@ function sample8() { // canvas.controlsAboveOverlay = true; function updateComplexity() { - setTimeout(function() { - var element = document.getElementById('complexity').childNodes[1]; + setTimeout(() => { + var element = document.getElementById('complexity').childNodes[1]; element.innerHTML = ' ' + canvas.complexity(); }, 100); } - document.getElementById('commands').onclick = function(ev: any) { + document.getElementById('commands').onclick = (ev: any) => { var ev: any = ev || window.event; if (ev.preventDefault) { - ev.preventDefault() - } - else if (ev.returnValue) { + ev.preventDefault(); + } else if (ev.returnValue) { ev.returnValue = false; } @@ -455,14 +453,14 @@ function sample8() { top = fabric.util.getRandomInt(0 + offset, 500 - offset), angle = fabric.util.getRandomInt(-20, 40), width = fabric.util.getRandomInt(30, 50), - opacity = (function(min: number, max: number) { return Math.random() * (max - min) + min; })(0.5, 1); + opacity = ((min: number, max: number) => Math.random() * (max - min) + min)(0.5, 1); switch (className) { case 'rect': canvas.add(new fabric.Rect({ - left: left, - top: top, + left, + top, fill: '#' + getRandomColor(), width: 50, height: 50, @@ -472,8 +470,8 @@ function sample8() { case 'circle': canvas.add(new fabric.Circle({ - left: left, - top: top, + left, + top, fill: '#' + getRandomColor(), radius: 50, opacity: 0.8 @@ -482,8 +480,8 @@ function sample8() { case 'triangle': canvas.add(new fabric.Triangle({ - left: left, - top: top, + left, + top, fill: '#' + getRandomColor(), width: 50, height: 50, @@ -492,11 +490,11 @@ function sample8() { break; case 'image1': - fabric.Image.fromURL('../assets/pug.jpg', function(image) { + fabric.Image.fromURL('../assets/pug.jpg', image => { image.set({ - left: left, - top: top, - angle: angle, + left, + top, + angle, padding: 10, cornersize: 10 }); @@ -506,11 +504,11 @@ function sample8() { break; case 'image2': - fabric.Image.fromURL('../assets/logo.png', function(image) { + fabric.Image.fromURL('../assets/logo.png', image => { image.set({ - left: left, - top: top, - angle: angle, + left, + top, + angle, padding: 10, cornersize: 10 }); @@ -521,15 +519,16 @@ function sample8() { break; case 'shape': - var id: any = element.id, match: RegExpExecArray; - if (match = /\d+$/.exec(id)) { - fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function(objects, options) { + var id: any = element.id; + const match = /\d+$/.exec(id); + if (match) { + fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', (objects, options) => { var loadedObject = fabric.util.groupSVGElements(objects, options); loadedObject.set({ - left: left, - top: top, - angle: angle, + left, + top, + angle, padding: 10, cornersize: 10 }); @@ -552,46 +551,43 @@ function sample8() { updateComplexity(); }; - document.getElementById('execute').onclick = function() { - var code = (document.getElementById('canvas-console')).value; + document.getElementById('execute').onclick = () => { + var code = ( document.getElementById('canvas-console')).value; if (!(/^\s+$/).test(code)) { - eval(code); + eval(code); // tslint:disable-line:no-eval } }; - document.getElementById('rasterize').onclick = function() { + document.getElementById('rasterize').onclick = () => { if (!fabric.Canvas.supports('toDataURL')) { alert('This browser doesn\'t provide means to serialize canvas to an image'); - } - else { + } else { window.open(canvas.toDataURL('png')); } }; var removeSelectedEl = document.getElementById('remove-selected'); - removeSelectedEl.onclick = function() { + removeSelectedEl.onclick = () => { var activeObject = canvas.getActiveObject(), activeGroup = canvas.getActiveGroup(); if (activeObject) { canvas.remove(activeObject); - } - else if (activeGroup) { + } else if (activeGroup) { var objectsInGroup = activeGroup.getObjects(); canvas.discardActiveGroup(); - objectsInGroup.forEach(function(object) { + objectsInGroup.forEach(object => { canvas.remove(object); }); } }; - var supportsInputOfType = function(type: string) { - return function() { - var el = document.createElement('input'); + var supportsInputOfType = (type: string) => { + return () => { + var el = document.createElement('input'); try { el.type = type; - } - catch (err) { } + } catch (err) { } return el.type === type; }; }; @@ -600,14 +596,14 @@ function sample8() { supportsColorpicker = supportsInputOfType('color'); if (supportsSlider()) { - (function() { + (() => { var controls = document.getElementById('controls'); - var sliderLabel = document.createElement('label'); + var sliderLabel = document.createElement('label'); sliderLabel.htmlFor = 'opacity'; sliderLabel.innerHTML = 'Opacity: '; - var slider = document.createElement('input'); + var slider = document.createElement('input'); try { slider.type = 'range'; } catch (err) { } @@ -632,15 +628,15 @@ function sample8() { } if (supportsColorpicker()) { - (function() { + (() => { var controls = document.getElementById('controls'); - var label = document.createElement('label'); + var label = document.createElement('label'); label.htmlFor = 'color'; label.innerHTML = 'Color: '; label.style.marginLeft = '10px'; - var colorpicker = document.createElement('input'); + var colorpicker = document.createElement('input'); colorpicker.type = 'color'; colorpicker.id = 'color'; colorpicker.style.width = '40px'; @@ -663,7 +659,7 @@ function sample8() { } var lockHorizontallyEl = document.getElementById('lock-horizontally'); - lockHorizontallyEl.onclick = function() { + lockHorizontallyEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockMovementX = !activeObject.lockMovementX; @@ -674,7 +670,7 @@ function sample8() { }; var lockVerticallyEl = document.getElementById('lock-vertically'); - lockVerticallyEl.onclick = function() { + lockVerticallyEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockMovementY = !activeObject.lockMovementY; @@ -685,7 +681,7 @@ function sample8() { }; var lockScalingXEl = document.getElementById('lock-scaling-x'); - lockScalingXEl.onclick = function() { + lockScalingXEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockScalingX = !activeObject.lockScalingX; @@ -696,7 +692,7 @@ function sample8() { }; var lockScalingYEl = document.getElementById('lock-scaling-y'); - lockScalingYEl.onclick = function() { + lockScalingYEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockScalingY = !activeObject.lockScalingY; @@ -707,7 +703,7 @@ function sample8() { }; var lockRotationEl = document.getElementById('lock-rotation'); - lockRotationEl.onclick = function() { + lockRotationEl.onclick = () => { var activeObject: any = canvas.getActiveObject(); if (activeObject) { activeObject.lockRotation = !activeObject.lockRotation; @@ -738,7 +734,7 @@ function sample8() { activeObjectButtons.push(colorEl); } - for (var i = activeObjectButtons.length; i--;) { + for (var i = activeObjectButtons.length; i--; ) { activeObjectButtons[i]; } @@ -748,7 +744,7 @@ function sample8() { function onObjectSelected(e: fabric.IEvent) { var selectedObject = e.target; - for (var i = activeObjectButtons.length; i--;) { + for (var i = activeObjectButtons.length; i--; ) { activeObjectButtons[i]; } @@ -759,40 +755,39 @@ function sample8() { lockRotationEl.innerHTML = (selectedObject.lockRotation ? 'Unlock rotation' : 'Lock rotation'); } - canvas.on('selection:cleared', function(e) { - for (var i = activeObjectButtons.length; i--;) { + canvas.on('selection:cleared', e => { + for (var i = activeObjectButtons.length; i--; ) { activeObjectButtons[i]; } }); var drawingModeEl = document.getElementById('drawing-mode'), drawingOptionsEl = document.getElementById('drawing-mode-options'), - drawingColorEl = document.getElementById('drawing-color'), - drawingLineWidthEl = document.getElementById('drawing-line-width'); + drawingColorEl = document.getElementById('drawing-color'), + drawingLineWidthEl = document.getElementById('drawing-line-width'); - drawingModeEl.onclick = function() { + drawingModeEl.onclick = () => { var canvasWithDrawingMode: any = canvas; canvasWithDrawingMode.isDrawingMode = !canvasWithDrawingMode.isDrawingMode; if (canvasWithDrawingMode.isDrawingMode) { drawingModeEl.innerHTML = 'Cancel drawing mode'; drawingModeEl.className = 'is-drawing'; drawingOptionsEl.style.display = ''; - } - else { + } else { drawingModeEl.innerHTML = 'Enter drawing mode'; drawingModeEl.className = ''; drawingOptionsEl.style.display = 'none'; } }; - canvas.on('path:created', function() { + canvas.on('path:created', () => { updateComplexity(); }); - drawingColorEl.onchange = function() { + drawingColorEl.onchange = () => { canvas.freeDrawingColor = drawingColorEl.value; }; - drawingLineWidthEl.onchange = function() { + drawingLineWidthEl.onchange = () => { canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; // disallow 0, NaN, etc. }; @@ -803,7 +798,7 @@ function sample8() { var text = 'Lorem ipsum dolor sit amet,\nconsectetur adipisicing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.\n' + 'Ut enim ad minim veniam,\nquis nostrud exercitation ullamco\nlaboris nisi ut aliquip ex ea commodo consequat.'; - document.getElementById('add-text').onclick = function() { + document.getElementById('add-text').onclick = () => { var textSample = new fabric.Text(text.slice(0, getRandomInt(0, text.length)), { left: getRandomInt(350, 400), top: getRandomInt(350, 400), @@ -819,7 +814,7 @@ function sample8() { }; - document.onkeydown = function(e) { + document.onkeydown = e => { var obj = canvas.getActiveObject() || canvas.getActiveGroup(); if (obj && e.keyCode === 8) { // this is horrible. need to fix, so that unified interface can be used @@ -829,25 +824,24 @@ function sample8() { // groupObjects.forEach(function(obj) { // canvas.remove(obj); // }); - } - else { - //canvas.remove(obj); + } else { + // canvas.remove(obj); } canvas.renderAll(); // return false; } }; - setTimeout(function() { + setTimeout(() => { canvas.calcOffset(); }, 100); if (document.location.search.indexOf('guidelines') > -1) { - //initCenteringGuidelines(canvas); - //initAligningGuidelines(canvas); + // initCenteringGuidelines(canvas); + // initAligningGuidelines(canvas); } - gradientifyBtn.onclick = function() { + gradientifyBtn.onclick = () => { var obj = canvas.getActiveObject(); if (obj) { obj.setGradient("fill", { @@ -862,13 +856,13 @@ function sample8() { } }; - var textEl = document.getElementById('text'); + var textEl = document.getElementById('text'); if (textEl) { textEl.onfocus = function() { var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - this.value = (activeObject).text; + this.value = ( activeObject).text; } }; textEl.onkeyup = function(e) { @@ -876,9 +870,8 @@ function sample8() { if (activeObject) { if (!this.value) { canvas.discardActiveObject(); - } - else { - (activeObject).text = this.value; + } else { + ( activeObject).text = this.value; } canvas.renderAll(); } @@ -889,9 +882,9 @@ function sample8() { if (cmdUnderlineBtn) { activeObjectButtons.push(cmdUnderlineBtn); cmdUnderlineBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'underline' ? '' : 'underline'); + activeObject.textDecoration = (activeObject.textDecoration === 'underline' ? '' : 'underline'); this.className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } @@ -902,9 +895,9 @@ function sample8() { if (cmdLinethroughBtn) { activeObjectButtons.push(cmdLinethroughBtn); cmdLinethroughBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'line-through' ? '' : 'line-through'); + activeObject.textDecoration = (activeObject.textDecoration === 'line-through' ? '' : 'line-through'); this.className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } @@ -915,9 +908,9 @@ function sample8() { if (cmdOverlineBtn) { activeObjectButtons.push(cmdOverlineBtn); cmdOverlineBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'overline' ? '' : 'overline'); + activeObject.textDecoration = (activeObject.textDecoration === 'overline' ? '' : 'overline'); this.className = activeObject.textDecoration ? 'selected' : ''; canvas.renderAll(); } @@ -928,9 +921,9 @@ function sample8() { if (cmdBoldBtn) { activeObjectButtons.push(cmdBoldBtn); cmdBoldBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.fontWeight = (activeObject.fontWeight == 'bold' ? '' : 'bold'); + activeObject.fontWeight = (activeObject.fontWeight === 'bold' ? '' : 'bold'); this.className = activeObject.fontWeight ? 'selected' : ''; canvas.renderAll(); } @@ -941,9 +934,9 @@ function sample8() { if (cmdItalicBtn) { activeObjectButtons.push(cmdItalicBtn); cmdItalicBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { - activeObject.fontStyle = (activeObject.fontStyle == 'italic' ? '' : 'italic'); + activeObject.fontStyle = (activeObject.fontStyle === 'italic' ? '' : 'italic'); this.className = activeObject.fontStyle ? 'selected' : ''; canvas.renderAll(); } @@ -954,7 +947,7 @@ function sample8() { if (cmdShadowBtn) { activeObjectButtons.push(cmdShadowBtn); cmdShadowBtn.onclick = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.shadow = !activeObject.shadow ? 'rgba(0,0,0,0.2) 2px 2px 10px' : ''; this.className = activeObject.shadow ? 'selected' : ''; @@ -967,7 +960,7 @@ function sample8() { if (textAlignSwitch) { activeObjectButtons.push(textAlignSwitch); textAlignSwitch.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.textAlign = this.value.toLowerCase(); canvas.renderAll(); @@ -979,7 +972,7 @@ function sample8() { if (fontFamilySwitch) { activeObjectButtons.push(fontFamilySwitch); fontFamilySwitch.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.fontFamily = this.value; canvas.renderAll(); @@ -990,7 +983,7 @@ function sample8() { var bgColorField = document.getElementById('text-bg-color'); if (bgColorField) { bgColorField.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.backgroundColor = this.value; canvas.renderAll(); @@ -1001,7 +994,7 @@ function sample8() { var strokeColorField = document.getElementById('text-stroke-color'); if (strokeColorField) { strokeColorField.onchange = function(this: HTMLInputElement) { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.stroke = this.value; canvas.renderAll(); @@ -1010,10 +1003,10 @@ function sample8() { } if (supportsSlider) { - (function() { + (() => { var container = document.getElementById('text-controls'); - var slider = document.createElement('input'); - var label = document.createElement('label'); + var slider = document.createElement('input'); + var label = document.createElement('label'); label.innerHTML = 'Line height: '; try { slider.type = 'range'; } catch (err) { } slider.min = "0"; @@ -1024,22 +1017,22 @@ function sample8() { label.appendChild(slider); slider.title = "Line height"; slider.onchange = function() { - var activeObject = canvas.getActiveObject(); + var activeObject = canvas.getActiveObject(); if (activeObject && activeObject.type === 'text') { activeObject.lineHeight = +this.value; canvas.renderAll(); } }; - canvas.on('object:selected', function(e: fabric.IEvent) { - slider.value = String((e.target).lineHeight); + canvas.on('object:selected', (e: fabric.IEvent) => { + slider.value = String(( e.target).lineHeight); }); })(); } - document.getElementById('load-svg').onclick = function() { - var svg = (document.getElementById('svg-console')).value; - fabric.loadSVGFromString(svg, function(objects, options) { + document.getElementById('load-svg').onclick = () => { + var svg = ( document.getElementById('svg-console')).value; + fabric.loadSVGFromString(svg, (objects, options) => { var obj = fabric.util.groupSVGElements(objects, options); canvas.add(obj).centerObject(obj).renderAll(); obj.setCoords(); @@ -1049,6 +1042,6 @@ function sample8() { function sample9() { var canvas = new fabric.Canvas('c'); - canvas.setBackgroundImage('yolo.jpg', () => { "a" }, { opacity: 45 }); - canvas.setBackgroundImage('yolo.jpg', () => { "a" }); + canvas.setBackgroundImage('yolo.jpg', () => { "a"; }, { opacity: 45 }); + canvas.setBackgroundImage('yolo.jpg', () => { "a"; }); } diff --git a/fabric/tsconfig.json b/fabric/tsconfig.json index 13faaee670..ab7021e0c9 100644 --- a/fabric/tsconfig.json +++ b/fabric/tsconfig.json @@ -6,7 +6,7 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, + "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ diff --git a/fabric/tslint.json b/fabric/tslint.json index 9f552c56eb..525190cf34 100644 --- a/fabric/tslint.json +++ b/fabric/tslint.json @@ -7,4 +7,4 @@ "no-empty-interface": false, "unified-signatures": false } -} \ No newline at end of file +} diff --git a/falcor/index.d.ts b/falcor/index.d.ts index fe3af19544..1bf3c9ba23 100644 --- a/falcor/index.d.ts +++ b/falcor/index.d.ts @@ -35,7 +35,10 @@ export { ///////////////////////////////////////////////////// /** - * A DataSource is an interface which can be implemented to expose JSON Graph information to a Model. Every DataSource is associated with a single JSON Graph object. Models execute JSON Graph operations (get, set, and call) to retrieve values from the DataSource’s JSON Graph object. DataSources may retrieve JSON Graph information from anywhere, including device memory, a remote machine, or even a lazily-run computation. + * A DataSource is an interface which can be implemented to expose JSON Graph information to a Model. + * Every DataSource is associated with a single JSON Graph object. + * Models execute JSON Graph operations (get, set, and call) to retrieve values from the DataSource’s JSON Graph object. + * DataSources may retrieve JSON Graph information from anywhere, including device memory, a remote machine, or even a lazily-run computation. **/ export abstract class DataSource { @@ -83,12 +86,14 @@ type ModelOnChange = () => void; type ModelErrorSelector = (jsonGraphError: any) => any; /** - * This function is invoked every time a value in the Model cache is about to be replaced with a new value. If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented. + * This function is invoked every time a value in the Model cache is about to be replaced with a new value. + * If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented. **/ type ModelComparator = (existingValue: any, newValue: any) => boolean; /** - * A Model object is used to execute commands against a {@link JSONGraph} object. {@link Model}s can work with a local JSONGraph cache, or it can work with a remote {@link JSONGraph} object through a {@link DataSource}. + * A Model object is used to execute commands against a {@link JSONGraph} object + * {@link Model}s can work with a local JSONGraph cache, or it can work with a remote {@link JSONGraph} object through a {@link DataSource}. **/ export class Model { constructor(options?: ModelOptions); @@ -100,7 +105,9 @@ export class Model { get(...path: Array): ModelResponse>; /** - * Sets the value at one or more places in the JSONGraph model. The set method accepts one or more {@link PathValue}s, each of which is a combination of a location in the document and the value to place there. In addition to accepting {@link PathValue}s, the set method also returns the values after the set operation is complete. + * Sets the value at one or more places in the JSONGraph model. + * The set method accepts one or more {@link PathValue}s, each of which is a combination of a location in the document and the value to place there. + * In addition to accepting {@link PathValue}s, the set method also returns the values after the set operation is complete. **/ set(...args: PathValue[]): ModelResponse>; set(...args: PathValue[]): ModelResponse>; @@ -127,7 +134,9 @@ export class Model { invalidate(...path: PathSet[]): void; /** - * Returns a new {@link Model} bound to a location within the {@link JSONGraph}. The bound location is never a {@link Reference}: any {@link Reference}s encountered while resolving the bound {@link Path} are always replaced with the {@link Reference}s target value. For subsequent operations on the {@link Model}, all paths will be evaluated relative to the bound path. Deref allows you to: + * Returns a new {@link Model} bound to a location within the {@link JSONGraph}. + * The bound location is never a {@link Reference}: any {@link Reference}s encountered while resolving the bound {@link Path} are always replaced with the {@link Reference}s target value. + * For subsequent operations on the {@link Model}, all paths will be evaluated relative to the bound path. Deref allows you to: * - Expose only a fragment of the {@link JSONGraph} to components, rather than the entire graph * - Hide the location of a {@link JSONGraph} fragment from components * - Optimize for executing multiple operations and path looksup at/below the same location in the {@link JSONGraph} @@ -162,7 +171,8 @@ export class Model { getVersion(path?: Path): number; /** - * Returns a clone of the {@link Model} that enables batching. Within the configured time period, paths for get operations are collected and sent to the {@link DataSource} in a batch. Batching can be more efficient if the {@link DataSource} access the network, potentially reducing the number of HTTP requests to the server. + * Returns a clone of the {@link Model} that enables batching. Within the configured time period, paths for get operations are collected and sent to the {@link DataSource} in a batch. + * Batching can be more efficient if the {@link DataSource} access the network, potentially reducing the number of HTTP requests to the server. **/ batch(schedulerOrDelay?: number | Scheduler): Model; // FIXME what's a valid type for scheduler? @@ -172,7 +182,8 @@ export class Model { unbatch(): Model; /** - * Returns a clone of the {@link Model} that treats errors as values. Errors will be reported in the same callback used to report data. Errors will appear as objects in responses, rather than being sent to the {@link Observable~onErrorCallback} callback of the {@link ModelResponse}. + * Returns a clone of the {@link Model} that treats errors as values. Errors will be reported in the same callback used to report data. + * Errors will appear as objects in responses, rather than being sent to the {@link Observable~onErrorCallback} callback of the {@link ModelResponse}. **/ treatErrorsAsValues(): Model; @@ -182,12 +193,14 @@ export class Model { asDataSource(): DataSource; /** - * Returns a clone of the {@link Model} that boxes values returning the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the value inside it. This allows any metadata attached to the wrapper to be inspected. + * Returns a clone of the {@link Model} that boxes values returning the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the value inside it. + * This allows any metadata attached to the wrapper to be inspected. **/ boxValues(): Model; /** - * Returns a clone of the {@link Model} that unboxes values, returning the value inside of the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the wrapper itself. This is the default mode. + * Returns a clone of the {@link Model} that unboxes values, returning the value inside of the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the wrapper itself. + * This is the default mode. **/ unboxValues(): Model; @@ -227,12 +240,17 @@ interface Thenable { export class Observable{ /** - * The forEach method is a synonym for {@link Observable.prototype.subscribe} and triggers the execution of the Observable, causing the values within to be pushed to a callback. An Observable is like a pipe of water that is closed. When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object. + * The forEach method is a synonym for {@link Observable.prototype.subscribe} and triggers the execution of the Observable, causing the values within to be pushed to a callback. + * An Observable is like a pipe of water that is closed. + * When forEach is called, we open the valve and the values within are pushed at us. + * These values can be received using either callbacks or an {@link Observer} object. **/ forEach(onNext?: ObservableOnNextCallback, onError?: ObservableOnErrorCallback , onCompleted?: ObservableOnCompletedCallback ): Subscription; /** - * The subscribe method is a synonym for {@link Observable.prototype.forEach} and triggers the execution of the Observable, causing the values within to be pushed to a callback. An Observable is like a pipe of water that is closed. When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object. + * The subscribe method is a synonym for {@link Observable.prototype.forEach} and triggers the execution of the Observable, causing the values within to be pushed to a callback. + * An Observable is like a pipe of water that is closed. + * When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object. **/ subscribe(onNext?: ObservableOnNextCallback, onError?: ObservableOnErrorCallback , onCompleted?: ObservableOnCompletedCallback ): Subscription; } @@ -243,12 +261,14 @@ export class Observable{ type ObservableOnNextCallback = (value: T) => void; /** - * This callback accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream. When this callback is invoked, the {@link Observable} stream ends and no more values will be received by the {@link Observable~onNextCallback}. + * This callback accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream. + * When this callback is invoked, the {@link Observable} stream ends and no more values will be received by the {@link Observable~onNextCallback}. **/ type ObservableOnErrorCallback = (error: Error) => void; /** - * This callback is invoked when the {@link Observable} stream ends. When this callback is invoked the {@link Observable} stream has ended, and therefore the {@link Observable~onNextCallback} will not receive any more values. + * This callback is invoked when the {@link Observable} stream ends. + * When this callback is invoked the {@link Observable} stream has ended, and therefore the {@link Observable~onNextCallback} will not receive any more values. **/ type ObservableOnCompletedCallback = () => void; diff --git a/falcor/test/index.ts b/falcor/test/index.ts index 4fdba89022..2798b72645 100644 --- a/falcor/test/index.ts +++ b/falcor/test/index.ts @@ -1,6 +1,6 @@ import falcor = require('falcor'); -let dataSource: falcor.DataSource; +declare const dataSource: falcor.DataSource; dataSource.get([['someParam']]).subscribe(jsonGraphEnvelope => { console.log(jsonGraphEnvelope.jsonGraph); }); @@ -84,7 +84,7 @@ model.invalidate(['items', 0, 'name'], ['items', 1, 'name']); model.invalidate(['items', {from: 0, to: 1}, 'name']); model.get('items[0].["name", "id"]').then(res => { - const derefedModel = model.deref(res.json.items[0]) + const derefedModel = model.deref(res.json.items[0]); derefedModel.get('name', 'id'); }); diff --git a/falcor/tslint.json b/falcor/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/falcor/tslint.json +++ b/falcor/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/fetch-mock/fetch-mock-tests.ts b/fetch-mock/fetch-mock-tests.ts index f16aab11c9..d3ea2c374c 100644 --- a/fetch-mock/fetch-mock-tests.ts +++ b/fetch-mock/fetch-mock-tests.ts @@ -24,14 +24,14 @@ fetchMock.calls().unmatched[0][0].toUpperCase(); fetchMock.calls("http://test.com")[0][0].toUpperCase(); (fetchMock.calls("http://test.com")[0][1] as RequestInit).body; -let doneStatus: boolean = fetchMock.done(); -let doneStatusArguments: boolean = fetchMock.done("http://test.com"); +const doneStatus: boolean = fetchMock.done(); +const doneStatusArguments: boolean = fetchMock.done("http://test.com"); -let calledStatus: boolean = fetchMock.called(); -let calledStatusArguments = fetchMock.called("http://test.com"); +const calledStatus: boolean = fetchMock.called(); +const calledStatusArguments = fetchMock.called("http://test.com"); (fetchMock.lastCall()[1] as RequestInit).body; -let lastUrl: string = fetchMock.lastUrl(); +const lastUrl: string = fetchMock.lastUrl(); fetchMock.lastOptions(); fetchMock.get("http://test.com", 200); diff --git a/fine-uploader/index.d.ts b/fine-uploader/index.d.ts index 75184f1baf..dab4e720ea 100644 --- a/fine-uploader/index.d.ts +++ b/fine-uploader/index.d.ts @@ -76,6 +76,7 @@ declare namespace qq { onLeave?: string; // default: The files are being uploaded, if you leave now the upload will be canceled. retryFailTooManyItemsError?: string; // default: Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}. typeError?: string; // default: {file} has an invalid extension. Valid extension(s): {extensions}. + // tslint:disable-next-line:max-line-length unsupportedBrowserIos8Safari?: string; // default: Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues. } @@ -115,7 +116,13 @@ declare namespace qq { } interface ScalingOptions { - customResizer?: (blob: File | Blob, height: number, image: HTMLImageElement, sourceCanvas: HTMLCanvasElement, targetCanvas: HTMLCanvasElement, width: number) => Promise | undefined; // default: undefined + customResizer?: ( + blob: File | Blob, + height: number, + image: HTMLImageElement, + sourceCanvas: HTMLCanvasElement, + targetCanvas: HTMLCanvasElement, + width: number) => Promise | undefined; // default: undefined defaultQuality?: number; // default: 80 defaultType?: string | null; // default: null failureText?: string; // default: Failed to scale @@ -127,7 +134,9 @@ declare namespace qq { /** * From Documentation: - * An array containing size objects that describe scaled versions of each submitted image that should be generated and uploaded. A size object should usually contain a name String property (which will be appended to the file name of the scaled file), and must always contain a maxSize integer property. A type MIME string property is optional. + * An array containing size objects that describe scaled versions of each submitted image that should be generated and uploaded. + * A size object should usually contain a name String property (which will be appended to the file name of the scaled file), and must always contain a maxSize integer property. + * A type MIME string property is optional. */ interface Size { name: string; @@ -203,7 +212,8 @@ declare namespace qq { onTotalProgress?: (totalUploadedBytes: number, totalBytes: number) => void; onUpload?: (id: number, name: string) => void; onUploadChunk?: (id: number, name: string, chunkData: ChunkData) => void; - onUploadChunkSuccess?: (id: number, chunkData: ChunkData, responseJSON: T, xhr: XMLHttpRequest) => void; // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript + // ignore xhr: XDomainRequest as it is not compatible for all versions of TypeScript + onUploadChunkSuccess?: (id: number, chunkData: ChunkData, responseJSON: T, xhr: XMLHttpRequest) => void; onValidate?: (data: ValidateMetadata, buttonContainer: HTMLElement) => void; onValidateBatch?: (fileOrBlobDataArray: ValidateMetadata[], buttomContainer: HTMLElement) => void; } diff --git a/fine-uploader/test/blobs.ts b/fine-uploader/test/blobs.ts index a8f3ab3370..99e5355460 100644 --- a/fine-uploader/test/blobs.ts +++ b/fine-uploader/test/blobs.ts @@ -1,11 +1,9 @@ -/// - function testBlob() { - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { blobs: { defaultName: "hi.png" } }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/callbacks.ts b/fine-uploader/test/callbacks.ts index 273f792dd9..eba85ad2a0 100644 --- a/fine-uploader/test/callbacks.ts +++ b/fine-uploader/test/callbacks.ts @@ -1,16 +1,14 @@ -/// - class CallbacksTest { constructor(private opts: qq.CallbackOptions) { } testCallbacks() { - let opts = this.opts; + const opts = this.opts; - type CustomType = { + interface CustomType { myTypeOfClass: string; - }; + } opts.onAutoRetry = (id, name, attemptNumber) => {}; diff --git a/fine-uploader/test/camera.ts b/fine-uploader/test/camera.ts index 0186080032..b42a080778 100644 --- a/fine-uploader/test/camera.ts +++ b/fine-uploader/test/camera.ts @@ -1,12 +1,10 @@ -/// - function cameraTest() { const cameraButton = new HTMLButtonElement(); const cameraOptions: qq.CameraOptions = { button: cameraButton, ios: false - } + }; const config: qq.BasicOptions = { camera: cameraOptions diff --git a/fine-uploader/test/chunking.ts b/fine-uploader/test/chunking.ts index 4c914f029a..386dd67738 100644 --- a/fine-uploader/test/chunking.ts +++ b/fine-uploader/test/chunking.ts @@ -1,5 +1,3 @@ -/// - function chunkingTest() { const chunkingOptions: qq.ChunkingOptions = { diff --git a/fine-uploader/test/core.ts b/fine-uploader/test/core.ts index a91a5b157d..dbc06e95d6 100644 --- a/fine-uploader/test/core.ts +++ b/fine-uploader/test/core.ts @@ -1,11 +1,9 @@ -/// - function testCore() { - let button: HTMLElement = new HTMLButtonElement() + const button: HTMLElement = new HTMLButtonElement(); - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { autoUpload: true, - button: button, + button, debug: true, disableCancelForFormUploads: true, formatFileName: (rawFileName: string) => { @@ -15,5 +13,5 @@ function testCore() { multiple: true }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/cors.ts b/fine-uploader/test/cors.ts index d0abddff37..771b210208 100644 --- a/fine-uploader/test/cors.ts +++ b/fine-uploader/test/cors.ts @@ -1,11 +1,9 @@ -/// - function corsTest() { const corsOptions: qq.CorsOptions = { allowXdr: true, expected: true, sendCredentials: true - } + }; const config: qq.BasicOptions = { cors: corsOptions diff --git a/fine-uploader/test/deleteFile.ts b/fine-uploader/test/deleteFile.ts index 7372f1135f..49c3e68890 100644 --- a/fine-uploader/test/deleteFile.ts +++ b/fine-uploader/test/deleteFile.ts @@ -1,5 +1,3 @@ -/// - function deleteFileTest() { interface CustomHeader { myOption: string; @@ -9,7 +7,7 @@ function deleteFileTest() { myParam: string; } - let deleteFileOptions: qq.DeleteFileOptions = { + const deleteFileOptions: qq.DeleteFileOptions = { customHeader: { myOption: "ewwww" }, @@ -22,9 +20,9 @@ function deleteFileTest() { }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { deleteFile: deleteFileOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/extraButtons.ts b/fine-uploader/test/extraButtons.ts index abc2194c30..eef709bea8 100644 --- a/fine-uploader/test/extraButtons.ts +++ b/fine-uploader/test/extraButtons.ts @@ -1,14 +1,12 @@ -/// - function extraButtons() { - type Validation = { - myValue: string - }; + interface Validation { + myValue: string; + } - let element: HTMLElement = new HTMLElement(); + const element: HTMLElement = new HTMLElement(); - let extraButtonOptions: qq.ExtraButtonsOptions = { - element: element, + const extraButtonOptions: qq.ExtraButtonsOptions = { + element, fileInputTitle: "inputTitle", folders: true, multiple: false, @@ -17,9 +15,9 @@ function extraButtons() { } }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { extraButtons: extraButtonOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/form.ts b/fine-uploader/test/form.ts index d280de7a03..ccc08b69a1 100644 --- a/fine-uploader/test/form.ts +++ b/fine-uploader/test/form.ts @@ -1,15 +1,13 @@ -/// - function formTest() { - let formOptions: qq.FormOptions = { + const formOptions: qq.FormOptions = { element: "qq-form", autoUpload: true, interceptSubmit: true }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { form: formOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/message.ts b/fine-uploader/test/message.ts index fa3d11adb6..726584bf7b 100644 --- a/fine-uploader/test/message.ts +++ b/fine-uploader/test/message.ts @@ -1,7 +1,5 @@ -/// - function messageTest() { - let messageOptions: qq.MessagesOptions = { + const messageOptions: qq.MessagesOptions = { emptyError: "emptyError", maxHeightImageError: "maxHeightImageError", maxWidthImageError: "error occurred", @@ -15,9 +13,9 @@ function messageTest() { unsupportedBrowserIos8Safari: "error occurred" }; - let config: qq.BasicOptions = { + const config: qq.BasicOptions = { messages: messageOptions }; - let uploader = new qq.FineUploaderBasic(config); + const uploader = new qq.FineUploaderBasic(config); } diff --git a/fine-uploader/test/method.ts b/fine-uploader/test/method.ts index 27e5144aa0..1adb13db81 100644 --- a/fine-uploader/test/method.ts +++ b/fine-uploader/test/method.ts @@ -1,13 +1,11 @@ -/// - class TestMethods { constructor(private uploader: qq.FineUploaderBasic) { } testAddFiles() { - type ParamType = { + interface ParamType { field: string; - }; + } const params: ParamType = { field: 'hiiiii' @@ -21,9 +19,9 @@ class TestMethods { } testAddInitialFiles() { - type InitialFiles = { + interface InitialFiles { myField: number; - }; + } const initialFiles: InitialFiles[] = [{ myField: 1324 @@ -43,22 +41,22 @@ class TestMethods { return new Blob(); }); } - ) + ); } testGetUploads() { - type ResponseType = { + interface ResponseType { hi: string; } - let response: ResponseType | ResponseType[] = this.uploader.getUploads({ + const response: ResponseType | ResponseType[] = this.uploader.getUploads({ status: "proggresssssssesees" }); } testSetCustomHeaders() { - type CustomHeader = { - customField: number - }; + interface CustomHeader { + customField: number; + } this.uploader.setCustomHeaders({ customField: 1234 @@ -66,9 +64,9 @@ class TestMethods { } testSetDeleteCustomHeaders() { - type CustomHeader = { - customField: number - }; + interface CustomHeader { + customField: number; + } this.uploader.setDeleteFileCustomHeaders({ customField: 1234 @@ -76,7 +74,7 @@ class TestMethods { } testSetDeleteFileParams() { - type CustomParams = { + interface CustomParams { paramField: boolean; } this.uploader.setDeleteFileParams({ @@ -85,9 +83,9 @@ class TestMethods { } testSetParams() { - type CustomParams = { + interface CustomParams { customParams: number; - }; + } this.uploader.setParams({ customParams: 1234 @@ -100,8 +98,8 @@ class TestMethods { this.uploader.clearStoredFiles(); const shouldContinue: boolean = this.uploader.continueUpload(1234); this.uploader.deleteFile(1234); - let elem: HTMLElement = this.uploader.getButton(1234); - let fileOrBlob: File | Blob = this.uploader.getFile(1234); + const elem: HTMLElement = this.uploader.getButton(1234); + const fileOrBlob: File | Blob = this.uploader.getFile(1234); let num: number = this.uploader.getInProgress(); let s: string = this.uploader.getName(1234); num = this.uploader.getParentId(1234); @@ -110,7 +108,7 @@ class TestMethods { num = this.uploader.getSize(1234); s = this.uploader.getUuid(1234); this.uploader.log("why am i doing this?", "info"); - let b: boolean = this.uploader.pauseUpload(1234); + const b: boolean = this.uploader.pauseUpload(1234); this.uploader.reset(); this.uploader.retry(1234); const blobPromise: Promise = this.uploader.scaleImage(1234, { @@ -135,7 +133,7 @@ class TestMethods { uiTests() { this.uploader.addExtraDropzone(new HTMLElement()); let elem: HTMLElement = this.uploader.getDropTarget(1234); - let n: number = this.uploader.getId(elem); + const n: number = this.uploader.getId(elem); elem = this.uploader.getItemByFileId(n); this.uploader.removeExtraDropzone(elem); } diff --git a/fine-uploader/test/paste.ts b/fine-uploader/test/paste.ts index 5122238c75..9b3c7d9007 100644 --- a/fine-uploader/test/paste.ts +++ b/fine-uploader/test/paste.ts @@ -1,12 +1,10 @@ -/// - function pasteTest() { const targetElement: HTMLElement = new HTMLElement(); const pasteOptions: qq.PasteOptions = { defaultName: "pasted_image", - targetElement: targetElement - } + targetElement + }; const config: qq.BasicOptions = { paste: pasteOptions diff --git a/fine-uploader/test/request.ts b/fine-uploader/test/request.ts index a93ee6edb2..54b29c9be9 100644 --- a/fine-uploader/test/request.ts +++ b/fine-uploader/test/request.ts @@ -1,13 +1,11 @@ -/// - function requestTest() { - type CustomHeader = { + interface CustomHeader { customHeader: string; - }; + } - type CustomParam = { + interface CustomParam { customParam: boolean; - }; + } const requestOptions: qq.RequestOptions = { customHeaders: { diff --git a/fine-uploader/test/resume.ts b/fine-uploader/test/resume.ts index 2b4d475bc0..dc588d19f5 100644 --- a/fine-uploader/test/resume.ts +++ b/fine-uploader/test/resume.ts @@ -1,5 +1,3 @@ -/// - function resumeTest() { const resumeOptions: qq.ResumeOptions = { recordsExpireIn: 10, diff --git a/fine-uploader/test/retry.ts b/fine-uploader/test/retry.ts index 6b94b93002..85c9f71af3 100644 --- a/fine-uploader/test/retry.ts +++ b/fine-uploader/test/retry.ts @@ -1,5 +1,3 @@ -/// - function retryTest() { const retryOptions: qq.RetryOptions = { diff --git a/fine-uploader/test/scaling.ts b/fine-uploader/test/scaling.ts index e57089d103..5e8ff3dc51 100644 --- a/fine-uploader/test/scaling.ts +++ b/fine-uploader/test/scaling.ts @@ -1,5 +1,3 @@ -/// - function scalingTest() { const scalingOptions: qq.ScalingOptions = { customResizer: (blob, height, image, sourceCanvas, targetCanvas, width) => { diff --git a/fine-uploader/test/session.ts b/fine-uploader/test/session.ts index 9728c657b5..7d8d6069b9 100644 --- a/fine-uploader/test/session.ts +++ b/fine-uploader/test/session.ts @@ -1,13 +1,11 @@ -/// - function sessionTest() { - type CustomHeader = { + interface CustomHeader { customHeader: string; - }; + } - type CustomParam = { + interface CustomParam { customParam: boolean; - }; + } const sessionOptions: qq.SessionOptions = { customHeaders: { diff --git a/fine-uploader/test/text.ts b/fine-uploader/test/text.ts index 4b52a96570..e83ddb4bcf 100644 --- a/fine-uploader/test/text.ts +++ b/fine-uploader/test/text.ts @@ -1,5 +1,3 @@ -/// - function textTest() { const textOptions: qq.TextOptions = { defaultResponseError: "you have failed me for the last time", diff --git a/fine-uploader/test/validation.ts b/fine-uploader/test/validation.ts index b6400d44b8..60324157f9 100644 --- a/fine-uploader/test/validation.ts +++ b/fine-uploader/test/validation.ts @@ -1,5 +1,3 @@ -/// - function validationTest() { const validationOptions: qq.ValidationOptions = { diff --git a/fine-uploader/test/workarounds.ts b/fine-uploader/test/workarounds.ts index 2acfac455b..42fa5ceee7 100644 --- a/fine-uploader/test/workarounds.ts +++ b/fine-uploader/test/workarounds.ts @@ -1,5 +1,3 @@ -/// - function workaroundsTest() { const workaroundOptions: qq.WorkaroundOptions = { iosEmptyVideos: false, diff --git a/fixed-data-table/index.d.ts b/fixed-data-table/index.d.ts index cb5809bf5a..a131501348 100644 --- a/fixed-data-table/index.d.ts +++ b/fixed-data-table/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/facebook/fixed-data-table // Definitions by: Petar Paar , Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/flux/index.d.ts b/flux/index.d.ts index 4b9c261040..54fecd3a4e 100644 --- a/flux/index.d.ts +++ b/flux/index.d.ts @@ -2,6 +2,7 @@ // Project: http://facebook.github.io/flux/ // Definitions by: Steve Baker , Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// diff --git a/fluxxor/index.d.ts b/fluxxor/index.d.ts index 4c8f773b1d..64c917cdf5 100644 --- a/fluxxor/index.d.ts +++ b/fluxxor/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/BinaryMuse/fluxxor // Definitions by: Yuichi Murata // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// diff --git a/forever-monitor/forever-monitor-tests.ts b/forever-monitor/forever-monitor-tests.ts new file mode 100644 index 0000000000..bc3c9a29f9 --- /dev/null +++ b/forever-monitor/forever-monitor-tests.ts @@ -0,0 +1,23 @@ +// Test from https://github.com/foreverjs/forever-monitor + +import * as forever from "forever-monitor"; +forever.start('script') + .on("start", () => console.log("started")); + +forever.kill(10, true); + +const child = new (forever.Monitor)('your-filename.js', { + max: 3, + silent: true, + args: [] +}); + +child.on('exit', () => { + console.log('your-filename.js has exited after 3 restarts'); +}); + +child.start() + .on("start", () => console.log("started")) + .restart() + .stop() + .on("exit", () => console.log("STOPPED")); diff --git a/forever-monitor/index.d.ts b/forever-monitor/index.d.ts new file mode 100644 index 0000000000..22fa4b0c61 --- /dev/null +++ b/forever-monitor/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for forever-monitor 1.7 +// Project: https://github.com/nodejitsu/forever-monitor#readme +// Definitions by: Shun Takahashi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +export interface SpawnWith { + customFds: number[]; + setsid: boolean; + uid: number; + gid: number; +} + +export interface Options { + silent?: boolean; + uid?: string; + pidFile?: string; + max?: number; + killTree?: boolean; + minUptime?: number; + spinSleepTime?: number; + command?: string; + args?: string[]; + sourceDir?: string; + watch?: boolean; + watchIgnoreDotFiles?: boolean; + watchIgnorePatters?: string[]; + watchDirectory?: string; + spawnWith?: SpawnWith; + env?: { [envKey: string]: string; }; + cwd?: string; + logFile?: string; + outFile?: string; + errFile?: string; + parser?: (command: string, args: string[]) => { command: string, args: string[] }; +} + +export function start(script: string, options?: Options): Monitor; +export function kill(pid: number, killTree?: boolean, signal?: string, callback?: () => any): void; +export function checkProcess(pid: number): boolean; +export const version: string; + +export class Monitor extends NodeJS.EventEmitter { + + /** + * @param script - Location of the target script to run. + * @param [options] - Configuration for this instance. + */ + constructor(script: string, options?: Options); + + /** + * @description Start the process that this instance is configured for + * @param [restart] - Value indicating whether this is a restart. + */ + start(restart?: boolean): this; + + /** + * @description Tries to spawn the target Forever child process. + */ + trySpawn(): boolean; + + /** + * @description Restarts the target script associated with this instance. + */ + restart(): this; + + /** + * @description Stops the target script associated with this instance. Prevents it from auto-respawning + */ + stop(): this; + + /** + * @description Kills the ChildProcess object associated with this instance + * @param [forceStop] - Value indicating whether short circuit forever auto-restart + */ + kill(forceStop?: boolean): this; + + /** + * @description Sends a message to a forked ChildProcess object associated with this instance + */ + send(msg?: any): this; + + /** + * respond with JSON for this instance + */ + toString(): string; + + /** + * @param command - Command string to parse + * @param args - Additional default arguments + */ + parseCommand(command: string, args?: string[]): (false | { command: string, args?: string[]}); +} diff --git a/forever-monitor/tsconfig.json b/forever-monitor/tsconfig.json new file mode 100644 index 0000000000..e0d7d1d5ee --- /dev/null +++ b/forever-monitor/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", + "forever-monitor-tests.ts" + ] +} \ No newline at end of file diff --git a/forever-monitor/tslint.json b/forever-monitor/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/forever-monitor/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/format-unicorn/tslint.json b/format-unicorn/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/format-unicorn/tslint.json +++ b/format-unicorn/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/fs-promise/fs-promise-tests.ts b/fs-promise/fs-promise-tests.ts index a90ae03804..43decbd256 100644 --- a/fs-promise/fs-promise-tests.ts +++ b/fs-promise/fs-promise-tests.ts @@ -34,8 +34,8 @@ async function test() { await fs.move(src, dst); await fs.outputFile(path, "test"); await fs.outputFile(path, "test", writeOptions); - await fs.outputFile(path, new Buffer([1,2])); - await fs.outputFile(path, new Buffer([1,2]), writeOptions); + await fs.outputFile(path, new Buffer([1, 2])); + await fs.outputFile(path, new Buffer([1, 2]), writeOptions); await fs.outputJson(path, data); await fs.outputJson(path, data, writeJsonOptions); await fs.outputJSON(path, data, writeJsonOptions); @@ -43,7 +43,7 @@ async function test() { json = await fs.readJson(path, readJsonOptions); json = await fs.readJSON(path, readJsonOptions); await fs.remove(path); - let dirs: string[] = await fs.walk(dir); + const dirs: string[] = await fs.walk(dir); await fs.writeJson(path, data); await fs.writeJson(path, data, writeJsonOptions); await fs.writeJSON(path, data, writeJsonOptions); diff --git a/fullcalendar/fullcalendar-tests.ts b/fullcalendar/fullcalendar-tests.ts index 0303dc7f75..7640c85db6 100644 --- a/fullcalendar/fullcalendar-tests.ts +++ b/fullcalendar/fullcalendar-tests.ts @@ -13,7 +13,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function () { + dayClick() { alert('a day has been clicked!'); } }); @@ -68,13 +68,13 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar('option', 'aspectRatio', 1.8); $('#calendar').fullCalendar({ - viewRender: function (view) { + viewRender(view) { alert('The new title of the view is ' + view.title); } }); $('#calendar').fullCalendar({ - windowResize: function (view) { + windowResize(view) { alert('The calendar has adjusted to a window resize'); } }); @@ -88,7 +88,7 @@ $('#calendar').fullCalendar({ var view = $('#calendar').fullCalendar('getView'); alert("The view's title is " + view.title); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -152,7 +152,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -217,7 +217,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -271,7 +271,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -336,7 +336,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -390,21 +390,21 @@ $(document).ready(function () { }); -$('#my-prev-button').click(function () { +$('#my-prev-button').click(() => { $('#calendar').fullCalendar('prev'); }); -$('#my-next-button').click(function () { +$('#my-next-button').click(() => { $('#calendar').fullCalendar('next'); }); -$('#my-today-button').click(function () { +$('#my-today-button').click(() => { $('#calendar').fullCalendar('today'); }); $('#calendar').fullCalendar('gotoDate', 1, 0, 1); -$('#my-button').click(function () { +$('#my-button').click(() => { var d = $('#calendar').fullCalendar('getDate'); alert("The current date of the calendar is " + d); }); @@ -429,7 +429,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function (date, allDay, jsEvent, view) { + dayClick(date, allDay, jsEvent, view) { if (allDay) { alert('Clicked on the entire day: ' + date); @@ -448,7 +448,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (calEvent, jsEvent, view) { + eventClick(calEvent, jsEvent, view) { alert('Event: ' + calEvent.title); alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); @@ -469,7 +469,7 @@ $('#calendar').fullCalendar({ } // other events here ], - eventClick: function (event) { + eventClick(event) { if (event.url) { window.open(event.url); return false; @@ -489,7 +489,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error() { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -511,7 +511,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error() { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -601,7 +601,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - events: function (start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { + events(start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { $.ajax({ url: 'myxmlfeed.php', dataType: 'xml', @@ -610,9 +610,9 @@ $('#calendar').fullCalendar({ start: Math.round(start.toDate().getTime() / 1000), end: Math.round(end.toDate().getTime() / 1000) }, - success: function (doc) { + success(doc) { var events: any[] = []; - $(doc).find('event').each(function () { + $(doc).find('event').each(() => { events.push({ title: $(this).attr('title'), start: $(this).attr('start') // will be parsed @@ -630,7 +630,7 @@ $('#calendar').fullCalendar({ // your event source { - events: function (start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { + events(start: moment.Moment, end: moment.Moment, timezone: string | boolean, callback: (events: FullCalendar.EventObject[]) => void) { // ... }, color: 'yellow', // an option! @@ -651,7 +651,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (event, element) { + eventClick(event, element) { event.title = "CLICKED!"; @@ -683,7 +683,7 @@ $('#calendar').fullCalendar({ } // more events here ], - eventRender: function (event: EventWithDescription, element: any, view: any) { + eventRender(event: EventWithDescription, element: any, view: any) { element.qtip({ content: event.description }); @@ -696,7 +696,7 @@ $('#my-draggable').draggable({ $('#calendar').fullCalendar({ droppable: true, - drop: function (date, allDay) { + drop(date, allDay) { alert("Dropped on " + date + " with allDay=" + allDay); } }); @@ -704,7 +704,7 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar({ droppable: true, dropAccept: '.cool-event', - drop: function () { + drop() { alert('dropped!'); } }); @@ -712,7 +712,7 @@ $('#calendar').fullCalendar({ $('#draggable1').draggable(); $('#draggable2').draggable(); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -777,10 +777,10 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { /* initialize the external events -----------------------------------------------------------------*/ - $('#external-events div.external-event').each(function () { + $('#external-events div.external-event').each(() => { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end @@ -810,7 +810,7 @@ $(document).ready(function () { }, editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! - drop: function (date, allDay) { // this function is called when something is dropped + drop(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); diff --git a/fullcalendar/index.d.ts b/fullcalendar/index.d.ts index 0c55872014..5d6401b9df 100644 --- a/fullcalendar/index.d.ts +++ b/fullcalendar/index.d.ts @@ -1,10 +1,9 @@ -// Type definitions for FullCalendar 2.7.2 +// Type definitions for FullCalendar 2.7 // Project: http://fullcalendar.io/ -// Definitions by: Neil Stalker , Marcelo Camargo +// Definitions by: Neil Stalker , Marcelo Camargo , Patrick Niemann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// import * as moment from 'moment'; @@ -20,7 +19,7 @@ export interface Calendar { export interface BusinessHours { start: moment.Duration | string | Date; end: moment.Duration | string | Date; - dow: Array; + dow: number[]; } export interface Timespan { @@ -50,7 +49,7 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr weekMode?: string; weekNumbers?: boolean; weekNumberCalculation?: any; // String/Function - businessHours?: boolean | BusinessHours | Array; + businessHours?: boolean | BusinessHours | BusinessHours[]; height?: number; contentHeight?: number; aspectRatio?: number; @@ -83,10 +82,10 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr titleFormat?: any; // String buttonText?: ButtonTextObject; - monthNames?: Array; - monthNamesShort?: Array; - dayNames?: Array; - dayNamesShort?: Array; + monthNames?: string[]; + monthNamesShort?: string[]; + dayNames?: string[]; + dayNamesShort?: string[]; weekNumberTitle?: string; // Clicking & Hovering - http://fullcalendar.io/docs/mouse/ @@ -136,13 +135,13 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr eventAfterAllRender?: (view: ViewObject) => void; eventDestroy?: (event: EventObject, element: JQuery, view: ViewObject) => void; - //scheduler options - resourceAreaWidth?:number, - schedulerLicenseKey?:string, - customButtons?:any, - resourceLabelText?:any, - resourceColumns?:any, - displayEventTime?:any, + // scheduler options + resourceAreaWidth?: number; + schedulerLicenseKey?: string; + customButtons?: any; + resourceLabelText?: any; + resourceColumns?: any; + displayEventTime?: any; } /** @@ -218,7 +217,7 @@ export interface EventObject extends Timespan { title: string; allDay?: boolean; url?: string; - className?: string | Array; + className?: string | string[]; editable?: boolean; startEditable?: boolean; durationEditable?: boolean; @@ -253,7 +252,7 @@ export interface EventSource extends JQueryAjaxSettings { backgroundColor?: string; borderColor?: string; textColor?: string; - className?: any; // string/Array + className?: any; // string/string[] editable?: boolean; allDayDefault?: boolean; ignoreTimezone?: boolean; @@ -364,14 +363,19 @@ declare global { fullCalendar(method: 'updateEvent', event: EventObject): void; /** - * Retrieves events that FullCalendar has in memory. + * Reports changes for multiple events and renders them on the calendar. */ - fullCalendar(method: 'clientEvents', idOrfilter?: any): Array; + fullCalendar(method: 'updateEvents', events: EventObject[]): void; /** * Retrieves events that FullCalendar has in memory. */ - fullCalendar(method: 'clientEvents', idOrfilter?: (e: EventObject) => boolean): Array; + fullCalendar(method: 'clientEvents', idOrfilter?: any): EventObject[]; + + /** + * Retrieves events that FullCalendar has in memory. + */ + fullCalendar(method: 'clientEvents', idOrfilter?: (e: EventObject) => boolean): EventObject[]; /** * Removes events from the calendar. @@ -403,6 +407,11 @@ declare global { */ fullCalendar(method: 'renderEvent', event: EventObject, stick?: boolean): void; + /** + * Renders new events on the calendar. + */ + fullCalendar(method: 'renderEvents', events: EventObject[], stick?: boolean): void; + /** * Rerenders all events on the calendar. */ diff --git a/fullcalendar/tslint.json b/fullcalendar/tslint.json new file mode 100644 index 0000000000..fe03bea79d --- /dev/null +++ b/fullcalendar/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "unified-signatures": false + } +} diff --git a/fullcalendar/v1/fullcalendar-tests.ts b/fullcalendar/v1/fullcalendar-tests.ts index 4cec7039de..56a9eb0024 100644 --- a/fullcalendar/v1/fullcalendar-tests.ts +++ b/fullcalendar/v1/fullcalendar-tests.ts @@ -11,7 +11,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function () { + dayClick: () => { alert('a day has been clicked!'); } }); @@ -66,13 +66,13 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar('option', 'aspectRatio', 1.8); $('#calendar').fullCalendar({ - viewRender: function (view) { + viewRender: view => { alert('The new title of the view is ' + view.title); } }); $('#calendar').fullCalendar({ - windowResize: function (view) { + windowResize: view => { alert('The calendar has adjusted to a window resize'); } }); @@ -86,7 +86,7 @@ $('#calendar').fullCalendar({ var view = $('#calendar').fullCalendar('getView'); alert("The view's title is " + view.title); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -150,7 +150,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -215,7 +215,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -269,7 +269,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -334,7 +334,7 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -388,21 +388,21 @@ $(document).ready(function () { }); -$('#my-prev-button').click(function () { +$('#my-prev-button').click(() => { $('#calendar').fullCalendar('prev'); }); -$('#my-next-button').click(function () { +$('#my-next-button').click(() => { $('#calendar').fullCalendar('next'); }); -$('#my-today-button').click(function () { +$('#my-today-button').click(() => { $('#calendar').fullCalendar('today'); }); $('#calendar').fullCalendar('gotoDate', 1, 0, 1); -$('#my-button').click(function () { +$('#my-button').click(() => { var d = $('#calendar').fullCalendar('getDate'); alert("The current date of the calendar is " + d); }); @@ -427,7 +427,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick: function (date, allDay, jsEvent, view) { + dayClick(date, allDay, jsEvent, view) { if (allDay) { alert('Clicked on the entire day: ' + date); @@ -446,7 +446,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (calEvent, jsEvent, view) { + eventClick(calEvent, jsEvent, view) { alert('Event: ' + calEvent.title); alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); @@ -467,7 +467,7 @@ $('#calendar').fullCalendar({ } // other events here ], - eventClick: function (event) { + eventClick(event) { if (event.url) { window.open(event.url); return false; @@ -487,7 +487,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error: () => { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -509,7 +509,7 @@ $('#calendar').fullCalendar({ custom_param1: 'something', custom_param2: 'somethingelse' }, - error: function () { + error: () => { alert('there was an error while fetching events!'); }, color: 'yellow', // a non-ajax option @@ -599,7 +599,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - events: function (start: any, end: any, callback: any) { + events(start: any, end: any, callback: any) { $.ajax({ url: 'myxmlfeed.php', dataType: 'xml', @@ -608,9 +608,9 @@ $('#calendar').fullCalendar({ start: Math.round(start.getTime() / 1000), end: Math.round(end.getTime() / 1000) }, - success: function (doc) { + success(doc) { var events: any[] = []; - $(doc).find('event').each(function () { + $(doc).find('event').each(() => { events.push({ title: $(this).attr('title'), start: $(this).attr('start') // will be parsed @@ -628,7 +628,7 @@ $('#calendar').fullCalendar({ // your event source { - events: function (start: any, end: any, callback: any) { + events(start: any, end: any, callback: any) { // ... }, color: 'yellow', // an option! @@ -649,7 +649,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - eventClick: function (event, element) { + eventClick(event, element) { event.title = "CLICKED!"; @@ -681,7 +681,7 @@ $('#calendar').fullCalendar({ } // more events here ], - eventRender: function (event: EventWithDescription, element: any) { + eventRender(event: EventWithDescription, element: any) { element.qtip({ content: event.description }); @@ -694,7 +694,7 @@ $('#my-draggable').draggable({ $('#calendar').fullCalendar({ droppable: true, - drop: function (date, allDay) { + drop(date, allDay) { alert("Dropped on " + date + " with allDay=" + allDay); } }); @@ -702,7 +702,7 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar({ droppable: true, dropAccept: '.cool-event', - drop: function () { + drop: () => { alert('dropped!'); } }); @@ -710,7 +710,7 @@ $('#calendar').fullCalendar({ $('#draggable1').draggable(); $('#draggable2').draggable(); -$(document).ready(function () { +$(document).ready(() => { var date = new Date(); var d = date.getDate(); @@ -775,10 +775,10 @@ $(document).ready(function () { }); -$(document).ready(function () { +$(document).ready(() => { /* initialize the external events -----------------------------------------------------------------*/ - $('#external-events div.external-event').each(function () { + $('#external-events div.external-event').each(() => { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end @@ -808,7 +808,7 @@ $(document).ready(function () { }, editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! - drop: function (date, allDay) { // this function is called when something is dropped + drop(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); diff --git a/fullcalendar/v1/tslint.json b/fullcalendar/v1/tslint.json index 7d876390fe..fe03bea79d 100644 --- a/fullcalendar/v1/tslint.json +++ b/fullcalendar/v1/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../../tslint.json", + "extends": "../tslint.json", "rules": { "forbidden-types": false, "unified-signatures": false } -} \ No newline at end of file +} diff --git a/fusioncharts/fusioncharts-tests.ts b/fusioncharts/fusioncharts-tests.ts index 9bbf640225..af71a2378a 100644 --- a/fusioncharts/fusioncharts-tests.ts +++ b/fusioncharts/fusioncharts-tests.ts @@ -1,49 +1,51 @@ -FusionCharts.addEventListener('ready',(eventObject)=>{ +import * as FusionCharts from "fusioncharts"; + +FusionCharts.addEventListener('ready', (eventObject) => { eventObject.stopPropagation(); }); -FusionCharts.ready((fusioncharts)=>{ +FusionCharts.ready((fusioncharts) => { }); FusionCharts.version; -FusionCharts('chartId').render();; +FusionCharts('chartId').render(); FusionCharts["debugger"].enable(true); -let chartData ={ +const chartData = { type: 'column2d', renderAt: 'chart-container', width: '450', height: '200', dataFormat: 'json', dataSource: { - "chart": { - "caption": "Monthly revenue for last year", - "subCaption": "Harry's SuperMart", + chart: { + caption: "Monthly revenue for last year", + subCaption: "Harry's SuperMart", }, - "data": [{ - "label": "Jan", - "value": "420000" + data: [{ + label: "Jan", + value: "420000" }, { - "label": "Feb", - "value": "810000" + label: "Feb", + value: "810000" } ] } }; -let chart = new FusionCharts(chartData); +const chart = new FusionCharts(chartData); chart.render(); chart.isActive(); -chart.addEventListener('ready',function(eventObject){ +chart.addEventListener('ready', eventObject => { eventObject.type; }); chart.chartType(); chart.addVariable(); chart.clone(); -chart.zoomTo(0,3); +chart.zoomTo(0, 3); chart.zoomOut(); chart.setJSONData(chartData); chart.ref; \ No newline at end of file diff --git a/fusioncharts/fusioncharts.charts.d.ts b/fusioncharts/fusioncharts.charts.d.ts new file mode 100644 index 0000000000..f06060a054 --- /dev/null +++ b/fusioncharts/fusioncharts.charts.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var charts: (H: FusionChartStatic) => FusionChartStatic; +export = charts; +export as namespace charts; + diff --git a/fusioncharts/fusioncharts.gantt.d.ts b/fusioncharts/fusioncharts.gantt.d.ts new file mode 100644 index 0000000000..d29fa26f78 --- /dev/null +++ b/fusioncharts/fusioncharts.gantt.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var gantt: (H: FusionChartStatic) => FusionChartStatic; +export = gantt; +export as namespace gantt; + diff --git a/fusioncharts/fusioncharts.maps.d.ts b/fusioncharts/fusioncharts.maps.d.ts new file mode 100644 index 0000000000..1894383758 --- /dev/null +++ b/fusioncharts/fusioncharts.maps.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var maps: (H: FusionChartStatic) => FusionChartStatic; +export = maps; +export as namespace maps; + diff --git a/fusioncharts/fusioncharts.powercharts.d.ts b/fusioncharts/fusioncharts.powercharts.d.ts new file mode 100644 index 0000000000..46178c8b8f --- /dev/null +++ b/fusioncharts/fusioncharts.powercharts.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var powercharts: (H: FusionChartStatic) => FusionChartStatic; +export = powercharts; +export as namespace powercharts; + diff --git a/fusioncharts/fusioncharts.ssgrid.d.ts b/fusioncharts/fusioncharts.ssgrid.d.ts new file mode 100644 index 0000000000..b44f5336c1 --- /dev/null +++ b/fusioncharts/fusioncharts.ssgrid.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var ssgrid: (H: FusionChartStatic) => FusionChartStatic; +export = ssgrid; +export as namespace ssgrid; + diff --git a/fusioncharts/fusioncharts.treemap.d.ts b/fusioncharts/fusioncharts.treemap.d.ts new file mode 100644 index 0000000000..c555a627bc --- /dev/null +++ b/fusioncharts/fusioncharts.treemap.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var treemap: (H: FusionChartStatic) => FusionChartStatic; +export = treemap; +export as namespace treemap; + diff --git a/fusioncharts/fusioncharts.widgets.d.ts b/fusioncharts/fusioncharts.widgets.d.ts new file mode 100644 index 0000000000..a4547b99b7 --- /dev/null +++ b/fusioncharts/fusioncharts.widgets.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var widgets: (H: FusionChartStatic) => FusionChartStatic; +export = widgets; +export as namespace widgets; + diff --git a/fusioncharts/fusioncharts.zoomscatter.d.ts b/fusioncharts/fusioncharts.zoomscatter.d.ts new file mode 100644 index 0000000000..106908b6df --- /dev/null +++ b/fusioncharts/fusioncharts.zoomscatter.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var zoomscatter: (H: FusionChartStatic) => FusionChartStatic; +export = zoomscatter; +export as namespace zoomscatter; + diff --git a/fusioncharts/index.d.ts b/fusioncharts/index.d.ts index dc053859b9..9c46955075 100644 --- a/fusioncharts/index.d.ts +++ b/fusioncharts/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for FusionCharts 3.11.2 +// Type definitions for fusioncharts 3.11 // Project: http://www.fusioncharts.com -// Definitions by: Shivaraj KV +// Definitions by: Rohit Kumar , Shivaraj KV // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -136,9 +136,9 @@ declare namespace FusionCharts { outputTo(callback: (message: any) => any): void; - enable(state:any,outputTo?:(message: any) =>any,outputFormat?:any):void + enable(state: any, outputTo?: (message: any) => any, outputFormat?: any): void; - enableFirebugLite():any; + enableFirebugLite(): any; } interface FusionCharts { @@ -154,7 +154,7 @@ declare namespace FusionCharts { configureLink(param: {} | any[], level?: number): void; - setChartAttribute(attributes: ChartObject | String, value?: string): void; + setChartAttribute(attributes: ChartObject | string, value?: string): void; getChartAttribute(attribute?: string | string[]): ChartObject; @@ -273,7 +273,7 @@ declare namespace FusionCharts { formatNumber(num: number, type?: string, config?: {}): Element; - setCurrentRenderer(name: string): void + setCurrentRenderer(name: string): void; getCurrentRenderer(): string; @@ -285,7 +285,7 @@ declare namespace FusionCharts { options: {}; - debugger:Debugger; + debugger: Debugger; } diff --git a/fusioncharts/maps/fusioncharts.usa.d.ts b/fusioncharts/maps/fusioncharts.usa.d.ts new file mode 100644 index 0000000000..16ed0d6c91 --- /dev/null +++ b/fusioncharts/maps/fusioncharts.usa.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var usa: (H: FusionChartStatic) => FusionChartStatic; +export = usa; +export as namespace usa; + diff --git a/fusioncharts/maps/fusioncharts.world.d.ts b/fusioncharts/maps/fusioncharts.world.d.ts new file mode 100644 index 0000000000..3e545e2556 --- /dev/null +++ b/fusioncharts/maps/fusioncharts.world.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var world: (H: FusionChartStatic) => FusionChartStatic; +export = world; +export as namespace world; + diff --git a/fusioncharts/themes/fusioncharts.theme.carbon.d.ts b/fusioncharts/themes/fusioncharts.theme.carbon.d.ts new file mode 100644 index 0000000000..79ba171231 --- /dev/null +++ b/fusioncharts/themes/fusioncharts.theme.carbon.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var carbon: (H: FusionChartStatic) => FusionChartStatic; +export = carbon; +export as namespace carbon; + diff --git a/fusioncharts/themes/fusioncharts.theme.fint.d.ts b/fusioncharts/themes/fusioncharts.theme.fint.d.ts new file mode 100644 index 0000000000..cee08aa6b2 --- /dev/null +++ b/fusioncharts/themes/fusioncharts.theme.fint.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var fint: (H: FusionChartStatic) => FusionChartStatic; +export = fint; +export as namespace fint; + diff --git a/fusioncharts/themes/fusioncharts.theme.ocean.d.ts b/fusioncharts/themes/fusioncharts.theme.ocean.d.ts new file mode 100644 index 0000000000..8b7e3828c0 --- /dev/null +++ b/fusioncharts/themes/fusioncharts.theme.ocean.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var ocean: (H: FusionChartStatic) => FusionChartStatic; +export = ocean; +export as namespace ocean; + diff --git a/fusioncharts/themes/fusioncharts.theme.zune.d.ts b/fusioncharts/themes/fusioncharts.theme.zune.d.ts new file mode 100644 index 0000000000..06ab4c1787 --- /dev/null +++ b/fusioncharts/themes/fusioncharts.theme.zune.d.ts @@ -0,0 +1,7 @@ + +import { FusionChartStatic } from "fusioncharts"; + +declare var zune: (H: FusionChartStatic) => FusionChartStatic; +export = zune; +export as namespace zune; + diff --git a/fusioncharts/tsconfig.json b/fusioncharts/tsconfig.json index dc4436d64c..970238d9a8 100644 --- a/fusioncharts/tsconfig.json +++ b/fusioncharts/tsconfig.json @@ -18,6 +18,20 @@ }, "files": [ "index.d.ts", + "fusioncharts.charts.d.ts", + "fusioncharts.powercharts.d.ts", + "fusioncharts.widgets.d.ts", + "fusioncharts.maps.d.ts", + "fusioncharts.zoomscatter.d.ts", + "fusioncharts.ssgrid.d.ts", + "fusioncharts.gantt.d.ts", + "fusioncharts.treemap.d.ts", + "maps/fusioncharts.usa.d.ts", + "maps/fusioncharts.world.d.ts", + "themes/fusioncharts.theme.carbon.d.ts", + "themes/fusioncharts.theme.fint.d.ts", + "themes/fusioncharts.theme.ocean.d.ts", + "themes/fusioncharts.theme.zune.d.ts", "fusioncharts-tests.ts" ] } \ No newline at end of file diff --git a/fusioncharts/tslint.json b/fusioncharts/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/fusioncharts/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/gaea-model/gaea-model-tests.ts b/gaea-model/gaea-model-tests.ts deleted file mode 100644 index 1615c039e8..0000000000 --- a/gaea-model/gaea-model-tests.ts +++ /dev/null @@ -1,8 +0,0 @@ -function nameSpaceTest() { - let components = {} as GaeaModel.ViewportComponentInfo - // insert into parent - components.props = { - gaeaUniqueKey: '123', - gaeaName: 'componentName' - } -} \ No newline at end of file diff --git a/gaea-model/index.d.ts b/gaea-model/index.d.ts deleted file mode 100644 index 769a1658d0..0000000000 --- a/gaea-model/index.d.ts +++ /dev/null @@ -1,491 +0,0 @@ -// Type definitions for gaea-model 1.0 -// Project: https://github.com/ascoders/gaea-model -// Definitions by: ascoders -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import * as React from 'react'; - -export as namespace GaeaModel; - -export type Component = React.ComponentClass; - -/** - * 组件信息 - */ -export interface ComponentProps extends React.HTMLProps { - /** - * 唯一的 key,用来唯一标识这个组件,所有盖亚内部组件都以 gaea-old- 为前缀 - */ - gaeaUniqueKey: string; - /** - * 组件的中文名 - */ - gaeaName: string; - /** - * 组件图标,为 fontAwesome - */ - gaeaIcon?: string; - /** - * 编辑信息 - */ - gaeaEdit?: ComponentPropsGaeaEdit[]; - /** - * 事件定义 - */ - gaeaEvent?: GaeaEvent; - /** - * 是否在预览模式,preivew 会传入 true - */ - gaeaPreview?: boolean; - /** - * 是否可以拖入子元素 - */ - canDragIn?: boolean; - /** - * 存储事件设置 - */ - gaeaEventData?: EventData[]; - /** - * 存储native事件设置 - */ - gaeaNativeEventData?: EventData[]; - /** - * 存储变量信息 - */ - gaeaVariables?: { - [field: string]: VariableData; - }; - - [x: string]: any; -} - -/** - * 组件配置中数组配置 - */ -export interface ComponentPropsOptionsArray extends ComponentPropsGaeaEdit { - key: string; -} - -/** - * 组件配置中数组配置的值 - */ -export interface ComponentPropsOptionsArrayValue { - /** - * ComponentPropsOptionsArray 设置的 key - */ - key: string; - /** - * 用户填入的值 - */ - value: number | string; -} - -/** - * 组件配置 选择器配置 - */ -export interface ComponentPropsOptionsSelector { - key: string; - value: string; -} - -/** - * number 配置项 - */ -export interface Number { - // 为空时,是数字,否则会以字符串加后缀形式赋值 - key: string; - value: string; -} - -/** - * 组件的值 - */ -export type ComponentPropsOptionValue = number | string | boolean | ComponentPropsOptionsArrayValue[] | any; - -/** - * 组件配置 - */ -export interface ComponentPropsGaeaEdit { - /** - * 对应字段名 - */ - field: string; - /** - * 选项名称 - */ - label: string; - /** - * 编辑器类型 - */ - editor: string; - /** - * 是否可被编辑 - */ - editable: boolean; - /** - * 是否隐藏编辑工具 - */ - hideTool: boolean; - /** - * 当 editor 为 array 时的数组配置 - * 数组中的 key,和填入的值,会作为 Array 填入到 value 中 - */ - array?: ComponentPropsOptionsArrayValue[]; - /** - * 当 editor 为 selector 时的数组配置 - */ - selector?: ComponentPropsOptionsSelector[]; - /** - * 值类型, 默认为字符串 - */ - type?: string; - /** - * 为空时的值,默认为 null - */ - emptyValue?: any; - /** - * 控制 number 单位 - */ - number?: { - units: number[]; - currentUnit: string; - max?: number; - min?: number; - step?: number; - speed?: number; - inputRange?: number[]; - outputRange?: number[]; - slider?: boolean; - }; - /** - * 枚举实例 - */ - instance?: Array<{ - [key: string]: ComponentPropsOptionValue; - }>; -} - -/** - * 组合信息 - */ -export interface ComboComponentInfo extends ViewportComponentFullInfo { - // 组合名 - name: string; -} - -/** - * 获取发布列表的返回值 - */ -export interface GetPublishListResult { - // 版本 - version: string; - // 描述 - description: string; -} - -/** - * 版本信息 - */ -export interface VersionInfo { - content: string; -} - -/** - * 事件设置 - */ -export interface GaeaEvent { - triggers: EventTriggerCondition[]; - effects: EventAction[]; -} - -export interface EventData { - type: string; - event: string; - /** - * 因为事件可能 type 相同,因此记录是第几个 - */ - typeIndex: number; - eventIndex: number; - typeData?: EventTriggerEvent; - eventData?: EventActionJumpUrl | EventActionCall | EventActionEvent; -} - -export interface EventTriggerCondition { - name: string; - // 触发类型 - type: string; - // 是否由自己的生命周期触发 - selfCallback?: boolean; -} - -export interface EventAction { - name: string; - // 动作类型 - // call: 调用传进来的方法 - // jumpUrl: 跳转一个网址 - type: string; - call?: EventCallType; -} - -/** - * 事件定义类型 - */ -export interface EventCallType { - // 调用函数名称 - functionName: string; - // 调用参数 - param?: EventCallTypeParam[]; -} - -export interface EventCallTypeParam { - label: string; - field: string; - editor: string; // text -} - -/** - * 事件触发数据类型 - */ -export interface EventTriggerEvent { - listen?: string; -} - -export interface EventUpdatePropsEvent { - /** - * 修改后的 props - */ - props: ComponentProps; -} - -/** - * 事件动作数据类型 - */ -export interface EventActionJumpUrl { - url?: string; -} - -export interface EventActionCall { - // 函数在 map 里的 key - key?: string; -} - -export interface EventActionEvent { - emit?: string; -} - -export interface ExternalParameter { - /** - * 名称 - */ - name: string; - /** - * 类型 - * number string boolean - */ - type: string; -} - -/** - * 标识哪些字段用什么变量 - */ -export interface VariableData { - // 变量类型 - // 比如是外部传参,还是全局变量 - variableType: string; - // 变量的哪个字段 - variableField: string; - // 值类型 string number boolean - valueType: string; -} - -/** - * 插件信息 - */ -export interface Plugin extends React.ComponentClass { - // 插件安放位置 - position: string; - Action?: any; - Store?: any; -} - -/******************************************************************************************************** - * DIff - ********************************************************************************************************/ -export interface Diff { - // 操作类型 - type: 'add' | 'move' | 'remove' | 'exchange' | 'update' | 'paste' | 'reset' | 'addCombo' | 'addSource'; - // 操作组件的 mapUniqueKey - mapUniqueKey: string; - // 新增操作 - add?: { - // 新增组件的唯一标识 id - uniqueId: string; - // 父级 mapKey - parentMapUniqueKey: string; - // 插入的位置 - index: number; - }; - // 移动到另一个父元素 - move?: { - // 移动到的父级 mapKey - targetParentMapUniqueKey: string; - // 移动前父级 mapKey - sourceParentMapUniqueKey: string; - // 插入的位置 - targetIndex: number; - // 移除的位置 - sourceIndex: number; - }; - // 删除组件 - remove?: DiffRemove; - // 内部交换顺序 - exchange?: { - oldIndex: number; - newIndex: number; - }; - // 更新操作 - update?: { - oldValue: ComponentProps; - newValue: ComponentProps; - }; - // 粘贴操作 - paste?: DiffRemove; - // 重置组件 - reset?: { - // 重置前的信息 - beforeProps: ComponentProps; - beforeName: string; - }; - // 新增组合 - addCombo?: { - // 父级 mapKey - parentMapUniqueKey: string; - // 父级的 index - index: number; - // 组合的完整信息(不是 copy 的, 是真正对应的 mapUniqueKey) - componentInfo: ViewportComponentFullInfo; - }; - // 新增模板 - addSource?: { - // 父级 mapKey - parentMapUniqueKey: string; - // 父级的 index - index: number; - // 组合的完整信息(不是 copy 的, 是真正对应的 mapUniqueKey) - componentInfo: ViewportComponentFullInfo; - }; -} - -export interface DiffRemove extends ViewportComponentFullInfo { - // 父级元素 mapKey - parentMapUniqueKey: string; - // 删除的位置 - index: number; -} - -/******************************************************************************************************** - * Viewport - ********************************************************************************************************/ -/** - * 在视图中的组件属性 - */ -export interface ViewportComponentInfo { - /** - * props - */ - props: ComponentProps; - /** - * 子元素(canDragIn才有) - * 只存子元素在 map 中的 key - */ - layoutChilds?: string[]; - /** - * 父级 mapUniqueKey, 这样不但方便寻找父级,还能根据是否为 null 判断是否为根元素 - */ - parentMapUniqueKey: string; -} - -/** - * 当前正在移动元素的信息 - */ -export interface MovingComponent { - // 在编辑区域的组件信息 - mapUniqueKey: string; - // 是否是新拖拽的 - isNew: boolean; - // 组件的唯一标识, 新建的时候采用 - uniqueKey: string; - // 直接给 source 就直接用 - source: string; -} - -/** - * hover 元素的信息 - */ -export interface HoverComponentSpec { - left: number; - top: number; - width: number; - height: number; - hovering: boolean; -} - -/** - * 一个独立组件的完整信息 - */ -export interface ViewportComponentFullInfo { - // 组件的 mapUniqueKey - mapUniqueKey: string; - // 组件信息 - componentInfo: ViewportComponentInfo; - // 子元素列表 (包括非直接子集) - childs: { - [mapUniqueKey: string]: ViewportComponentInfo; - }; -} - -/** - * 当前拖拽元素信息 - */ -export interface CurrentDragComponentInfo { - // 类型 - type: 'new' | 'combo' | 'viewport'; - // 开始拖拽父级的 dom - dragStartParentElement: HTMLElement; - // 开始拖拽在父级中的位置 - dragStartIndex: number; - newInfo?: { - // 唯一 key,用来实例化组件 - uniqueKey: string; - }; - comboInfo?: { - // combo 信息 - source: string; - }; - viewportInfo?: { - // 当前拖拽组件的 mapUniqueKey - mapUniqueKey: string; - // 拖拽目标的 mapUniqueKey - targetMapUniqueKey?: string; - // 拖拽目标的 index - targetIndex?: number; - }; -} - -/******************************************************************************************************** - * Event - ********************************************************************************************************/ -/** - * 鼠标移动到组件上/树对应的组件上 - */ -export interface MouseHoverComponentEvent { - mapUniqueKey: string; - type: string; -} - -/** - * 修改某个组件选中状态 - */ -export interface ComponentSelectStatusEvent { - mapUniqueKey: string; - selected: boolean; -} diff --git a/gapi.auth2/gapi.auth2-tests.ts b/gapi.auth2/gapi.auth2-tests.ts index a3ba839a36..621ca6f056 100644 --- a/gapi.auth2/gapi.auth2-tests.ts +++ b/gapi.auth2/gapi.auth2-tests.ts @@ -19,6 +19,28 @@ function test_getAuthInstance(){ var auth = gapi.auth2.getAuthInstance(); } +function test_signIn(){ + gapi.auth2.getAuthInstance().signIn({ + scope: 'email profile', + prompt: 'content' + }); +} + +function test_signInOptionsBuild(){ + var options = new gapi.auth2.SigninOptionsBuilder(); + options.setAppPackageName('com.example.app'); + options.setFetchBasicProfile(true); + options.setPrompt('select_account'); + options.setScope('profile').setScope('email'); + gapi.auth2.getAuthInstance().signIn(options); +} + +function test_getAuthResponse(){ + var user = gapi.auth2.getAuthInstance().currentUser.get(); + var authResponse = user.getAuthResponse(); + var authResponseWithAuth = user.getAuthResponse(true); +} + function test_render(){ var success = (googleUser: gapi.auth2.GoogleUser): void => { console.log(googleUser); diff --git a/gapi.auth2/index.d.ts b/gapi.auth2/index.d.ts index 593cae78d8..6146a87e28 100644 --- a/gapi.auth2/index.d.ts +++ b/gapi.auth2/index.d.ts @@ -31,12 +31,7 @@ declare namespace gapi.auth2 { /** * Signs in the user using the specified options. */ - signIn(options?: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, optionBuilder?: SigninOptionsBuilder): any; + signIn(options?: SigninOptions | SigninOptionsBuilder): any; /** * Signs out all accounts from the application. @@ -59,12 +54,8 @@ declare namespace gapi.auth2 { /** * Attaches the sign-in flow to the specified container's click handler. */ - attachClickHandler(container: any, options: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; + attachClickHandler(container: any, options: SigninOptions, + onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; } export interface IsSignedIn{ @@ -93,6 +84,32 @@ declare namespace gapi.auth2 { listen(listener: (user: GoogleUser) => any): void; } + export interface SigninOptions { + /** + * The package name of the Android app to install over the air. + * See Android app installs from your web site: + * https://developers.google.com/identity/sign-in/web/android-app-installs + */ + app_package_name?: string; + /** + * Fetch users' basic profile information when they sign in. + * Adds 'profile', 'email' and 'openid' to the requested scopes. + * True if unspecified. + */ + fetch_basic_profile?: boolean; + /** + * Specifies whether to prompt the user for re-authentication. + * See OpenID Connect Request Parameters: + * https://openid.net/specs/openid-connect-basic-1_0.html#RequestParameters + */ + prompt?: string; + /** + * The scopes to request, as a space-delimited string. + * Optional if fetch_basic_profile is not set to false. + */ + scope?: string; + } + export class SigninOptionsBuilder { setAppPackageName(name: string): any; setFetchBasicProfile(fetch: boolean): any; @@ -151,7 +168,7 @@ declare namespace gapi.auth2 { /** * Get the response object from the user's auth session. */ - getAuthResponse(): AuthResponse; + getAuthResponse(includeAuthorizationData?: boolean): AuthResponse; /** * Returns true if the user granted the specified scopes. @@ -164,22 +181,12 @@ declare namespace gapi.auth2 { * When you use GoogleUser.signIn(), the sign-in flow skips the account chooser step. * See GoogleAuth.signIn(). */ - signIn(options?: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, optionBuilder?: SigninOptionsBuilder): any; + signIn(options?: SigninOptions | SigninOptionsBuilder): any; /** - * + * See GoogleUser.signIn() */ - grant(options?: { - app_package_name?: string; - fetch_basic_profile?: boolean; - prompt?: boolean; - scope?: string; - }, optionBuilder?: SigninOptionsBuilder): any; + grant(options?: SigninOptions | SigninOptionsBuilder): any; /** * Get permission from the user to access the specified scopes offline. diff --git a/geodesy/tslint.json b/geodesy/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/geodesy/tslint.json +++ b/geodesy/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/geojson/geojson-tests.ts b/geojson/geojson-tests.ts index dc3432f48c..42ae99ce47 100644 --- a/geojson/geojson-tests.ts +++ b/geojson/geojson-tests.ts @@ -1,26 +1,24 @@ - - -var featureCollection: GeoJSON.FeatureCollection = { +let featureCollection: GeoJSON.FeatureCollection = { type: "FeatureCollection", - features: [ - { + features: [ + { type: "Feature", geometry: { - type: "Point", + type: "Point", coordinates: [102.0, 0.5] }, properties: { prop0: "value0" } }, - { + { type: "Feature", geometry: { type: "LineString", coordinates: [ - [102.0, 0.0], - [103.0, 1.0], - [104.0, 0.0], + [102.0, 0.0], + [103.0, 1.0], + [104.0, 0.0], [105.0, 1.0] ] }, @@ -29,7 +27,7 @@ var featureCollection: GeoJSON.FeatureCollection = { prop1: 0.0 } }, - { + { type: "Feature", geometry: { type: "Polygon", @@ -52,9 +50,9 @@ var featureCollection: GeoJSON.FeatureCollection = { type: "proj4" } } -} +}; -var feature: GeoJSON.Feature = { +let featureWithPolygon: GeoJSON.Feature = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], geometry: { @@ -67,29 +65,29 @@ var feature: GeoJSON.Feature = { }; -var point: GeoJSON.Point = { +let point: GeoJSON.Point = { type: "Point", coordinates: [100.0, 0.0] }; // This type is commonly used in the turf package -var pointCoordinates: number[] = point.coordinates +let pointCoordinates: number[] = point.coordinates; -var lineString: GeoJSON.LineString = { +let lineString: GeoJSON.LineString = { type: "LineString", coordinates: [ [100.0, 0.0], [101.0, 1.0] ] }; -var polygon: GeoJSON.Polygon = { +let polygon: GeoJSON.Polygon = { type: "Polygon", coordinates: [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }; -var polygonWithHole: GeoJSON.Polygon = { +let polygonWithHole: GeoJSON.Polygon = { type: "Polygon", coordinates: [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], @@ -97,12 +95,12 @@ var polygonWithHole: GeoJSON.Polygon = { ] }; -var multiPoint: GeoJSON.MultiPoint = { +let multiPoint: GeoJSON.MultiPoint = { type: "MultiPoint", coordinates: [ [100.0, 0.0], [101.0, 1.0] ] }; -var multiLineString: GeoJSON.MultiLineString = { +let multiLineString: GeoJSON.MultiLineString = { type: "MultiLineString", coordinates: [ [ [100.0, 0.0], [101.0, 1.0] ], @@ -110,25 +108,103 @@ var multiLineString: GeoJSON.MultiLineString = { ] }; -var multiPolygon: GeoJSON.MultiPolygon = { +let multiPolygon: GeoJSON.MultiPolygon = { type: "MultiPolygon", coordinates: [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] -} +}; -var geometryCollection: GeoJSON.GeometryCollection = { +let geometryCollection: GeoJSON.GeometryCollection = { type: "GeometryCollection", - "geometries": [ - { + geometries: [ + { type: "Point", coordinates: [100.0, 0.0] }, - { + { type: "LineString", coordinates: [ [101.0, 0.0], [102.0, 1.0] ] } ] -} \ No newline at end of file +}; + +let feature: GeoJSON.Feature = { + type: "Feature", + geometry: lineString, + properties: null +}; +feature = { + type: "Feature", + geometry: polygon, + properties: null +}; +feature = { + type: "Feature", + geometry: polygonWithHole, + properties: null +}; +feature = { + type: "Feature", + geometry: multiPoint, + properties: null +}; +feature = { + type: "Feature", + geometry: multiLineString, + properties: null +}; +feature = { + type: "Feature", + geometry: multiPolygon, + properties: null +}; +feature = { + type: "Feature", + geometry: geometryCollection, + properties: null +}; + +featureCollection = { + type: "FeatureCollection", + features: [ + { + type: "Feature", + geometry: lineString, + properties: {test: 'OK'} + }, { + type: "Feature", + geometry: polygon, + properties: {test: 'OK'} + }, { + type: "Feature", + geometry: polygonWithHole, + properties: {test: 'OK'} + }, { + type: "Feature", + geometry: multiPoint, + properties: {test: 'OK'} + }, { + type: "Feature", + geometry: multiLineString, + properties: {test: 'OK'} + }, { + type: "Feature", + geometry: multiPolygon, + properties: {test: 'OK'} + }, { + type: "Feature", + geometry: geometryCollection, + properties: {test: 'OK'} + } + ], + crs: { + type: "link", + properties: { + href: "http://example.com/crs/42", + type: "proj4" + } + } +}; diff --git a/geojson/index.d.ts b/geojson/index.d.ts index f6261d81fe..7c825d2541 100644 --- a/geojson/index.d.ts +++ b/geojson/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for GeoJSON Format Specification +// Type definitions for GeoJSON Format Specification Revision 1.0 // Project: http://geojson.org/ // Definitions by: Jacob Bruun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,8 +8,7 @@ declare namespace GeoJSON { /*** * http://geojson.org/geojson-spec.html#geojson-objects */ - export interface GeoJsonObject - { + export interface GeoJsonObject { type: string; bbox?: number[]; crs?: CoordinateReferenceSystem; @@ -18,116 +17,107 @@ declare namespace GeoJSON { /*** * http://geojson.org/geojson-spec.html#positions */ - export type Position = number[] + export type Position = number[]; /*** * http://geojson.org/geojson-spec.html#geometry-objects */ - export interface GeometryObject extends GeoJsonObject - { - coordinates: any + interface DirectGeometryObject extends GeoJsonObject { + coordinates: Position[][][] | Position[][] | Position[] | Position; } + /** + * GeometryObject supports geometry collection as well + */ + export type GeometryObject = DirectGeometryObject | GeometryCollection; /*** * http://geojson.org/geojson-spec.html#point */ - export interface Point extends GeometryObject - { - type: 'Point' - coordinates: Position + export interface Point extends DirectGeometryObject { + type: 'Point'; + coordinates: Position; } /*** * http://geojson.org/geojson-spec.html#multipoint */ - export interface MultiPoint extends GeometryObject - { - type: 'MultiPoint' - coordinates: Position[] + export interface MultiPoint extends DirectGeometryObject { + type: 'MultiPoint'; + coordinates: Position[]; } /*** * http://geojson.org/geojson-spec.html#linestring */ - export interface LineString extends GeometryObject - { - type: 'LineString' - coordinates: Position[] + export interface LineString extends DirectGeometryObject { + type: 'LineString'; + coordinates: Position[]; } /*** * http://geojson.org/geojson-spec.html#multilinestring */ - export interface MultiLineString extends GeometryObject - { - type: 'MultiLineString' - coordinates: Position[][] + export interface MultiLineString extends DirectGeometryObject { + type: 'MultiLineString'; + coordinates: Position[][]; } /*** * http://geojson.org/geojson-spec.html#polygon */ - export interface Polygon extends GeometryObject - { - type: 'Polygon' - coordinates: Position[][] + export interface Polygon extends DirectGeometryObject { + type: 'Polygon'; + coordinates: Position[][]; } /*** * http://geojson.org/geojson-spec.html#multipolygon */ - export interface MultiPolygon extends GeometryObject - { - type: 'MultiPolygon' - coordinates: Position[][][] + export interface MultiPolygon extends DirectGeometryObject { + type: 'MultiPolygon'; + coordinates: Position[][][]; } /*** * http://geojson.org/geojson-spec.html#geometry-collection */ - export interface GeometryCollection extends GeoJsonObject - { - type: 'GeometryCollection' + export interface GeometryCollection extends GeoJsonObject { + type: 'GeometryCollection'; geometries: GeometryObject[]; } /*** * http://geojson.org/geojson-spec.html#feature-objects */ - export interface Feature extends GeoJsonObject - { - type: 'Feature' + export interface Feature extends GeoJsonObject { + type: 'Feature'; geometry: T; - properties: any; + properties: {} | null; id?: string; } /*** * http://geojson.org/geojson-spec.html#feature-collection-objects */ - export interface FeatureCollection extends GeoJsonObject - { - type: 'FeatureCollection' - features: Feature[]; + export interface FeatureCollection extends GeoJsonObject { + type: 'FeatureCollection'; + features: Array>; } /*** * http://geojson.org/geojson-spec.html#coordinate-reference-system-objects */ - export interface CoordinateReferenceSystem - { + export interface CoordinateReferenceSystem { type: string; properties: any; } - export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem - { - properties: { name: string } + export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem { + properties: { name: string }; } - export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem - { - properties: { href: string; type: string } + export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem { + properties: { href: string; type: string }; } } diff --git a/geojson/tslint.json b/geojson/tslint.json new file mode 100644 index 0000000000..0b14fdec0d --- /dev/null +++ b/geojson/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/geolib/geolib-tests.ts b/geolib/geolib-tests.ts index 5386bf730b..e69de29bb2 100644 --- a/geolib/geolib-tests.ts +++ b/geolib/geolib-tests.ts @@ -1,201 +0,0 @@ -import "geolib"; -import PositionAsDecimal = geolib.PositionAsDecimal; -import CompassDirection = geolib.CompassDirection; -import Distance = geolib.Distance; -import Bound = geolib.Bound; - -let dist: number = geolib.getDistance( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"} -); - -dist = geolib.getDistance( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"} -); - -dist = geolib.getDistance( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"}, - 1, - 1 -); - -// Working with W3C Geolocation API -navigator.geolocation.getCurrentPosition( - function(position) { - alert('You are ' + geolib.getDistance(position.coords, { - latitude: 51.525, - longitude: 7.4575 - }) + ' meters away from 51.525, 7.4575'); - }, - function() { - alert('Position could not be determined.') - }, - { - enableHighAccuracy: true - } -); - - -dist = geolib.getDistanceSimple( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"} -); - -dist = geolib.getDistanceSimple( - {latitude: 51.5103, longitude: 7.49347}, - {latitude: "51° 31' N", longitude: "7° 28' E"}, - 1 -); - -let posAsDecimal: PositionAsDecimal = geolib.getCenter([ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722} -]); - -posAsDecimal = geolib.getCenter([ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722} -]); - -posAsDecimal = geolib.getCenterOfBounds([ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722}, - {latitude: 51.503333, longitude: -1.119722} -]); - - - -let bound: Bound = geolib.getBounds([ - {latitude: 52.516272, longitude: 13.377722, elevation: 1}, - {latitude: 51.515, longitude: 7.453619, elevation: 1}, - {latitude: 51.503333, longitude: -0.119722, elevation: 1}]); - -let isInside: boolean = geolib.isPointInside( - {latitude: 51.5125, longitude: 7.485}, - [ - {latitude: 51.50, longitude: 7.40}, - {latitude: 51.555, longitude: 7.40}, - {latitude: 51.555, longitude: 7.625}, - {latitude: 51.5125, longitude: 7.625} - ] -); // -> true - -// checks if 51.525, 7.4575 is within a radius of 5km from 51.5175, 7.4678 -let boolResult: boolean = geolib.isPointInCircle( - {latitude: 51.525, longitude: 7.4575}, - {latitude: 51.5175, longitude: 7.4678}, - 5000 -); - -let bearing: number = geolib.getRhumbLineBearing( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444} -); - -bearing = geolib.getBearing( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444} -); - -let compassDirection: CompassDirection = geolib.getCompassDirection( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444} -); - -compassDirection = geolib.getCompassDirection( - {latitude: 52.518611, longitude: 13.408056}, - {latitude: 51.519475, longitude: 7.46694444}, - 'circle' -); - -// coords array -let distanceArray: Distance[] = geolib.orderByDistance({latitude: 51.515, longitude: 7.453619}, [ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.518, longitude: 7.45425}, - {latitude: 51.503333, longitude: -0.119722} -]); - -// coords object -distanceArray = geolib.orderByDistance({latitude: 51.515, longitude: 7.453619}, [ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.518, longitude: 7.45425}, - {latitude: 51.503333, longitude: -0.119722} -]); - - -// in this case set offset to 1 otherwise the nearest point will always be your reference point -let posAsDecimalArray: Distance[] = geolib.findNearest( - {latitude: 51.515, longitude: 7.453619}, - [ - {latitude: 52.516272, longitude: 13.377722}, - {latitude: 51.515, longitude: 7.453619}, - {latitude: 51.503333, longitude: -0.119722}, - {latitude: 55.751667, longitude: 37.617778}, - {latitude: 48.8583, longitude: 2.2945}, - {latitude: 59.3275, longitude: 18.0675}, - {latitude: 59.916911, longitude: 10.727567} - ], 1); - - -// Calculate distance from Berlin via Dortmund to London -dist = geolib.getPathLength([ - {latitude: 52.516272, longitude: 13.377722}, // Berlin - {latitude: 51.515, longitude: 7.453619}, // Dortmund - {latitude: 51.503333, longitude: -0.119722} // London -]); // -> 945235 - -let speed: number = geolib.getSpeed( - [ - {latitude: 51.567294, longitude: 7.38896, time: 1360231200880}, - {latitude: 52.54944, longitude: 13.468509, time: 1360245600880} - ], - {unit: 'mph'} -); // -> 66.9408 (mph) - -speed= geolib.getSpeed( - [ - {latitude: 51.567294, longitude: 7.38896, time: 1360231200880}, - {latitude: 52.54944, longitude: 13.468509, time: 1360245600880} - ] -); // -> 66.9408 (mph) - -let point1 = {latitude: 0.5, longitude: 0}; -let point2 = {latitude: 0, longitude: 10}; -let point3 = {latitude: 0, longitude: 15.5}; -let start = {latitude: 0, longitude: 0}; -let end = {latitude: 0, longitude: 15}; - -let isInLine1 = geolib.isPointInLine(point1, start, end) //-> false; -let isInLine2 = geolib.isPointInLine(point2, start, end) //-> true; -let isInLine3 = geolib.isPointInLine(point3, start, end) //-> false; - - -let convertResult: number = geolib.convertUnit('km', 14213, 2) // -> 14,21 -convertResult = geolib.convertUnit('km', 14213) // -> 14,21 - -let result: number = geolib.sexagesimal2decimal("51° 29' 46\" N") - -let resultString: string = geolib.decimal2sexagesimal(51.49611111); // -> 51° 29' 46.00 - -result = geolib.latitude({lat: 51.49611, lng: 7.38896}); // -> 51.49611 -result = geolib.longitude({lat: 51.49611, lng: 7.38896}); // -> 7.38896 - -result = geolib.useDecimal("51° 29' 46\" N"); // -> 51.59611111 -result = geolib.useDecimal(51.59611111) // -> 51.59611111 - -result = geolib.elevation({lat: 51.49611, lng: 7.38896}); - -let initialPoint = {latitude: 51.516272, longitude: 0.45425} -let radius = 100; -dist = 1234; -bearing = 45; - - -posAsDecimal = geolib.computeDestinationPoint(initialPoint, dist, bearing); -posAsDecimal = geolib.computeDestinationPoint(initialPoint, dist, bearing, radius); -// -> {"latitude":51.52411853234181,"longitude":0.4668623365950795} diff --git a/geopattern/geopattern-tests.ts b/geopattern/geopattern-tests.ts index 96ea652028..957da81c20 100644 --- a/geopattern/geopattern-tests.ts +++ b/geopattern/geopattern-tests.ts @@ -1,4 +1,3 @@ -/// /// var pattern = GeoPattern.generate('GitHub'); diff --git a/get-stdin/get-stdin-tests.ts b/get-stdin/get-stdin-tests.ts index d5b720234f..d77dff5924 100644 --- a/get-stdin/get-stdin-tests.ts +++ b/get-stdin/get-stdin-tests.ts @@ -6,4 +6,4 @@ getStdin().then(str => { getStdin.buffer().then(buffer => { console.log("Length " + buffer.length + buffer.toString()); -}) \ No newline at end of file +}); diff --git a/globule/globule-tests.ts b/globule/globule-tests.ts new file mode 100644 index 0000000000..78697ba199 --- /dev/null +++ b/globule/globule-tests.ts @@ -0,0 +1,28 @@ +import * as globule from 'globule'; + +let filepaths: string[]; + +filepaths = globule.find('**/*.js'); +filepaths = globule.find(['**/*.js']); +filepaths = globule.find('**/*.js', '**/*.less'); +filepaths = globule.find('*.js', { matchBase: true }); +filepaths = globule.find('**/*.js', '**/*.less', { filter: 'isFile' }); +filepaths = globule.find('**/*.js', '**/*.less', { filter: /jQuery/i.test }); +filepaths = globule.find({ src: '**/*.js' }); + +filepaths = globule.match('*.js', '/home/code'); +filepaths = globule.match('*.js', '/home/code', { matchBase: true }); + +let bResult: boolean; +bResult = globule.isMatch('*.js', '/home/code'); +bResult = globule.isMatch('*.js', '/home/code', { matchBase: true }); + +let mappings = globule.mapping(['*.js']); +const len = mappings.length; +const src = mappings[0].src; +const dest = mappings[0].dest; + +mappings = globule.mapping(['*.js'], { srcBase: '/home/code' }); +mappings = globule.mapping(['*.js', '*.less']); +mappings = globule.mapping(['*.js'], ['*.less']); + diff --git a/globule/index.d.ts b/globule/index.d.ts new file mode 100644 index 0000000000..4add1d4461 --- /dev/null +++ b/globule/index.d.ts @@ -0,0 +1,87 @@ +// Type definitions for globule 1.1 +// Project: https://github.com/cowboy/node-globule +// Definitions by: Dusan Radovanovic +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import minimatch = require('minimatch'); +import glob = require('glob'); + +interface FindOptions extends glob.IOptions { + src?: string; + filter?: string | ((filepath?: string, options?: any) => boolean); + nonull?: boolean; + matchBase?: boolean; + srcBase?: string; + prefixBase?: boolean; +} + +interface MappingOptions extends FindOptions { + srcBase?: string; + destBase?: string; + ext?: string; + extDot?: 'first' | 'last'; + flatten?: boolean; + rename?: (p: string) => string; +} + +interface OneMapping { + src: string[]; + dest: string; +} + +interface GlobuleStatic { + /** + * Match one or more globbing patterns against one or more file paths. + * Returns a uniqued array of all file paths that match any of the specified globbing patterns. + */ + match(patterns: string | string[], filepaths: string | string[], options?: minimatch.IOptions): string[]; + + /** + * Tests pattern(s) against against one or more file paths and returns true if any files were matched, otherwise false. + */ + isMatch(patterns: string | string[], filepaths: string | string[], options?: minimatch.IOptions): boolean; + + /** + * Returns a unique array of all file or directory paths that match the given globbing pattern(s) + */ + find(pattern: string | string[], options?: FindOptions): string[]; + + /** + * Returns a unique array of all file or directory paths that match the given globbing pattern(s) + */ + find(options: FindOptions): string[]; + + /** + * Returns a unique array of all file or directory paths that match the given globbing pattern(s) + */ + find(pattern: string | string[], pattern2: string | string[], options?: FindOptions): string[]; + + /** + * Returns a unique array of all file or directory paths that match the given globbing pattern(s) + */ + find(pattern: string, pattern2: string, pattern3: string | string[], options?: FindOptions): string[]; + + /** + * Given a set of source file paths, returns an array of src-dest file mapping objects + */ + mapping(filepaths: string[], options?: MappingOptions): OneMapping[]; + + /** + * Given a set of source file paths, returns an array of src-dest file mapping objects + */ + mapping(options: MappingOptions): OneMapping[]; + + /** + * Given a set of source file paths, returns an array of src-dest file mapping objects + */ + mapping(filepaths: string[], filepaths2: string[], options?: MappingOptions): OneMapping[]; + + /** + * Given a set of source file paths, returns an array of src-dest file mapping objects + */ + mapping(filepaths: string[], filepaths2: string[], filepaths3: string[], options?: MappingOptions): OneMapping[]; +} + +declare var globule: GlobuleStatic; +export = globule; + diff --git a/globule/tsconfig.json b/globule/tsconfig.json new file mode 100644 index 0000000000..55317b01f8 --- /dev/null +++ b/globule/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", + "globule-tests.ts" + ] +} \ No newline at end of file diff --git a/globule/tslint.json b/globule/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/globule/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/google.analytics/google.analytics-tests.ts b/google.analytics/google.analytics-tests.ts index 82533e4bdf..6b7962899b 100644 --- a/google.analytics/google.analytics-tests.ts +++ b/google.analytics/google.analytics-tests.ts @@ -3,13 +3,13 @@ describe("tester Google Analytics Tracker _gat object", () => { it("can set ga script element", () => { - gaClassic = document.createElement("script"); + gaClassic = document.createElement("script"); }); it("can set aync to true", () => { gaClassic.async = true; }); it("can set src to string url", () => { - gaClassic.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; + gaClassic.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; }); it("can set type", () => { gaClassic.type = 'text/javascript'; @@ -27,10 +27,10 @@ describe('UniversalAnalytics', () => { ga('send', {hitType: 'event', eventCategory: 'Videos', eventAction: 'play', eventLabel: 'Fall Campaign'}); ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {nonInteraction: true}); ga('send', 'pageview', '/page'); - ga('send', 'social', {'socialNetwork': 'facebook', 'socialAction': 'like', 'socialTarget': 'http://foo.com'}); - ga('send', 'social', {'socialNetwork': 'google+', 'socialAction': 'plus', 'socialTarget': 'http://foo.com'}); - ga('send', 'timing', {'timingCategory': 'category', 'timingVar': 'lookup', 'timingValue': 123}); - ga('send', 'timing', {'timingCategory': 'category', 'timingVar': 'lookup', 'timingValue': 123, 'timingLabel': 'label'}); + ga('send', 'social', {socialNetwork: 'facebook', socialAction: 'like', socialTarget: 'http://foo.com'}); + ga('send', 'social', {socialNetwork: 'google+', socialAction: 'plus', socialTarget: 'http://foo.com'}); + ga('send', 'timing', {timingCategory: 'category', timingVar: 'lookup', timingValue: 123}); + ga('send', 'timing', {timingCategory: 'category', timingVar: 'lookup', timingValue: 123, timingLabel: 'label'}); ga('trackerName.send', 'event', 'load'); ga.create('UA-65432-1', 'auto'); diff --git a/google.analytics/index.d.ts b/google.analytics/index.d.ts index 68c1c627c1..0f86e0be40 100644 --- a/google.analytics/index.d.ts +++ b/google.analytics/index.d.ts @@ -87,7 +87,7 @@ declare namespace UniversalAnalytics { getAll(): UniversalAnalytics.Tracker[]; getByName(name: string): UniversalAnalytics.Tracker; - remove(name:string): void; + remove(name: string): void; } interface Tracker { diff --git a/google.analytics/tslint.json b/google.analytics/tslint.json new file mode 100644 index 0000000000..e8bc207e33 --- /dev/null +++ b/google.analytics/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "../tslint.json", + "rules": { + "dt-header": false, + "forbidden-types": false, + "unified-signatures": false + } +} diff --git a/googlemaps/index.d.ts b/googlemaps/index.d.ts index df0d9ceb5d..f94b29525c 100644 --- a/googlemaps/index.d.ts +++ b/googlemaps/index.d.ts @@ -784,7 +784,7 @@ declare namespace google.maps { open(map?: Map|StreetViewPanorama, anchor?: MVCObject): void; setContent(content: string|Node): void; setOptions(options: InfoWindowOptions): void; - setPosition(position: LatLng): void; + setPosition(position: LatLng|LatLngLiteral): void; setZIndex(zIndex: number): void; } diff --git a/graphql-relay/graphql-relay-tests.ts b/graphql-relay/graphql-relay-tests.ts index f1b18a4521..723ffa393b 100644 --- a/graphql-relay/graphql-relay-tests.ts +++ b/graphql-relay/graphql-relay-tests.ts @@ -43,13 +43,13 @@ forwardConnectionArgs.first = 10; backwardConnectionArgs.before = "b"; backwardConnectionArgs.last = 10; // connectionDefinitions returns a connectionType and its associated edgeType, given a node type. -let resolve: GraphQLFieldResolver = (source, args, context, info) => { +const resolve: GraphQLFieldResolver = (source, args, context, info) => { info.fieldName = "f"; }; const fields: GraphQLFieldConfigMap = {}; let t: GraphQLObjectType; let e: GraphQLObjectType; -let def = connectionDefinitions({ +const def = connectionDefinitions({ connectionFields: fields, edgeFields: fields, name: "N", @@ -62,7 +62,8 @@ let def = connectionDefinitions({ }); t = def.connectionType; e = def.edgeType; -// connectionFromArray is a helper method that takes an array and the arguments from connectionArgs, does pagination and filtering, and returns an object in the shape expected by a connectionType's resolve function. +// connectionFromArray is a helper method that takes an array and the arguments from connectionArgs, +// does pagination and filtering, and returns an object in the shape expected by a connectionType's resolve function. const conn = connectionFromArray([1, 2, 3], { after: "a", before: "b", @@ -89,7 +90,7 @@ conn2.then((res) => { // cursorForObjectInConnection is a helper method that takes an array and a member object, and returns a cursor for use in the mutation payload. cursorForObjectInConnection(["a"], "b").toLowerCase(); // An example usage of these methods from the test schema: -let shipType: GraphQLObjectType = new GraphQLObjectType({ +const shipType: GraphQLObjectType = new GraphQLObjectType({ name: "ShipType", fields: {}, }); @@ -109,7 +110,8 @@ const factionType = new GraphQLObjectType({ }), }); // Object Identification -// nodeDefinitions returns the Node interface that objects can implement, and returns the node root field to include on the query type. To implement this, it takes a function to resolve an ID to an object, and to determine the type of a given object. +// nodeDefinitions returns the Node interface that objects can implement, and returns the node root field to include on the query type. +// To implement this, it takes a function to resolve an ID to an object, and to determine the type of a given object. const resolver: GraphQLTypeResolver = () => { return new GraphQLObjectType({ name: "T", @@ -170,7 +172,8 @@ const queryType = new GraphQLObjectType({ }) }); // Mutations -// mutationWithClientMutationId takes a name, input fields, output fields, and a mutation method to map from the input fields to the output fields, performing the mutation along the way. It then creates and returns a field configuration that can be used as a top-level field on the mutation type. +// mutationWithClientMutationId takes a name, input fields, output fields, and a mutation method to map from the input fields to the output fields, performing the mutation along the way. +// It then creates and returns a field configuration that can be used as a top-level field on the mutation type. const gifcm: GraphQLInputFieldConfigMap = {}; const gfcm: GraphQLFieldConfigMap = {}; mutationWithClientMutationId({ diff --git a/halogen/index.d.ts b/halogen/index.d.ts index 72d57ace51..5735737f41 100644 --- a/halogen/index.d.ts +++ b/halogen/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/yuanyan/halogen // Definitions by: Vincent Rouffiat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as react from "react"; diff --git a/halogen/test/clip-loader.tsx b/halogen/test/clip-loader.tsx index 884e1caec6..02f0dd232c 100644 --- a/halogen/test/clip-loader.tsx +++ b/halogen/test/clip-loader.tsx @@ -1,18 +1,18 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_ClipLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_ClipLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_ClipLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_ClipLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/test/fade-loader.tsx b/halogen/test/fade-loader.tsx index 63781098eb..deeae1ce95 100644 --- a/halogen/test/fade-loader.tsx +++ b/halogen/test/fade-loader.tsx @@ -1,19 +1,19 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_FadeLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_FadeLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_FadeLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_FadeLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/test/pacman-loader.tsx b/halogen/test/pacman-loader.tsx index 7ccd294918..7852026580 100644 --- a/halogen/test/pacman-loader.tsx +++ b/halogen/test/pacman-loader.tsx @@ -1,18 +1,18 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_PacmanLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_PacmanLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_PacmanLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_PacmanLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/test/rotate-loader.tsx b/halogen/test/rotate-loader.tsx index 82b4b2b380..a5325a4962 100644 --- a/halogen/test/rotate-loader.tsx +++ b/halogen/test/rotate-loader.tsx @@ -1,18 +1,18 @@ import * as React from "react"; import * as Halogen from "halogen"; -class HalogenTests_RotateLoader_withNoProps extends React.Component, {}>{ +class HalogenTests_RotateLoader_withNoProps extends React.Component, {}> { render() { return ( - ) + ); } } -class HalogenTests_RotateLoader_withAllProps extends React.Component, {}>{ +class HalogenTests_RotateLoader_withAllProps extends React.Component, {}> { render() { return ( - ) + ); } } diff --git a/halogen/tslint.json b/halogen/tslint.json index fdc7cdc370..377cc837d4 100644 --- a/halogen/tslint.json +++ b/halogen/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts b/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts new file mode 100644 index 0000000000..e6eeb6a055 --- /dev/null +++ b/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts @@ -0,0 +1,41 @@ +import Hapi = require('hapi'); +import hapiAuthJwt2 = require('hapi-auth-jwt2'); + +var server = new Hapi.Server(); +server.connection({port: 8000}); + +interface User { + id: number; + name: string; +} + +interface Users { + [id: number]: User; +} + +var users: Users = { + 1: { + id: 1, + name: 'Test User' + } +}; + +function validate(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.ValidateCallback) { + if (!users[decoded.id]) { + return callback(null, false); + } + + return callback(null, true); +} + +server.register(hapiAuthJwt2, err => { + server.auth.strategy('jwt', 'jwt', { + key: 'NeverShareYourSecret', + validateFunc: validate, + verifyOptions: { + algorithms: ['HS256'] + } + }); +}); + +server.start(); diff --git a/hapi-auth-jwt2/index.d.ts b/hapi-auth-jwt2/index.d.ts new file mode 100644 index 0000000000..1bcbbc817e --- /dev/null +++ b/hapi-auth-jwt2/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for hapi-auth-jwt2 7.0 +// Project: http://github.com/dwyl/hapi-auth-jwt2 +// Definitions by: Warren Seymour +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import {Request, Response} from 'hapi'; + +/** + * A key lookup function + * + * @param decoded the *decoded* but *unverified* JWT received from client + * @param callback the key lookup callback + */ +type KeyLookup = (decoded: any, callback: KeyLookupCallback) => void; + +/** + * Called when key lookup function has completed + * + * @param err an internal error + * @param key the secret key + * @param extraInfo any additional information that you would like + * to use in `validateFunc` which can be accessed via + * `request.plugins['hapi-auth-jwt2'].extraInfo` + */ +type KeyLookupCallback = (err: any, key: string, extraInfo?: any) => void; + +/** + * Called when Validation has completed + * + * @param err an internal error + * @param valid `true` if the JWT was valid, otherwise `false` + * @param credentials alternative credentials to be set instead of `decoded` + */ +type ValidateCallback = (err: any, valid: boolean, credentials?: any) => void; + +/** + * Options passed to `hapi.auth.strategy` when this plugin is used + */ +export interface Options { + /** + * The secret key used to check the signature of the token *or* a *key lookup function* + */ + key?: string | KeyLookup; + + /** + * The function which is run once the Token has been decoded + * + * @param decoded the *decoded* and *verified* JWT received from the client in *request.headers.authorization* + * @param request the original *request* received from the client + * @param callback the validation callback + */ + validateFunc(decoded: {}, request: Request, callback: ValidateCallback): void; + + /** + * Settings to define how tokens are verified by the jsonwebtoken library + */ + verifyOptions?: { + /** + * Ignore expired tokens + */ + ignoreExpiration?: boolean; + + /** + * Do not enforce token audience + */ + audience?: boolean; + + /** + * Do not require the issuer to be valid + */ + issuer?: boolean; + + /** + * List of allowed algorithms + */ + algorithms?: string[]; + }; + + /** + * function called to decorate the response with authentication headers + * before the response headers or payload is written + * + * @param request the Request object + * @param reply is called if an error occurred + */ + responseFunc?(request: Request, reply: (err: any, response: Response) => void): void; + + /** + * If you prefer to pass your token via url, simply add a token url + * parameter to your request or use a custom parameter by setting `urlKey. + * To disable the url parameter set urlKey to `false` or ''. + * @default 'token' + */ + urlKey?: string | boolean; + + /** + * If you prefer to set your own cookie key or your project has a cookie + * called 'token' for another purpose, you can set a custom key for your + * cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies + * set cookieKey to `false` or ''. + * @default 'token' + */ + cookieKey?: string | boolean; + + /** + * If you want to set a custom key for your header token use the + * `headerKey` option. To disable header token set headerKey to `false` or + * ''. + * @default 'authorization' + */ + headerKey?: string | boolean; + + /** + * Allow custom token type, e.g. `Authorization: 12345678` + */ + tokenType?: string; + + /** + * Set to `true` to receive the complete token (`decoded.header`, + * `decoded.payload` and `decoded.signature`) as decoded argument to key + * lookup and `verifyFunc` callbacks (*not `validateFunc`*) + * @default false + */ + complete?: boolean; +} + +export default function hapiAuthJwt2(): void; diff --git a/hapi-auth-jwt2/tsconfig.json b/hapi-auth-jwt2/tsconfig.json new file mode 100644 index 0000000000..3bbd249dc8 --- /dev/null +++ b/hapi-auth-jwt2/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", + "hapi-auth-jwt2-tests.ts" + ] +} \ No newline at end of file diff --git a/hapi-auth-jwt2/tslint.json b/hapi-auth-jwt2/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/hapi-auth-jwt2/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/hapi-decorators/hapi-decorators-tests.ts b/hapi-decorators/hapi-decorators-tests.ts index 2a05f67e4d..49a112152a 100644 --- a/hapi-decorators/hapi-decorators-tests.ts +++ b/hapi-decorators/hapi-decorators-tests.ts @@ -39,3 +39,18 @@ class TestController implements Controller { const server = new hapi.Server(); server.route(new TestController().routes()); + +@controller('/test') +class SimpleTestController implements Controller { + + foo: string; + + constructor(foo: string) { + this.foo = foo; + } + + baseUrl: string; + routes: () => hapi.IRouteConfiguration[]; +} + +server.route(new SimpleTestController('bar').routes()); diff --git a/hapi-decorators/index.d.ts b/hapi-decorators/index.d.ts index c58a1a6052..fc32ae8ad5 100644 --- a/hapi-decorators/index.d.ts +++ b/hapi-decorators/index.d.ts @@ -5,7 +5,7 @@ import * as hapi from 'hapi'; interface ControllerStatic { - new (): Controller; + new (...args: any[]): Controller; } export interface Controller { baseUrl: string; diff --git a/hapi/index.d.ts b/hapi/index.d.ts index b98e1cdf25..9d8f8f0120 100644 --- a/hapi/index.d.ts +++ b/hapi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi 13.0.0 +// Type definitions for hapi 16.0.0 // Project: http://github.com/spumko/hapi // Definitions by: Jason Swearingen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1206,7 +1206,7 @@ export class Request extends Events.EventEmitter { /** the raw request headers (references request.raw.headers).*/ headers: IDictionary; /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ - id: number; + id: string; /** request information */ info: { /** the request preferred encoding. */ diff --git a/highcharts-ng/highcharts-ng-tests.ts b/highcharts-ng/highcharts-ng-tests.ts index 0bf559061b..6f79d6e79a 100644 --- a/highcharts-ng/highcharts-ng-tests.ts +++ b/highcharts-ng/highcharts-ng-tests.ts @@ -33,7 +33,8 @@ class AppController { title: { text: 'My Awesome Chart' }, - loading: true + loading: true, + noData: 'No data here' }; constructor($timeout: ng.ITimeoutService) { var vm = this; diff --git a/highcharts-ng/index.d.ts b/highcharts-ng/index.d.ts index 123799e76c..639d21d88e 100644 --- a/highcharts-ng/index.d.ts +++ b/highcharts-ng/index.d.ts @@ -35,6 +35,8 @@ declare global { }; //function (optional) - setup some logic for the chart func?: (chart: ChartObject) => void; + //no data text (optional) to show if all series are empty + noData?: string; } //Instantiated Chart diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index 60a9fa15cb..58f2a97a5e 100644 --- a/highcharts/index.d.ts +++ b/highcharts/index.d.ts @@ -701,6 +701,13 @@ declare namespace Highcharts { * @default false */ reversed?: boolean; + /** + * If true, the first series in a stack will be drawn on top in a positive, non-reversed Y axis. If false, the first series is in the base of the stack. + * Only used for yAxis + * @default true + * @since 3.0.10 + */ + reversedStacks?: boolean; /** * Whether to show the axis line and title when the axis has no data. * @default true diff --git a/history/v2/history-tests.ts b/history/v2/history-tests.ts index 454b223e09..598d934e8d 100644 --- a/history/v2/history-tests.ts +++ b/history/v2/history-tests.ts @@ -1,4 +1,4 @@ -import { createBrowserHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' +import { createHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' import { getUserConfirmation } from 'history/lib/DOMUtils' @@ -10,7 +10,7 @@ let doSomethingAsync: () => Promise; let input = { value: "" }; { - let history = createBrowserHistory() + let history = createHistory() // Listen for changes to the current location. The // listener is called once immediately. @@ -46,7 +46,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() // Pushing a path string. history.push('/the/path') @@ -63,7 +63,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() history.listenBefore(function(location) { if (input.value !== '') return 'Are you sure you want to leave this page?' @@ -75,7 +75,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory({ + let history = createHistory({ getUserConfirmation(message, callback) { callback(window.confirm(message)) // The default behavior } @@ -83,7 +83,7 @@ let input = { value: "" }; } { - let history = useBeforeUnload(createBrowserHistory)() + let history = useBeforeUnload(createHistory)() history.listenBeforeUnload(function() { return 'Are you sure you want to leave this page?' @@ -91,7 +91,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)() + let history = useQueries(createHistory)() history.listen(function(location) { console.log(location.query) @@ -99,7 +99,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)({ + let history = useQueries(createHistory)({ parseQueryString: function(queryString) { // TODO: return a parsed version of queryString return {}; @@ -116,7 +116,7 @@ let input = { value: "" }; { // Run our app under the /base URL. - let history = useBasename(createBrowserHistory)({ + let history = useBasename(createHistory)({ basename: '/base' }) @@ -128,4 +128,4 @@ let input = { value: "" }; history.createPath('/the/path') // /base/the/path history.push('/the/path') // push /base/the/path -} \ No newline at end of file +} diff --git a/history/v2/index.d.ts b/history/v2/index.d.ts index 5f719c2f0b..6b61fa1b77 100644 --- a/history/v2/index.d.ts +++ b/history/v2/index.d.ts @@ -127,7 +127,7 @@ export interface Module { }; } -export { default as createBrowserHistory } from "./lib/createBrowserHistory"; +export { default as createHistory } from "./lib/createBrowserHistory"; export { default as createHashHistory } from "./lib/createHashHistory"; export { default as createMemoryHistory } from "./lib/createMemoryHistory"; export { default as createLocation } from "./lib/createLocation"; diff --git a/history/v3/index.d.ts b/history/v3/index.d.ts new file mode 100644 index 0000000000..7a6c8116bd --- /dev/null +++ b/history/v3/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for history 3.2 +// Project: https://github.com/mjackson/history +// Definitions by: Sergey Buturlakin , Nathan Brown , Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace History; + +export type Action = "POP" | "PUSH" | "REPLACE"; +export type BeforeUnloadHook = () => string | boolean; +export type CreateHistory = (options?: HistoryOptions & O) => History & H; +export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; + +export interface History { + listenBefore(hook: TransitionHook): () => void; + listen(listener: LocationListener): () => void; + transitionTo(location: Location): void; + push(path: LocationDescriptor): void; + replace(path: LocationDescriptor): void; + go(n: number): void; + goBack(): void; + goForward(): void; + createKey(): LocationKey; + createPath(path: LocationDescriptor): Path; + createHref(path: LocationDescriptor): Href; + createLocation(path?: LocationDescriptor, action?: Action, key?: LocationKey): Location; + getCurrentLocation(): Location; +} + +export interface HistoryOptions { + getUserConfirmation?: (message: string, callback: (result: boolean) => void) => void; + keyLength?: number; +} + +export type Hash = string; +export type Href = string; + +export interface Location { + pathname: Pathname; + search: Search; + query: Query; + state: LocationState; + action: Action; + key: LocationKey; +} + +export interface LocationDescriptorObject { + pathname?: Pathname; + search?: Search; + query?: Query; + state?: LocationState; +} + +export type LocationDescriptor = LocationDescriptorObject | Path; + +export type LocationKey = string; + +export type LocationListener = (location: Location) => void; + +export type LocationState = any; + +export type Path = string; // Pathname + Search; +export type Pathname = string; +export type Query = any; +export type Search = string; + +export type TransitionHook = (location: Location, callback: (result: any) => void) => any; + +export { default as createHistory } from "history/lib/createBrowserHistory"; +export { default as createHashHistory } from "history/lib/createHashHistory"; +export { default as createMemoryHistory, MemoryHistory, MemoryHistoryOptions } from "history/lib/createMemoryHistory"; + +export { default as useBasename, Basename, HistoryBasename, HistoryBasenameOptions } from "history/lib/useBasename"; +export { default as useBeforeUnload, HistoryBeforeUnload } from "history/lib/useBeforeUnload"; +export { default as useQueries, HistoryQueries } from "history/lib/useQueries"; + +import * as Actions from "history/lib/actions"; +export { Actions }; + +export { locationsAreEqual } from "history/lib/LocationUtils"; diff --git a/history/v3/lib/LocationUtils.d.ts b/history/v3/lib/LocationUtils.d.ts new file mode 100644 index 0000000000..1202cde9fe --- /dev/null +++ b/history/v3/lib/LocationUtils.d.ts @@ -0,0 +1,3 @@ +import { Location } from "history"; + +export function locationsAreEqual(a: Location, b: Location): boolean; diff --git a/history/v3/lib/actions.d.ts b/history/v3/lib/actions.d.ts new file mode 100644 index 0000000000..22fd29f61e --- /dev/null +++ b/history/v3/lib/actions.d.ts @@ -0,0 +1,9 @@ +export const PUSH: string; +export const REPLACE: string; +export const POP: string; + +export default { + PUSH, + REPLACE, + POP +}; diff --git a/history/v3/lib/createBrowserHistory.d.ts b/history/v3/lib/createBrowserHistory.d.ts new file mode 100644 index 0000000000..64f6bede8b --- /dev/null +++ b/history/v3/lib/createBrowserHistory.d.ts @@ -0,0 +1,5 @@ +import { CreateHistory } from "history"; + +declare const createBrowserHistory: CreateHistory; + +export default createBrowserHistory; diff --git a/history/v3/lib/createHashHistory.d.ts b/history/v3/lib/createHashHistory.d.ts new file mode 100644 index 0000000000..5150656393 --- /dev/null +++ b/history/v3/lib/createHashHistory.d.ts @@ -0,0 +1,5 @@ +import { CreateHistory } from "history"; + +declare const createHashHistory: CreateHistory; + +export default createHashHistory; diff --git a/history/v3/lib/createLocation.d.ts b/history/v3/lib/createLocation.d.ts new file mode 100644 index 0000000000..4007d98f05 --- /dev/null +++ b/history/v3/lib/createLocation.d.ts @@ -0,0 +1,2 @@ +import { Path, LocationState, Action, LocationKey, Location } from "history"; +export default function createLocation(path?: Path, state?: LocationState, action?: Action, key?: LocationKey): Location; diff --git a/history/v3/lib/createMemoryHistory.d.ts b/history/v3/lib/createMemoryHistory.d.ts new file mode 100644 index 0000000000..9ce282f164 --- /dev/null +++ b/history/v3/lib/createMemoryHistory.d.ts @@ -0,0 +1,14 @@ +import { CreateHistory, History } from "history"; + +export interface MemoryHistoryOptions { + entries?: string | [string]; + current?: string; +} + +export interface MemoryHistory { + canGo(n: number): boolean; +} + +declare const createMemoryHistory: CreateHistory; + +export default createMemoryHistory; diff --git a/history/v3/lib/useBasename.d.ts b/history/v3/lib/useBasename.d.ts new file mode 100644 index 0000000000..7b50904a56 --- /dev/null +++ b/history/v3/lib/useBasename.d.ts @@ -0,0 +1,13 @@ +import { CreateHistory, HistoryOptions } from "history"; + +export type Basename = string; + +export interface HistoryBasenameOptions { + basename?: Basename; +} + +export interface HistoryBasename { + basename?: Basename; +} + +export default function useBasename(createHistory: CreateHistory): CreateHistory; diff --git a/history/v3/lib/useBeforeUnload.d.ts b/history/v3/lib/useBeforeUnload.d.ts new file mode 100644 index 0000000000..950a7e6a17 --- /dev/null +++ b/history/v3/lib/useBeforeUnload.d.ts @@ -0,0 +1,7 @@ +import { BeforeUnloadHook, CreateHistory } from "history"; + +export interface HistoryBeforeUnload { + listenBeforeUnload(hook: BeforeUnloadHook): () => void; +} + +export default function useBeforeUnload(createHistory: CreateHistory): CreateHistory; diff --git a/history/v3/lib/useQueries.d.ts b/history/v3/lib/useQueries.d.ts new file mode 100644 index 0000000000..685c0221a6 --- /dev/null +++ b/history/v3/lib/useQueries.d.ts @@ -0,0 +1,10 @@ +import { CreateHistory, Href, LocationState, Path, Pathname, Query } from "history"; + +export interface HistoryQueries { + pushState(state: LocationState, pathname: Pathname, query?: Query): void; + replaceState(state: LocationState, pathname: Pathname, query?: Query): void; + createPath(path: Path, query?: Query): Path; + createHref(path: Path, query?: Query): Href; +} + +export default function useQueries(createHistory: CreateHistory): CreateHistory; diff --git a/history/v3/tsconfig.json b/history/v3/tsconfig.json new file mode 100644 index 0000000000..7523fbbbe9 --- /dev/null +++ b/history/v3/tsconfig.json @@ -0,0 +1,35 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "history": ["history/v3"], + "history/*": ["history/v3/*"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/actions.d.ts", + "lib/createBrowserHistory.d.ts", + "lib/createHashHistory.d.ts", + "lib/createLocation.d.ts", + "lib/createMemoryHistory.d.ts", + "lib/LocationUtils.d.ts", + "lib/useBasename.d.ts", + "lib/useBeforeUnload.d.ts", + "lib/useQueries.d.ts" + ] +} diff --git a/hoek/hoek-tests.ts b/hoek/hoek-tests.ts index 09f82a7e2a..bb2ac87389 100644 --- a/hoek/hoek-tests.ts +++ b/hoek/hoek-tests.ts @@ -50,16 +50,16 @@ console.log(copy.x.b); // results in 100 // merge(target, source, isNullOverride, isMergeArrays) -let target = { a: 1, b: 2 }; -let source = { a: 0, c: 5 }; -let source2 = { a: null, c: 5 }; +const target = { a: 1, b: 2 }; +const source = { a: 0, c: 5 }; +const source2 = { a: null, c: 5 }; Hoek.merge(target, source); // results in {a: 0, b: 2, c: 5} Hoek.merge(target, source2); // results in {a: null, b: 2, c: 5} Hoek.merge(target, source2, false); // results in {a: 1, b: 2, c: 5} -let targetArray = [1, 2, 3]; -let sourceArray = [4, 5]; +const targetArray = [1, 2, 3]; +const sourceArray = [4, 5]; Hoek.merge(targetArray, sourceArray); // results in [1, 2, 3, 4, 5] Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5] @@ -67,18 +67,18 @@ Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5] // applyToDefaults(defaults, options, isNullOverride) let defaults = { host: "localhost", port: 8000 }; -let options = { port: 8080 }; +const options = { port: 8080 }; let config = Hoek.applyToDefaults(defaults, options); // results in { host: "localhost", port: 8080 } defaults = { host: "localhost", port: 8000 }; -let options1 = { host: null, port: 8080 }; +const options1 = { host: null, port: 8080 }; config = Hoek.applyToDefaults(defaults, options1, true); // results in { host: null, port: 8080 } // applyToDefaultsWithShallow(defaults, options, keys) -let defaults1 = { +const defaults1 = { server: { host: "localhost", port: 8000 @@ -86,25 +86,25 @@ let defaults1 = { name: 'example' }; -let options2 = { server: { port: 8080 } }; +const options2 = { server: { port: 8080 } }; -let config1 = Hoek.applyToDefaultsWithShallow(defaults1, options2, ['server']); // results in { server: { port: 8080 }, name: 'example' } +const config1 = Hoek.applyToDefaultsWithShallow(defaults1, options2, ['server']); // results in { server: { port: 8080 }, name: 'example' } // deepEqual(b, a, [options]) -Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } }); //results in true -Hoek.deepEqual(Object.create(null), {}, { prototype: false }); //results in true -Hoek.deepEqual(Object.create(null), {}); //results in false +Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } }); // results in true +Hoek.deepEqual(Object.create(null), {}, { prototype: false }); // results in true +Hoek.deepEqual(Object.create(null), {}); // results in false // unique(array, key) let array = [1, 2, 2, 3, 3, 4, 5, 6]; -let newArray = Hoek.unique(array); // results in [1,2,3,4,5,6] +const newArray = Hoek.unique(array); // results in [1,2,3,4,5,6] let array1 = [{ id: 1 }, { id: 1 }, { id: 2 }]; -let newArray1 = Hoek.unique(array1, "id"); // results in [{id: 1}, {id: 2}] +const newArray1 = Hoek.unique(array1, "id"); // results in [{id: 1}, {id: 2}] // mapToObject(array, key) @@ -117,9 +117,9 @@ newObject = Hoek.mapToObject(array1, "id"); // results in {"1": true, "2": true} // intersect(array1, array2) array = [1, 2, 3]; -let array2 = [1, 4, 5]; +const array2 = [1, 4, 5]; -let newArray2 = Hoek.intersect(array, array2); // results in [1] +const newArray2 = Hoek.intersect(array, array2); // results in [1] // contain(ref, values, [options]) @@ -135,7 +135,7 @@ let array3 = [1, [2, 3]]; let flattenedArray = Hoek.flatten(array); // results in [1, 2, 3] array3 = [1, [2, 3]]; -let target1 = [4, [5]]; +const target1 = [4, [5]]; flattenedArray = Hoek.flatten(array3, target1); // results in [4, [5], 1, 2, 3] @@ -147,7 +147,7 @@ let obj = { a: { b: { c: 1 } } }; Hoek.reach(obj, chain); // returns 1 chain = 'a.b.-1'; -let obj1 = { a: { b: [2, 3, 6] } }; +const obj1 = { a: { b: [2, 3, 6] } }; Hoek.reach(obj1, chain); // returns 6 @@ -160,7 +160,7 @@ Hoek.reachTemplate(obj, '1+{a.b.c}=2'); // returns '1+1=2' // transform(obj, transform, [options]) -let source1 = { +const source1 = { address: { one: '123 main street', two: 'PO Box 1234' @@ -189,7 +189,7 @@ let result = Hoek.transform(source1, { // shallow(obj) -let shallow = Hoek.shallow({ a: { b: 1 } }); +const shallow = Hoek.shallow({ a: { b: 1 } }); // stringify(obj) @@ -199,13 +199,13 @@ Hoek.stringify(a); // Returns '[Cannot display object: Converting circular // Timer -let timerObj = new Hoek.Timer(); +const timerObj = new Hoek.Timer(); console.log("Time is now: " + timerObj.ts); console.log("Elapsed time from initialization: " + timerObj.elapsed() + 'milliseconds'); // Bench -let benchObj = new Hoek.Bench(); +const benchObj = new Hoek.Bench(); console.log("Elapsed time from initialization: " + benchObj.elapsed() + 'milliseconds'); // base64urlEncode(value) @@ -218,12 +218,12 @@ Hoek.base64urlDecode("aG9law=="); // escapeHtml(string) -let string = ' hey '; -let escapedString = Hoek.escapeHtml(string); // returns <html> hey </html> +const string = ' hey '; +const escapedString = Hoek.escapeHtml(string); // returns <html> hey </html> // escapeHeaderAttribute(attribute) -a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); //returns I said \"go w\\o me\" +a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); // returns I said \"go w\\o me\" // escapeRegex(string) @@ -231,7 +231,7 @@ a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,'); // returns 4\^f\ // assert(condition, message) -let x = 1, y = 2; +const x = 1, y = 2 as number; Hoek.assert(x === y, 'x should equal y'); // Throws 'x should equal y' @@ -243,21 +243,21 @@ Hoek.abort("Error message"); // displayStack(slice) -let stack = Hoek.displayStack(); +const stack = Hoek.displayStack(); console.log(stack); // callStack(slice) -let stack2 = Hoek.callStack(); +const stack2 = Hoek.callStack(); console.log(stack2); // nextTick(fn) -let myFn = function () { +let myFn = () => { console.log('Do this later'); }; -let nextFn = Hoek.nextTick(myFn); +const nextFn = Hoek.nextTick(myFn); nextFn(); console.log('Do this first'); @@ -269,11 +269,11 @@ console.log('Do this first'); // once(fn) -myFn = function () { +myFn = () => { console.log('Ran myFn'); }; -let onceFn = Hoek.once(myFn); +const onceFn = Hoek.once(myFn); onceFn(); // results in "Ran myFn" onceFn(); // results in undefined @@ -283,7 +283,7 @@ Hoek.ignore(); // uniqueFilename(path, extension) -let result1 = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt" +const result1 = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt" // isInteger(value) diff --git a/hoek/index.d.ts b/hoek/index.d.ts index 98e2188fec..e1ea52677b 100644 --- a/hoek/index.d.ts +++ b/hoek/index.d.ts @@ -27,8 +27,8 @@ interface ReachOptions { // Object -/** - * Clone an object or an array. +/** + * Clone an object or an array. */ export function clone(obj: T): T; diff --git a/hoek/tslint.json b/hoek/tslint.json index 192203ab54..377cc837d4 100644 --- a/hoek/tslint.json +++ b/hoek/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/howler/index.d.ts b/howler/index.d.ts index 1b6604b1aa..df3f6a363b 100644 --- a/howler/index.d.ts +++ b/howler/index.d.ts @@ -66,7 +66,7 @@ interface Howl { rate(idOrSetRate: number): this | number; rate(rate: number, id: number): this; - seek(seek?: number, id?: number): this; + seek(seek?: number, id?: number): this | number; loop(loop?: boolean, id?: number): this; playing(id?: number): boolean; duration(id?: number): number; diff --git a/html-to-text/index.d.ts b/html-to-text/index.d.ts index ce02e4bfe5..406908a6ce 100644 --- a/html-to-text/index.d.ts +++ b/html-to-text/index.d.ts @@ -39,7 +39,7 @@ interface HtmlToTextOptions { * Defines after how many chars a line break should follow in p elements. * Set to null or false to disable word-wrapping. Default: 80 */ - wordwrap?: number; + wordwrap?: number | false | null; /** * Allows to select certain tables by the class or id attribute from the HTML diff --git a/html-webpack-plugin/html-webpack-plugin-tests.ts b/html-webpack-plugin/html-webpack-plugin-tests.ts index 485f6a81bf..a84d19bea5 100644 --- a/html-webpack-plugin/html-webpack-plugin-tests.ts +++ b/html-webpack-plugin/html-webpack-plugin-tests.ts @@ -1,34 +1,24 @@ -import HtmlWebpackPlugin = require("html-webpack-plugin"); -import { Configuration } from "webpack"; +import * as HtmlWebpackPlugin from 'html-webpack-plugin'; -const a: Configuration = { - plugins: [ - new HtmlWebpackPlugin() - ] -}; +new HtmlWebpackPlugin(); -const b: Configuration = { - plugins: [ - new HtmlWebpackPlugin({ - title: "test" - }) - ] -}; +const optionsArray: HtmlWebpackPlugin.Options[] = [ + { + title: 'test', + }, + { + minify: { + caseSensitive: true, + }, + }, + { + chunksSortMode: function compare(a, b) { + return 1; + }, + }, + { + arbitrary: 'data', + }, +]; -const minify: HtmlWebpackPlugin.MinifyConfig = { - caseSensitive: true -}; - -new HtmlWebpackPlugin({ - minify -}); - -new HtmlWebpackPlugin({ - chunksSortMode: function compare(a, b) { - return 1; - } -}); - -new HtmlWebpackPlugin({ - arbitrary: "data" -}); +const plugins: HtmlWebpackPlugin[] = optionsArray.map(options => new HtmlWebpackPlugin(options)); diff --git a/html-webpack-plugin/index.d.ts b/html-webpack-plugin/index.d.ts index f34d46c8c2..792c7a2dc0 100644 --- a/html-webpack-plugin/index.d.ts +++ b/html-webpack-plugin/index.d.ts @@ -3,106 +3,86 @@ // Definitions by: Simon Hartcher , Benjamin Lim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Plugin, Webpack } from "webpack"; -import { Options } from "html-minifier"; +import { Plugin } from 'webpack'; +import { Options as HtmlMinifierOptions } from 'html-minifier'; export = HtmlWebpackPlugin; -declare class HtmlWebpackPlugin implements Plugin { - constructor(options?: HtmlWebpackPlugin.Config); - apply(thisArg: Webpack, ...args: any[]): void; +declare class HtmlWebpackPlugin extends Plugin { + constructor(options?: HtmlWebpackPlugin.Options); } declare namespace HtmlWebpackPlugin { - export type MinifyConfig = Options; + type MinifyOptions = HtmlMinifierOptions; - /** - * It is assumed that each [chunk] contains at least the properties "id" - * (containing the chunk id) and "parents" (array containing the ids of the - * parent chunks). - */ - export interface Chunk { // TODO: Import from webpack? - id: string; - parents: string[]; - [propName: string]: any; // TODO: Narrow type - } + /** + * It is assumed that each [chunk] contains at least the properties "id" + * (containing the chunk id) and "parents" (array containing the ids of the + * parent chunks). + * + * @todo define in webpack + */ + interface Chunk { + id: string; + parents: string[]; + [propName: string]: any; + } - export type ChunkComparator = (a: Chunk, b: Chunk) => number; + type ChunkComparator = (a: Chunk, b: Chunk) => number; - export interface Config { - /** - * The title to use for the generated HTML document. - */ - title?: string; + interface Options { + /** `true | false` if `true` (default) try to emit the file only if it was changed. */ + cache?: boolean; + /** + * Allows to control how chunks should be sorted before they are included to the html. + * Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'` + */ + chunksSortMode?: 'none' | 'auto' | 'dependency' | ChunkComparator; + /** Allows you to add only some chunks (e.g. only the unit-test chunk) */ + chunks?: string[]; + /** Allows you to skip some chunks (e.g. don't add the unit-test chunk) */ + excludeChunks?: string[]; + /** Adds the given favicon path to the output html. */ + favicon?: string; + /** + * The file to write the HTML to. + * Defaults to index.html. You can specify a subdirectory here too (eg: `assets/admin.html`). + */ + filename?: string; + /** + * `true | false` if `true` then append a unique webpack compilation hash to all included scripts and css files. + * This is useful for cache busting. + */ + hash?: boolean; + /** + * `true | 'head' | 'body' | false` + * Inject all assets into the given template or templateContent. + * When passing true or 'body' all javascript resources will be placed at the bottom of the body element. + * 'head' will place the scripts in the head element. + */ + inject?: 'body' | 'head' | boolean; + /** + * `{...} | false` Pass a html-minifier options object to minify the output. + * https://github.com/kangax/html-minifier#options-quick-reference + */ + minify?: false | MinifyOptions; + /** `true | false` if `true` (default) errors details will be written into the html page. */ + showErrors?: boolean; + /** Webpack require path to the template. Please see the docs for details. */ + template?: string; + /** The title to use for the generated HTML document. */ + title?: string; + /** `true | false` If `true` render the link tags as self-closing, XHTML compliant. Default is `false` */ + xhtml?: boolean; + /** + * In addition to the options actually used by this plugin, you can use this hash to pass arbitrary data through + * to your template. + */ + [option: string]: any; + } - /** - * The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: `assets/admin.html`). - */ - filename?: string; - - /** - * Webpack require path to the template. Please see the docs for details. - */ - template?: string; - - /** - * `true | 'head' | 'body' | false` - * - * Inject all assets into the given template or templateContent - When passing true or 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element. - */ - inject?: boolean | "head" | "body"; - - /** - * Adds the given favicon path to the output html. - */ - favicon?: string; - - /** - * `{...} | false` Pass a html-minifier options object to minify the output. - * - * https://github.com/kangax/html-minifier#options-quick-reference - */ - minify?: MinifyConfig | false; - - /** - * `true | false` if `true` then append a unique webpack compilation hash to all included scripts and css files. This is useful for cache busting. - */ - hash?: boolean; - - /** - * `true | false` if `true` (default) try to emit the file only if it was changed. - */ - cache?: boolean; - - /** - * `true | false` if `true` (default) errors details will be written into the html page. - */ - showErrors?: boolean; - - /** - * Allows you to add only some chunks (e.g. only the unit-test chunk) - */ - chunks?: string[]; - - /** - * Allows to control how chunks should be sorted before they are included to the html. Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'` - */ - chunksSortMode?: "none" | "auto" | "dependency" | ChunkComparator; - - /** - * Allows you to skip some chunks (e.g. don't add the unit-test chunk) - */ - excludeChunks?: string[]; - - /** - * `true | false` If `true` render the link tags as self-closing, XHTML compliant. Default is `false` - */ - xhtml?: boolean; - - /** - * In addition to the options actually used by this plugin, you can use - * this hash to pass arbitrary data through to your template. - */ - [option: string]: any; - } + /** @deprecated use MinifyOptions */ + type MinifyConfig = MinifyOptions; + /** @deprecated use Options */ + type Config = Options; } diff --git a/html-webpack-template/html-webpack-template-tests.ts b/html-webpack-template/html-webpack-template-tests.ts index c24a9506d3..4407af69eb 100644 --- a/html-webpack-template/html-webpack-template-tests.ts +++ b/html-webpack-template/html-webpack-template-tests.ts @@ -1,65 +1,65 @@ -import HtmlWebpackPlugin = require('html-webpack-plugin'); -import template = require('html-webpack-template'); +import * as HtmlWebpackPlugin from 'html-webpack-plugin'; +import * as template from 'html-webpack-template'; -const configs: Array = [ - { - // Required - inject: false, - template, - // template: 'node_modules/html-webpack-template/index.ejs', +const optionsArray: template.Options[] = [ + { + /** Required */ + inject: false, + template, + // template: 'node_modules/html-webpack-template/index.ejs', - // Optional - appMountId: 'app', - appMountIds: [ - 'root0', - 'root1', - ], - baseHref: 'http://example.com/awesome', - devServer: 'http://localhost:3001', - googleAnalytics: { - trackingId: 'UA-XXXX-XX', - pageViewOnLoad: true, - }, - links: [ - 'https://fonts.googleapis.com/css?family=Roboto', - { - href: '/apple-touch-icon.png', - rel: 'apple-touch-icon', - sizes: '180x180', - }, - { - href: '/favicon-32x32.png', - rel: 'icon', - sizes: '32x32', - type: 'image/png', - }, - ], - meta: [ - { - description: 'A better default template for html-webpack-plugin.', - }, - ], - mobile: true, - inlineManifestWebpackName: 'webpackManifest', - scripts: [ - 'http://example.com/somescript.js', - { - src: '/myModule.js', - type: 'module', - }, - ], - window: { - env: { - apiHost: 'http://myapi.com/api/v1', - }, - }, + /** Optional */ + appMountId: 'app', + appMountIds: [ + 'root0', + 'root1', + ], + baseHref: 'http://example.com/awesome', + devServer: 'http://localhost:3001', + googleAnalytics: { + trackingId: 'UA-XXXX-XX', + pageViewOnLoad: true, + }, + links: [ + 'https://fonts.googleapis.com/css?family=Roboto', + { + href: '/apple-touch-icon.png', + rel: 'apple-touch-icon', + sizes: '180x180', + }, + { + href: '/favicon-32x32.png', + rel: 'icon', + sizes: '32x32', + type: 'image/png', + }, + ], + meta: [ + { + description: 'A better default template for html-webpack-plugin.', + }, + ], + mobile: true, + inlineManifestWebpackName: 'webpackManifest', + scripts: [ + 'http://example.com/somescript.js', + { + src: '/myModule.js', + type: 'module', + }, + ], + window: { + env: { + apiHost: 'http://myapi.com/api/v1', + }, + }, - // And any other config options from html-webpack-plugin: - // https://github.com/ampedandwired/html-webpack-plugin#configuration - title: 'My App', - }, + /** + * And any other config options from html-webpack-plugin: + * https://github.com/ampedandwired/html-webpack-plugin#configuration + */ + title: 'My App', + }, ]; -const plugins: Array = configs.map(config => - new HtmlWebpackPlugin(config) -); +const plugins: HtmlWebpackPlugin[] = optionsArray.map(options => new HtmlWebpackPlugin(options)); diff --git a/html-webpack-template/index.d.ts b/html-webpack-template/index.d.ts index e224e96296..f1b57fa331 100644 --- a/html-webpack-template/index.d.ts +++ b/html-webpack-template/index.d.ts @@ -3,94 +3,74 @@ // Definitions by: Benjamin Lim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Config as HtmlWebpackPluginConfig } from 'html-webpack-plugin'; +import { Options as HtmlWebpackPluginOptions } from 'html-webpack-plugin'; export = HtmlWebpackTemplate; declare const HtmlWebpackTemplate: string; declare namespace HtmlWebpackTemplate { - export interface GoogleAnalyticsConfig { - trackingId: string; - // Log a pageview event after the analytics code loads. - pageViewOnLoad?: boolean; - } + interface GoogleAnalyticsOptions { + /** Log a pageview event after the analytics code loads. */ + pageViewOnLoad?: boolean; + trackingId: string; + } - export interface Attributes { - [name: string]: any; - } + interface Attributes { + [name: string]: any; + } - type Resource = string | Attributes; + type Resource = string | Attributes; - /** - * string: value is assigned to the href attribute and the rel attribute is - * set to "stylesheet" - * - * object: properties and values are used as the attribute names and values, - * respectively: - */ - export type Link = Resource; + /** + * string: value is assigned to the href attribute and the rel attribute is set to "stylesheet" + * object: properties and values are used as the attribute names and values, respectively. + */ + type Link = Resource; - /** - * string: value is assigned to the src attribute and the type attribute is - * set to "text/javascript"; - * - * object: properties and values are used as the attribute names and values, - * respectively. - */ - export type Script = Resource; + /** + * string: value is assigned to the src attribute and the type attribute is set to "text/javascript". + * object: properties and values are used as the attribute names and values, respectively. + */ + type Script = Resource; - export interface Config extends HtmlWebpackPluginConfig { - /** - * Set to false. Controls asset addition to the template. This template - * takes care of that. - */ - inject: false; + interface Options extends HtmlWebpackPluginOptions { + /** The

element id on which you plan to mount a JavaScript app. */ + appMountId?: string; + /** An array of application element ids. */ + appMountIds?: string[]; + /** + * Adjust the URL for relative URLs in the document (MDN). + * https://developer.mozilla.org/en/docs/Web/HTML/Element/base + */ + baseHref?: string; + /** Insert the webpack-dev-server hot reload script at this host:port/path; e.g., http://localhost:3000. */ + devServer?: string; + /** Track usage of your site via Google Analytics. */ + googleAnalytics?: GoogleAnalyticsOptions; + /** Set to false. Controls asset addition to the template. This template takes care of that. */ + inject: false; + /** + * For use with inline-manifest-webpack-plugin. + * https://github.com/szrenwei/inline-manifest-webpack-plugin + */ + inlineManifestWebpackName?: string; + /** Array of elements. */ + links?: Link[]; + /** Array of objects containing key value pairs to be included as meta tags. */ + meta?: Attributes[]; + /** Sets appropriate meta tag for page scaling. */ + mobile?: boolean; + /** Array of external script imports to include on page. */ + scripts?: Script[]; + /** Specify this module's index.ejs file. */ + template: string; + /** Object that defines data you need to bootstrap a JavaScript app. */ + window?: {}; + } - // Specify this module's index.ejs file. - template: string; - - // The
element id on which you plan to mount a JavaScript app. - appMountId?: string; - - // An array of application element ids. - appMountIds?: string[]; - - /** - * Adjust the URL for relative URLs in the document (MDN). - * https://developer.mozilla.org/en/docs/Web/HTML/Element/base - */ - baseHref?: string; - - /** - * Insert the webpack-dev-server hot reload script at this - * host:port/path; e.g., http://localhost:3000. - */ - devServer?: string; - - // Track usage of your site via Google Analytics. - googleAnalytics?: GoogleAnalyticsConfig; - - // Array of elements. - links?: Link[]; - - // Array of objects containing key value pairs to be included as meta tags. - meta?: Attributes[]; - - // Sets appropriate meta tag for page scaling. - mobile?: boolean; - - /** - * For use with inline-manifest-webpack-plugin. - * - * https://github.com/szrenwei/inline-manifest-webpack-plugin - */ - inlineManifestWebpackName?: string; - - // Array of external script imports to include on page. - scripts?: Script[]; - - // Object that defines data you need to bootstrap a JavaScript app. - window?: {}; - } + /** @deprecated use GoogleAnalyticsOptions */ + type GoogleAnalyticsConfig = GoogleAnalyticsOptions; + /** @deprecated use Options */ + type Config = Options; } diff --git a/http-assert/http-assert-tests.ts b/http-assert/http-assert-tests.ts index b95561b635..bfb12e650a 100644 --- a/http-assert/http-assert-tests.ts +++ b/http-assert/http-assert-tests.ts @@ -4,8 +4,8 @@ import { HttpError } from 'http-errors'; try { httpAssert.equal('hello', 'hello'); httpAssert(false, 401, 'authentication failed'); -} catch(err) { - console.log((err).status); - console.log((err).message); - console.log((err).expose); +} catch (err) { + console.log(( err).status); + console.log(( err).message); + console.log(( err).expose); } diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index af06b3ebc6..e8c12126b4 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -26,6 +26,7 @@ console.log(err.message); console.log(err.status); console.log(err.statusCode); console.log(err.expose); +console.log(err.headers); // createError(status, msg) var err = createError(404, 'LOL'); diff --git a/http-errors/index.d.ts b/http-errors/index.d.ts index e70d1d973c..176703f23f 100644 --- a/http-errors/index.d.ts +++ b/http-errors/index.d.ts @@ -11,6 +11,9 @@ declare module 'http-errors' { status: number; statusCode: number; expose: boolean; + headers?: { + [key: string]: string + }; } type HttpErrorConstructor = new(msg?: string) => HttpError; diff --git a/hyco-ws/hyco-ws-tests.ts b/hyco-ws/hyco-ws-tests.ts new file mode 100644 index 0000000000..05b500d81c --- /dev/null +++ b/hyco-ws/hyco-ws-tests.ts @@ -0,0 +1,21 @@ +import * as WebSocket from 'ws'; +import * as AzureRelay from 'hyco-ws'; + +const wss = AzureRelay.createRelayedServer( + { + server: AzureRelay.createRelayListenUri('uri_namespace', 'uri_path'), + token: AzureRelay.createRelayToken( + 'http://exampleurl.com}', + 'key_rule', + 'key') + }, + (ws: WebSocket) => { + console.log('New connection accepted'); + ws.onmessage = (event: any) => { + console.log('New message!!'); + }; + }); + +wss.on('error', (err: any) => { + console.log('error' + err); +}); \ No newline at end of file diff --git a/hyco-ws/index.d.ts b/hyco-ws/index.d.ts new file mode 100644 index 0000000000..053c7fba18 --- /dev/null +++ b/hyco-ws/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for hyco-ws 1.0 +// Project: https://github.com/Azure/azure-relay-node +// Definitions by: Manuel Rodrigo Cabello +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as WebSocket from 'ws'; + +export class HybridConnectionWebSocketServer extends NodeJS.EventEmitter { + constructor(options: any); + close(callback: () => void): void; + listenUri: string; + closeRequested: boolean; + options: any; + path: string; + clients: WebSocket[]; + controlChannel: WebSocket; +} + +export function createRelayedServer(options: any, fn: (ws: WebSocket) => void): HybridConnectionWebSocketServer; +export function relayedConnect(address: string, fn: () => void): WebSocket; +export function createRelayToken(uri: string, key_name: string, key: string, expiry?: number): string; +export function appendRelayToken(uri: string, key_name: string, key: string, expiry?: number): string; +export function createRelayBaseUri(serviceBusNamespace: string, path: string): string; +export function createRelaySendUri(serviceBusNamespace: string, path: string, token?: any, id?: any): string; +export function createRelayListenUri(serviceBusNamespace: string, path: string, token?: any, id?: any): string; \ No newline at end of file diff --git a/hyco-ws/tsconfig.json b/hyco-ws/tsconfig.json new file mode 100644 index 0000000000..a625ff1bab --- /dev/null +++ b/hyco-ws/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "experimentalDecorators": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hyco-ws-tests.ts" + ] +} \ No newline at end of file diff --git a/hyco-ws/tslint.json b/hyco-ws/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/hyco-ws/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/i18next/index.d.ts b/i18next/index.d.ts index b0cb04b267..958bff12a6 100644 --- a/i18next/index.d.ts +++ b/i18next/index.d.ts @@ -63,8 +63,8 @@ declare namespace i18n { lowerCaseLng?: boolean; load?: string preload?: string[]; - keySeparator?: string; - nsSeparator?: string; + keySeparator?: string | false; + nsSeparator?: string | false; pluralSeparator?: string; contextSeparator?: string; saveMissing?: boolean; diff --git a/indent-string/indent-string-tests.ts b/indent-string/indent-string-tests.ts index ea473a2814..6e5e764cb4 100644 --- a/indent-string/indent-string-tests.ts +++ b/indent-string/indent-string-tests.ts @@ -1,9 +1,9 @@ import indentString = require('indent-string'); indentString('Unicorns\nRainbows', 4); -//=> ' Unicorns' -//=> ' Rainbows' +// => ' Unicorns' +// => ' Rainbows' indentString('Unicorns\nRainbows', 4, '♥'); -//=> '♥♥♥♥Unicorns' -//=> '♥♥♥♥Rainbows' \ No newline at end of file +// => '♥♥♥♥Unicorns' +// => '♥♥♥♥Rainbows' \ No newline at end of file diff --git a/inert/tslint.json b/inert/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/inert/tslint.json +++ b/inert/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/is-absolute-url/is-absolute-url-tests.ts b/is-absolute-url/is-absolute-url-tests.ts index 8ddf3e2514..47c5f007ed 100644 --- a/is-absolute-url/is-absolute-url-tests.ts +++ b/is-absolute-url/is-absolute-url-tests.ts @@ -1,10 +1,10 @@ import isAbsoluteUrl = require('is-absolute-url'); isAbsoluteUrl('http://sindresorhus.com/foo/bar'); -//=> true +// => true isAbsoluteUrl('//sindresorhus.com'); -//=> false +// => false isAbsoluteUrl('foo/bar'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-archive/is-archive-tests.ts b/is-archive/is-archive-tests.ts index 30be8dc06e..332deae7ec 100644 --- a/is-archive/is-archive-tests.ts +++ b/is-archive/is-archive-tests.ts @@ -1,7 +1,7 @@ import isArchive = require('is-archive'); isArchive('src/unicorn.zip'); -//=> true +// => true isArchive('src/unicorn.txt'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-array/index.d.ts b/is-array/index.d.ts new file mode 100644 index 0000000000..f57afcbd50 --- /dev/null +++ b/is-array/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for is-array 1.0 +// Project: https://github.com/retrofox/is-array +// Definitions by: Pine Mizune +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isArray; +declare function isArray(val?: any): val is any[]; diff --git a/is-array/is-array-tests.ts b/is-array/is-array-tests.ts new file mode 100644 index 0000000000..9a8e252e05 --- /dev/null +++ b/is-array/is-array-tests.ts @@ -0,0 +1,13 @@ +import isArray = require('is-array'); + +isArray(); +isArray(null); +isArray(1); +isArray(true); +isArray([]); +isArray({}); + +var x = {} +if (isArray(x)) { + x.push(0); +} diff --git a/is-array/tsconfig.json b/is-array/tsconfig.json new file mode 100644 index 0000000000..2d027ece6d --- /dev/null +++ b/is-array/tsconfig.json @@ -0,0 +1,23 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-array-tests.ts" + ] +} diff --git a/is-array/tslint.json b/is-array/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/is-array/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/is-binary-path/is-binary-path-tests.ts b/is-binary-path/is-binary-path-tests.ts index 967346a35a..43505a5b32 100644 --- a/is-binary-path/is-binary-path-tests.ts +++ b/is-binary-path/is-binary-path-tests.ts @@ -1,5 +1,5 @@ import isBinaryPath = require("is-binary-path"); -let a: boolean = isBinaryPath("src/unicorn.png"); +const a: boolean = isBinaryPath("src/unicorn.png"); -let b: boolean = isBinaryPath("src/unicorn.txt"); \ No newline at end of file +const b: boolean = isBinaryPath("src/unicorn.txt"); \ No newline at end of file diff --git a/is-compressed/is-compressed-tests.ts b/is-compressed/is-compressed-tests.ts index 11a2e67294..7720b334a4 100644 --- a/is-compressed/is-compressed-tests.ts +++ b/is-compressed/is-compressed-tests.ts @@ -1,7 +1,7 @@ import isCompressed = require('is-compressed'); isCompressed('src/unicorn.zip'); -//=> true +// => true isCompressed('src/unicorn.txt'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-relative-url/is-relative-url-tests.ts b/is-relative-url/is-relative-url-tests.ts index 293c621872..8835694624 100644 --- a/is-relative-url/is-relative-url-tests.ts +++ b/is-relative-url/is-relative-url-tests.ts @@ -1,10 +1,10 @@ import isRelativeUrl = require('is-relative-url'); isRelativeUrl('foo/bar'); -//=> true +// => true isRelativeUrl('http://sindresorhus.com/foo/bar'); -//=> false +// => false isRelativeUrl('//sindresorhus.com'); -//=> true \ No newline at end of file +// => true \ No newline at end of file diff --git a/is-root-path/is-root-path-tests.ts b/is-root-path/is-root-path-tests.ts index 0a577aee5a..3e050cd162 100644 --- a/is-root-path/is-root-path-tests.ts +++ b/is-root-path/is-root-path-tests.ts @@ -1,7 +1,7 @@ import isRootPath = require('is-root-path'); isRootPath('/'); -//=> true +// => true isRootPath('/Users'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-root/is-root-tests.ts b/is-root/is-root-tests.ts index 42fc3ee4f3..b53d07a0ac 100644 --- a/is-root/is-root-tests.ts +++ b/is-root/is-root-tests.ts @@ -2,4 +2,4 @@ import isRoot = require('is-root'); isRoot(); -//=> true \ No newline at end of file +// => true \ No newline at end of file diff --git a/is-text-path/is-text-path-tests.ts b/is-text-path/is-text-path-tests.ts index cd71933ec2..f7c417fe51 100644 --- a/is-text-path/is-text-path-tests.ts +++ b/is-text-path/is-text-path-tests.ts @@ -1,7 +1,7 @@ import isTextPath = require('is-text-path'); isTextPath('src/unicorn.txt'); -//=> true +// => true isTextPath('src/unicorn.png'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/isomorphic-fetch/index.d.ts b/isomorphic-fetch/index.d.ts index 452e95e871..00b40fe911 100644 --- a/isomorphic-fetch/index.d.ts +++ b/isomorphic-fetch/index.d.ts @@ -3,182 +3,115 @@ // Definitions by: Todd Lucas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | - "track" | "video"; -type RequestDestination = "" | "document" | "embed" | "font" | "image" | - "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | - "sharedworker" | "style" | "worker" | "xslt"; -type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestCache = - "default" | "no-store" | "reload" | "no-cache" | "force-cache" | - "only-if-cached"; -type RequestRedirect = "follow" | "error" | "manual"; +interface ForEachCallback { + (keyId: any, status: string): void; +} -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | - "opaqueredirect"; - -type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | - "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | - "strict-origin-when-cross-origin" | "unsafe-url"; - -interface HeadersInterface { +interface Headers { append(name: string, value: string): void; delete(name: string): void; + forEach(callback: ForEachCallback): void; get(name: string): string | null; - getAll(name: string): string[]; has(name: string): boolean; set(name: string, value: string): void; - - // TODO: iterable; - forEach(callback: (value: string, index: number, headers: HeadersInterface) => void, thisArg?: any): void; - // NOTE: The following are supported by whatwg-fetch but not node-fetch. - // entries(): IterableIterator<[string, string]>; - // keys(): IterableIterator; - // values(): IterableIterator; } -type HeadersInit = Headers | string[] | { [index: string]: string }; - -declare class Headers implements HeadersInterface { - constructor(init?: HeadersInit); - append(name: string, value: string): void; - delete(name: string): void; - get(name: string): string | null; - getAll(name: string): string[]; - has(name: string): boolean; - set(name: string, value: string): void; - - forEach(callback: (value: string, index: number, headers: HeadersInterface) => void, thisArg?: any): void; +declare var Headers: { + prototype: Headers; + new(init?: any): Headers; } -interface BodyInterface { - bodyUsed: boolean; +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +interface Body { + readonly bodyUsed: boolean; arrayBuffer(): Promise; blob(): Promise; - formData(): Promise; json(): Promise; - json(): Promise; text(): Promise; } -declare class Body implements BodyInterface { - bodyUsed: boolean; - arrayBuffer(): Promise; - blob(): Promise; - formData(): Promise; - json(): Promise; - json(): Promise; - text(): Promise; -} - -interface RequestInterface extends BodyInterface { - method: string; - url: string; - headers: HeadersInterface; - - type: RequestType; - destination: RequestDestination; - referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode: RequestMode; - credentials: RequestCredentials; - cache: RequestCache; - redirect?: RequestRedirect; - integrity?: string; - - clone(): RequestInterface; -} - -type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; - interface RequestInit { method?: string; - headers?: HeadersInit; - body?: BodyInit; + headers?: any; + body?: any; referrer?: string; - referrerPolicy?: ReferrerPolicy; - mode?: RequestMode; - credentials?: RequestCredentials; - cache?: RequestCache; - redirect?: RequestRedirect; + referrerPolicy?: string; + mode?: string; + credentials?: string; + cache?: string; + redirect?: string; integrity?: string; - window?: any; // can only be set to null + keepalive?: boolean; + window?: any; } -type RequestInfo = RequestInterface | string; - -declare class Request extends Body implements RequestInterface { - constructor(input: RequestInfo, init?: RequestInit); - - method: string; - url: string; - headers: HeadersInterface; - - type: RequestType; - destination: RequestDestination; - referrer: string; - referrerPolicy: ReferrerPolicy; - mode: RequestMode; - credentials: RequestCredentials; - cache: RequestCache; - redirect: RequestRedirect; - integrity: string; - - clone(): RequestInterface; +interface Request extends Object, Body { + readonly cache: string; + readonly credentials: string; + readonly destination: string; + readonly headers: Headers; + readonly integrity: string; + readonly keepalive: boolean; + readonly method: string; + readonly mode: string; + readonly redirect: string; + readonly referrer: string; + readonly referrerPolicy: string; + readonly type: string; + readonly url: string; + clone(): Request; } -interface ResponseInterface extends BodyInterface { - type: ResponseType; - - url: string; - redirected: boolean; - status: number; - statusText: string; - ok: boolean; - headers: HeadersInterface; - // size: number; - // timeout: number; - body: any; - trailer: Promise; - - clone(): ResponseInterface; +declare var Request: { + prototype: Request; + new(input: Request | string, init?: RequestInit): Request; } -type ResponseBodyInit = BodyInit; +interface ReadableStream { + readonly locked: boolean; + cancel(): Promise; +} interface ResponseInit { status?: number; statusText?: string; - headers?: HeadersInit; + headers?: any; } -declare class Response extends Body implements ResponseInterface { - constructor(body?: ResponseBodyInit, init?: ResponseInit); - - static redirect(url: string, status?: number): ResponseInterface; - static error(): ResponseInterface; - - type: ResponseType; - - url: string; - redirected: boolean; - status: number; - statusText: string; - ok: boolean; - headers: HeadersInterface; - body: any; - trailer: Promise; - - clone(): ResponseInterface; +interface Response extends Object, Body { + readonly body: ReadableStream | null; + readonly headers: Headers; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly type: string; + readonly url: string; + clone(): Response; } -interface Window { - fetch(url: RequestInfo, init?: RequestInit): Promise; +declare var Response: { + prototype: Response; + new(body?: any, init?: ResponseInit): Response; } -declare var fetch: typeof window.fetch; +interface GlobalFetch { + fetch(input: Request | string, init?: RequestInit): Promise; +} + +interface Window extends GlobalFetch { +} + +declare function fetch(input: Request | string, init?: RequestInit): Promise; declare module "isomorphic-fetch" { - export = fetch; + namespace _fetch { } + const _fetch: typeof fetch; + export = _fetch; } diff --git a/isomorphic-fetch/isomorphic-fetch-tests.ts b/isomorphic-fetch/isomorphic-fetch-tests.ts index 78f0da930a..ac1a008350 100644 --- a/isomorphic-fetch/isomorphic-fetch-tests.ts +++ b/isomorphic-fetch/isomorphic-fetch-tests.ts @@ -6,7 +6,7 @@ function test_isomorphicFetchTestCases_ambient() { expectSuccess(fetch('http://localhost:3000/good'), 'Good response'); fetch('http://localhost:3000/bad') - .then((response: ResponseInterface) => { + .then((response: Response) => { return response.text(); }) .catch((err) => { @@ -17,7 +17,7 @@ function test_isomorphicFetchTestCases_commonjs() { expectSuccess(fetchImportedViaCommonJS('http://localhost:3000/good'), 'Good response'); fetchImportedViaCommonJS('http://localhost:3000/bad') - .then((response: ResponseInterface) => { + .then((response: Response) => { return response.text(); }) .catch((err) => { @@ -28,7 +28,7 @@ function test_isomorphicFetchTestCases_es6() { expectSuccess(fetchImportedViaES6Module('http://localhost:3000/good'), 'Good response'); fetchImportedViaES6Module('http://localhost:3000/bad') - .then((response: ResponseInterface) => { + .then((response: Response) => { return response.text(); }) .catch((err) => { @@ -135,8 +135,8 @@ function test_whatwgTestCases_es6() { expectSuccess(fetchImportedViaES6Module(request), 'Post response:'); } -function expectSuccess(promise: Promise, responseText: string) { - promise.then((response: ResponseInterface) => { +function expectSuccess(promise: Promise, responseText: string) { + promise.then((response: Response) => { return response.text(); }) .then((text: string) => { diff --git a/jalaali-js/tslint.json b/jalaali-js/tslint.json index fdc7cdc370..377cc837d4 100644 --- a/jalaali-js/tslint.json +++ b/jalaali-js/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/japanese-holidays/index.d.ts b/japanese-holidays/index.d.ts new file mode 100644 index 0000000000..e8102de87d --- /dev/null +++ b/japanese-holidays/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for japanese-holidays 1.0 +// Project: https://github.com/osamutake/japanese-holidays-js +// Definitions by: syamatoo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function isHoliday(date: Date, furikae?: boolean): string | undefined; +export function isHolidayAt(date: Date, furikae?: boolean): string | undefined; +export function getHolidaysOf(year: number, furikae?: boolean): Holiday[]; + +export interface Holiday { + month: number; + date: number; + name: string; +} diff --git a/japanese-holidays/japanese-holidays-tests.ts b/japanese-holidays/japanese-holidays-tests.ts new file mode 100644 index 0000000000..32f760360e --- /dev/null +++ b/japanese-holidays/japanese-holidays-tests.ts @@ -0,0 +1,22 @@ +import {isHoliday, isHolidayAt, getHolidaysOf} from 'japanese-holidays'; + +const date = new Date(2017, 0, 9); +const h: string | undefined = isHoliday(date); +if (h !== undefined) { + h.charAt(0); +} + +const noFurikae: string | undefined = isHoliday(date, false); + +const hAt = isHolidayAt(date); +if (hAt !== undefined) { + hAt.charAt(0); +} + +isHolidayAt(date, false); + +const holidays = getHolidaysOf(2017); +const first = holidays[0]; +const n: string = first.name; +const m: number = first.month; +const d: number = first.date; diff --git a/japanese-holidays/tsconfig.json b/japanese-holidays/tsconfig.json new file mode 100644 index 0000000000..11826ce711 --- /dev/null +++ b/japanese-holidays/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", + "japanese-holidays-tests.ts" + ] +} \ No newline at end of file diff --git a/japanese-holidays/tslint.json b/japanese-holidays/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/japanese-holidays/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jasmine-ajax/index.d.ts b/jasmine-ajax/index.d.ts index 72a3348afc..6ec4020d00 100644 --- a/jasmine-ajax/index.d.ts +++ b/jasmine-ajax/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for jasmine-ajax 3.1.1 +// Type definitions for jasmine-ajax 3.1 // Project: https://github.com/jasmine/jasmine-ajax // Definitions by: Louis Grignon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 interface JasmineAjaxResponse { status?: number; @@ -74,7 +75,7 @@ declare class MockAjax { stubRequest(url: RegExp, data?: string, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: string, method?: string): JasmineAjaxRequestStub; - + stubRequest(url: RegExp, data?: RegExp, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: RegExp, method?: string): JasmineAjaxRequestStub; diff --git a/jasmine-ajax/jasmine-ajax-tests.ts b/jasmine-ajax/jasmine-ajax-tests.ts index 890a724420..d94b205d13 100644 --- a/jasmine-ajax/jasmine-ajax-tests.ts +++ b/jasmine-ajax/jasmine-ajax-tests.ts @@ -8,31 +8,31 @@ declare function getJasmineRequireObj(); -describe('StubTracker', function() { - beforeEach(function() { +describe('StubTracker', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxStubTracker(); this.tracker = new Constructor(); }); - it('finds nothing if no stubs are added', function() { + it('finds nothing if no stubs are added', () => { expect(this.tracker.findStub()).toBeUndefined(); }); - it('finds an added stub', function() { - var stub = { matches: function() { return true; } }; + it('finds an added stub', () => { + var stub = { matches: () => true }; this.tracker.addStub(stub); expect(this.tracker.findStub()).toBe(stub); }); - it('skips an added stub that does not match', function() { - var stub = { matches: function() { return false; } }; + it('skips an added stub that does not match', () => { + var stub = { matches: () => false }; this.tracker.addStub(stub); expect(this.tracker.findStub()).toBeUndefined(); }); - it('passes url, data, and method to the stub', function() { + it('passes url, data, and method to the stub', () => { var stub = { matches: jasmine.createSpy('matches') }; this.tracker.addStub(stub); @@ -41,7 +41,7 @@ describe('StubTracker', function() { expect(stub.matches).toHaveBeenCalledWith('url', 'data', 'method'); }); - it('can clear out all stubs', function() { + it('can clear out all stubs', () => { var stub = { matches: jasmine.createSpy('matches') }; this.tracker.addStub(stub); @@ -57,10 +57,10 @@ describe('StubTracker', function() { expect(stub.matches).not.toHaveBeenCalled(); }); - it('uses the most recently added stub that matches', function() { - var stub1 = { matches: function() { return true; } }; - var stub2 = { matches: function() { return true; } }; - var stub3 = { matches: function() { return false; } }; + it('uses the most recently added stub that matches', () => { + var stub1 = { matches: () => true }; + var stub2 = { matches: () => false }; + var stub3 = { matches: () => false }; this.tracker.addStub(stub1); this.tracker.addStub(stub2); @@ -70,22 +70,22 @@ describe('StubTracker', function() { }); }); -describe('FakeRequest', function() { - beforeEach(function() { +describe('FakeRequest', () => { + beforeEach(() => { this.requestTracker = { track: jasmine.createSpy('trackRequest') }; - this.stubTracker = { findStub: function() { } }; + this.stubTracker = { findStub() { } }; var parserInstance = this.parserInstance = jasmine.createSpy('parse'); - this.paramParser = { findParser: function() { return { parse: parserInstance }; } }; + this.paramParser = { findParser: () => ({ parse: parserInstance }) }; var eventBus = this.fakeEventBus = { addEventListener: jasmine.createSpy('addEventListener'), trigger: jasmine.createSpy('trigger'), removeEventListener: jasmine.createSpy('removeEventListener') }; - this.eventBusFactory = function() { + this.eventBusFactory = () => { return eventBus; }; this.fakeGlobal = { - XMLHttpRequest: function() { + XMLHttpRequest: () => { this.extraAttribute = 'my cool attribute'; }, DOMParser: window['DOMParser'], @@ -94,13 +94,13 @@ describe('FakeRequest', function() { this.FakeRequest = getJasmineRequireObj().AjaxFakeRequest(this.eventBusFactory)(this.fakeGlobal, this.requestTracker, this.stubTracker, this.paramParser); }); - it('extends from the global XMLHttpRequest', function() { + it('extends from the global XMLHttpRequest', () => { var request = new this.FakeRequest(); expect(request.extraAttribute).toEqual('my cool attribute'); }); - it('skips XMLHttpRequest attributes that IE does not want copied', function() { + it('skips XMLHttpRequest attributes that IE does not want copied', () => { // use real window here so it will correctly go red on IE if it breaks var FakeRequest = getJasmineRequireObj().AjaxFakeRequest(this.eventBusFactory)(window, this.requestTracker, this.stubTracker, this.paramParser); var request = new FakeRequest(); @@ -110,20 +110,20 @@ describe('FakeRequest', function() { expect(request.statusText).toBeUndefined(); }); - it('tracks the request', function() { + it('tracks the request', () => { var request = new this.FakeRequest(); expect(this.requestTracker.track).toHaveBeenCalledWith(request); }); - it('has default request headers and override mime type', function() { + it('has default request headers and override mime type', () => { var request = new this.FakeRequest(); expect(request.requestHeaders).toEqual({}); expect(request.overriddenMimeType).toBeNull(); }); - it('saves request information when opened', function() { + it('saves request information when opened', () => { var request = new this.FakeRequest(); request.open('METHOD', 'URL', 'ignore_async', 'USERNAME', 'PASSWORD'); @@ -133,7 +133,7 @@ describe('FakeRequest', function() { expect(request.password).toEqual('PASSWORD'); }); - it('saves an override mime type', function() { + it('saves an override mime type', () => { var request = new this.FakeRequest(); request.overrideMimeType('application/text; charset: utf-8'); @@ -141,7 +141,7 @@ describe('FakeRequest', function() { expect(request.overriddenMimeType).toBe('application/text; charset: utf-8'); }); - it('saves request headers', function() { + it('saves request headers', () => { var request = new this.FakeRequest(); request.setRequestHeader('X-Header-1', 'value1'); @@ -153,7 +153,7 @@ describe('FakeRequest', function() { }); }); - it('combines request headers with the same header name', function() { + it('combines request headers with the same header name', () => { var request = new this.FakeRequest(); request.setRequestHeader('X-Header', 'value1'); @@ -162,7 +162,7 @@ describe('FakeRequest', function() { expect(request.requestHeaders['X-Header']).toEqual('value1, value2'); }); - it('finds the content-type request header', function() { + it('finds the content-type request header', () => { var request = new this.FakeRequest(); request.setRequestHeader('ContEnt-tYPe', 'application/text+xml'); @@ -170,24 +170,24 @@ describe('FakeRequest', function() { expect(request.contentType()).toEqual('application/text+xml'); }); - describe('managing readyState', function() { - beforeEach(function() { + describe('managing readyState', () => { + beforeEach(() => { this.request = new this.FakeRequest(); }); - it('has an initial ready state of 0 (uninitialized)', function() { + it('has an initial ready state of 0 (uninitialized)', () => { expect(this.request.readyState).toBe(0); expect(this.fakeEventBus.trigger).not.toHaveBeenCalled(); }); - it('has a ready state of 1 (open) when opened', function() { + it('has a ready state of 1 (open) when opened', () => { this.request.open(); expect(this.request.readyState).toBe(1); expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 0 (uninitialized) when aborted', function() { + it('has a ready state of 0 (uninitialized) when aborted', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -197,7 +197,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 1 (sent) when sent', function() { + it('has a ready state of 1 (sent) when sent', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -208,7 +208,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).not.toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 4 (loaded) when timed out', function() { + it('has a ready state of 4 (loaded) when timed out', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -221,7 +221,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange', 'timeout'); }); - it('has a ready state of 4 (loaded) when network erroring', function() { + it('has a ready state of 4 (loaded) when network erroring', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -232,7 +232,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 4 (loaded) when responding', function() { + it('has a ready state of 4 (loaded) when responding', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -243,7 +243,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 2, then 4 (loaded) when responding', function() { + it('has a ready state of 2, then 4 (loaded) when responding', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -254,7 +254,7 @@ describe('FakeRequest', function() { { name: 'X-Header', value: 'foo' } ]; - this.fakeEventBus.trigger.and.callFake(function(event) { + this.fakeEventBus.trigger.and.callFake(event => { if (event === 'readystatechange') { events.push({ readyState: request.readyState, @@ -280,41 +280,41 @@ describe('FakeRequest', function() { ]); }); - it('throws an error when timing out a request that has completed', function() { + it('throws an error when timing out a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.responseTimeout(); }).toThrowError('FakeXMLHttpRequest already completed'); }); - it('throws an error when responding to a request that has completed', function() { + it('throws an error when responding to a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.respondWith({}); }).toThrowError('FakeXMLHttpRequest already completed'); }); - it('throws an error when erroring a request that has completed', function() { + it('throws an error when erroring a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.responseError({}); }).toThrowError('FakeXMLHttpRequest already completed'); }); }); - it('registers on-style callback with the event bus', function() { + it('registers on-style callback with the event bus', () => { this.request = new this.FakeRequest(); expect(this.fakeEventBus.addEventListener).toHaveBeenCalledWith('readystatechange', jasmine.any(Function)); @@ -336,16 +336,13 @@ describe('FakeRequest', function() { this.request.onloadend = jasmine.createSpy('loadend'); var args = this.fakeEventBus.addEventListener.calls.allArgs(); - for (var i = 0; i < args.length; i++) { - var eventName = args[i][0], - busCallback = args[i][1]; - + for (const [eventName, busCallback] of args) { busCallback(); expect(this.request['on' + eventName]).toHaveBeenCalled(); } }); - it('delegates addEventListener to the eventBus', function() { + it('delegates addEventListener to the eventBus', () => { this.request = new this.FakeRequest(); this.request.addEventListener('foo', 'bar'); @@ -353,7 +350,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.addEventListener).toHaveBeenCalledWith('foo', 'bar'); }); - it('delegates removeEventListener to the eventBus', function() { + it('delegates removeEventListener to the eventBus', () => { this.request = new this.FakeRequest(); this.request.removeEventListener('foo', 'bar'); @@ -361,18 +358,18 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.removeEventListener).toHaveBeenCalledWith('foo', 'bar'); }); - describe('triggering progress events', function() { - beforeEach(function() { + describe('triggering progress events', () => { + beforeEach(() => { this.request = new this.FakeRequest(); }); - it('should not trigger any events to start', function() { + it('should not trigger any events to start', () => { this.request.open(); expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('should trigger loadstart when sent', function() { + it('should trigger loadstart when sent', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -389,7 +386,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).not.toHaveBeenCalledWith('loadend'); }); - it('should trigger abort, progress, loadend when aborted', function() { + it('should trigger abort, progress, loadend when aborted', () => { this.request.open(); this.request.send(); @@ -407,7 +404,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger error, progress, loadend when network error', function() { + it('should trigger error, progress, loadend when network error', () => { this.request.open(); this.request.send(); @@ -425,7 +422,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger timeout, progress, loadend when timing out', function() { + it('should trigger timeout, progress, loadend when timing out', () => { this.request.open(); this.request.send(); @@ -445,7 +442,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger load, progress, loadend when responding', function() { + it('should trigger load, progress, loadend when responding', () => { this.request.open(); this.request.send(); @@ -464,7 +461,7 @@ describe('FakeRequest', function() { }); }); - it('ticks the jasmine clock on timeout', function() { + it('ticks the jasmine clock on timeout', () => { var clock = { tick: jasmine.createSpy('tick') }; spyOn(jasmine, 'clock').and.returnValue(clock); @@ -477,13 +474,13 @@ describe('FakeRequest', function() { expect(clock.tick).toHaveBeenCalledWith(30000); }); - it('has an initial status of null', function() { + it('has an initial status of null', () => { var request = new this.FakeRequest(); expect(request.status).toBeNull(); }); - it('has an aborted status', function() { + it('has an aborted status', () => { var request = new this.FakeRequest(); request.abort(); @@ -492,7 +489,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe('abort'); }); - it('has a status from the response', function() { + it('has a status from the response', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -503,7 +500,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe(''); }); - it('has a statusText from the response', function() { + it('has a statusText from the response', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -514,7 +511,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe('OK'); }); - it('saves off any data sent to the server', function() { + it('saves off any data sent to the server', () => { var request = new this.FakeRequest(); request.open(); request.send('foo=bar&baz=quux'); @@ -522,7 +519,7 @@ describe('FakeRequest', function() { expect(request.params).toBe('foo=bar&baz=quux'); }); - it('parses data sent to the server', function() { + it('parses data sent to the server', () => { var request = new this.FakeRequest(); request.open(); request.send('foo=bar&baz=quux'); @@ -532,7 +529,7 @@ describe('FakeRequest', function() { expect(request.data()).toBe('parsed'); }); - it('skips parsing if no data was sent', function() { + it('skips parsing if no data was sent', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -541,7 +538,7 @@ describe('FakeRequest', function() { expect(this.parserInstance).not.toHaveBeenCalled(); }); - it('saves responseText', function() { + it('saves responseText', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -551,7 +548,7 @@ describe('FakeRequest', function() { expect(request.responseText).toBe('foobar'); }); - it('defaults responseText if none is given', function() { + it('defaults responseText if none is given', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -561,7 +558,7 @@ describe('FakeRequest', function() { expect(request.responseText).toBe(''); }); - it('retrieves individual response headers', function() { + it('retrieves individual response headers', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -576,7 +573,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('X-Header')).toBe('foo'); }); - it('retrieves individual response headers case-insensitively', function() { + it('retrieves individual response headers case-insensitively', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -591,7 +588,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('x-header')).toBe('foo'); }); - it('retrieves a combined response header', function() { + it('retrieves a combined response header', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -607,7 +604,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('x-header')).toBe('foo, bar'); }); - it("doesn't pollute the response headers of other XHRs", function() { + it("doesn't pollute the response headers of other XHRs", () => { var request1 = new this.FakeRequest(); request1.open(); request1.send(); @@ -623,7 +620,7 @@ describe('FakeRequest', function() { expect(request2.getAllResponseHeaders()).toBe("X-Baz: quux\r\n"); }); - it('retrieves all response headers', function() { + it('retrieves all response headers', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -640,7 +637,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("X-Header-1: foo\r\nX-Header-2: bar\r\nX-Header-1: baz\r\n"); }); - it('sets the content-type header to the specified contentType when no other headers are supplied', function() { + it('sets the content-type header to the specified contentType when no other headers are supplied', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -651,7 +648,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("Content-Type: text/plain\r\n"); }); - it('sets a default content-type header if no contentType and headers are supplied', function() { + it('sets a default content-type header if no contentType and headers are supplied', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -662,7 +659,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("Content-Type: application/json\r\n"); }); - it('has no responseXML by default', function() { + it('has no responseXML by default', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -672,7 +669,7 @@ describe('FakeRequest', function() { expect(request.responseXML).toBeNull(); }); - it('parses a text/xml document into responseXML', function() { + it('parses a text/xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -689,7 +686,7 @@ describe('FakeRequest', function() { } }); - it('parses an application/xml document into responseXML', function() { + it('parses an application/xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -706,7 +703,7 @@ describe('FakeRequest', function() { } }); - it('parses a custom blah+xml document into responseXML', function() { + it('parses a custom blah+xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -723,7 +720,7 @@ describe('FakeRequest', function() { } }); - it('defaults the response attribute to the responseText', function() { + it('defaults the response attribute to the responseText', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -733,7 +730,7 @@ describe('FakeRequest', function() { expect(request.response).toEqual('foo'); }); - it('has a text response when the responseType is blank', function() { + it('has a text response when the responseType is blank', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -743,7 +740,7 @@ describe('FakeRequest', function() { expect(request.response).toEqual('foo'); }); - it('has a text response when the responseType is text', function() { + it('has a text response when the responseType is text', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -755,14 +752,14 @@ describe('FakeRequest', function() { }); -describe("Jasmine Mock Ajax (for toplevel)", function() { +describe("Jasmine Mock Ajax (for toplevel)", () => { var request, anotherRequest, response; var success, error, complete; var client, onreadystatechange; var sharedContext: any = {}; var fakeGlobal, mockAjax; - beforeEach(function() { + beforeEach(() => { var fakeXMLHttpRequest = jasmine.createSpy('realFakeXMLHttpRequest'); fakeGlobal = { XMLHttpRequest: fakeXMLHttpRequest, @@ -776,7 +773,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { error = jasmine.createSpy("onFailure"); complete = jasmine.createSpy("onComplete"); - onreadystatechange = function() { + onreadystatechange = () => { if (this.readyState === (this.DONE || 4)) { // IE 8 doesn't support DONE if (this.status === 200) { success(this.responseText, this.textStatus, this); @@ -789,8 +786,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }; }); - describe("when making a request", function() { - beforeEach(function() { + describe("when making a request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -798,24 +795,24 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { request = mockAjax.requests.mostRecent(); }); - it("should store URL and transport", function() { + it("should store URL and transport", () => { expect(request.url).toEqual("example.com/someApi"); }); - it("should queue the request", function() { + it("should queue the request", () => { expect(mockAjax.requests.count()).toEqual(1); }); - it("should allow access to the queued request", function() { + it("should allow access to the queued request", () => { expect(mockAjax.requests.first()).toEqual(request); }); - it("should allow access to the queued request via index", function() { + it("should allow access to the queued request via index", () => { expect(mockAjax.requests.at(0)).toEqual(request); }); - describe("and then another request", function() { - beforeEach(function() { + describe("and then another request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -824,26 +821,26 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { anotherRequest = mockAjax.requests.mostRecent(); }); - it("should queue the next request", function() { + it("should queue the next request", () => { expect(mockAjax.requests.count()).toEqual(2); }); - it("should allow access to the other queued request", function() { + it("should allow access to the other queued request", () => { expect(mockAjax.requests.first()).toEqual(request); expect(mockAjax.requests.mostRecent()).toEqual(anotherRequest); }); }); - describe("mockAjax.requests.mostRecent()", function() { + describe("mockAjax.requests.mostRecent()", () => { - describe("when there is one request queued", function() { - it("should return the request", function() { + describe("when there is one request queued", () => { + it("should return the request", () => { expect(mockAjax.requests.mostRecent()).toEqual(request); }); }); - describe("when there is more than one request", function() { - beforeEach(function() { + describe("when there is more than one request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -851,37 +848,37 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { anotherRequest = mockAjax.requests.mostRecent(); }); - it("should return the most recent request", function() { + it("should return the most recent request", () => { expect(mockAjax.requests.mostRecent()).toEqual(anotherRequest); }); }); - describe("when there are no requests", function() { - beforeEach(function() { + describe("when there are no requests", () => { + beforeEach(() => { mockAjax.requests.reset(); }); - it("should return null", function() { + it("should return null", () => { expect(mockAjax.requests.mostRecent()).toBeUndefined(); }); }); }); - describe("clearAjaxRequests()", function() { - beforeEach(function() { + describe("clearAjaxRequests()", () => { + beforeEach(() => { mockAjax.requests.reset(); }); - it("should remove all requests", function() { + it("should remove all requests", () => { expect(mockAjax.requests.count()).toEqual(0); expect(mockAjax.requests.mostRecent()).toBeUndefined(); }); }); }); - describe("when simulating a response with request.response", function() { - describe("and the response is Success", function() { - beforeEach(function() { + describe("when simulating a response with request.response", () => { + describe("and the response is Success", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -900,23 +897,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the response is Success, but with JSON", function() { - beforeEach(function() { + describe("and the response is Success, but with JSON", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -938,19 +935,19 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); - it("should return a JavaScript object for XHR2 response", function() { + it("should return a JavaScript object for XHR2 response", () => { var responseText = sharedContext.responseText; expect(success.calls.mostRecent().args[0]).toEqual(responseText); @@ -961,8 +958,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the response is Success, and response is overriden", function() { - beforeEach(function() { + describe("and the response is Success, and response is overriden", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -984,7 +981,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("should return the provided override for the XHR2 response", function() { + it("should return the provided override for the XHR2 response", () => { var responseText = sharedContext.responseText; expect(response.responseText).toEqual(responseText); @@ -994,8 +991,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("response with unique header names using an object", function() { - beforeEach(function() { + describe("response with unique header names using an object", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com"); @@ -1013,13 +1010,13 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("getResponseHeader should return the each value", function() { + it("getResponseHeader should return the each value", () => { expect(response.getResponseHeader('X-Header1')).toBe('header 1 value'); expect(response.getResponseHeader('X-Header2')).toBe('header 2 value'); expect(response.getResponseHeader('X-Header3')).toBe('header 3 value'); }); - it("getAllResponseHeaders should return all values", function() { + it("getAllResponseHeaders should return all values", () => { expect(response.getAllResponseHeaders()).toBe([ "X-Header1: header 1 value", "X-Header2: header 2 value", @@ -1028,8 +1025,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("response with multiple headers of the same name using an array of objects", function() { - beforeEach(function() { + describe("response with multiple headers of the same name using an array of objects", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com"); @@ -1046,11 +1043,11 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("getResponseHeader should return all values comma separated", function() { + it("getResponseHeader should return all values comma separated", () => { expect(response.getResponseHeader('X-Header')).toBe('header value 1, header value 2'); }); - it("getAllResponseHeaders should return all values", function() { + it("getAllResponseHeaders should return all values", () => { expect(response.getAllResponseHeaders()).toBe([ "X-Header: header value 1", "X-Header: header value 2" @@ -1058,8 +1055,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("the content type defaults to application/json", function() { - beforeEach(function() { + describe("the content type defaults to application/json", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1078,23 +1075,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseText = response.responseText; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the status/response code is 0", function() { - beforeEach(function() { + describe("and the status/response code is 0", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1113,15 +1110,15 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); @@ -1129,8 +1126,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("and the response is error", function() { - beforeEach(function() { + describe("and the response is error", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1138,7 +1135,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { client.send(); request = mockAjax.requests.mostRecent(); - response = { status: 500, statusText: "SERVER ERROR", contentType: "text/html", responseText: "(._){",responseType: "json"}; + response = { status: 500, statusText: "SERVER ERROR", contentType: "text/html", responseText: "(._){", responseType: "json"}; request.respondWith(response); sharedContext.responseCallback = error; @@ -1149,23 +1146,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should not call the success handler", function() { + it("should not call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should call the failure handler", function() { + it("should call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Failure(sharedContext); }); - describe('when simulating a response with request.responseTimeout', function() { - beforeEach(function() { + describe('when simulating a response with request.responseTimeout', () => { + beforeEach(() => { jasmine.clock().install(); client = new fakeGlobal.XMLHttpRequest(); @@ -1186,19 +1183,19 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - afterEach(function() { + afterEach(() => { jasmine.clock().uninstall(); }); - it("should not call the success handler", function() { + it("should not call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should call the failure handler", function() { + it("should call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); }); @@ -1206,74 +1203,74 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { function sharedAjaxResponseBehaviorForZepto_Success(context) { - describe("the success response", function() { + describe("the success response", () => { var xhr; - beforeEach(function() { + beforeEach(() => { xhr = context.responseCallback.calls.mostRecent().args[2]; }); - it("should have the expected status code", function() { + it("should have the expected status code", () => { expect(xhr.status).toEqual(context.status); }); - it("should have the expected content type", function() { + it("should have the expected content type", () => { expect(xhr.getResponseHeader('Content-Type')).toEqual(context.contentType); }); - it("should have the expected xhr2 response", function() { + it("should have the expected xhr2 response", () => { var expected = context.response || context.responseType === 'json' ? JSON.parse(context.responseText) : context.responseText; expect(xhr.response).toEqual(expected); }); - it("should have the expected response text", function() { + it("should have the expected response text", () => { expect(xhr.responseText).toEqual(context.responseText); }); - it("should have the expected status text", function() { + it("should have the expected status text", () => { expect(xhr.statusText).toEqual(context.statusText); }); }); } function sharedAjaxResponseBehaviorForZepto_Failure(context) { - describe("the failure response", function() { + describe("the failure response", () => { var xhr; - beforeEach(function() { + beforeEach(() => { xhr = context.responseCallback.calls.mostRecent().args[0]; }); - it("should have the expected status code", function() { + it("should have the expected status code", () => { expect(xhr.status).toEqual(context.status); }); - it("should have the expected content type", function() { + it("should have the expected content type", () => { expect(xhr.getResponseHeader('Content-Type')).toEqual(context.contentType); }); - it("should have the expected xhr2 response", function() { + it("should have the expected xhr2 response", () => { var expected = context.response || xhr.responseType === 'json' ? JSON.parse(xhr.responseText) : xhr.responseText; expect(xhr.response).toEqual(expected); }); - it("should have the expected response text", function() { + it("should have the expected response text", () => { expect(xhr.responseText).toEqual(context.responseText); }); - it("should have the expected status text", function() { + it("should have the expected status text", () => { expect(xhr.statusText).toEqual(context.statusText); }); }); } -describe('ParamParser', function() { - beforeEach(function() { +describe('ParamParser', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxParamParser(); expect(Constructor).toEqual(jasmine.any(Function)); this.parser = new Constructor(); }); - it('has a default parser', function() { - var parser = this.parser.findParser({ contentType: function() { } }), + it('has a default parser', () => { + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('3+stooges=shemp&3+stooges=larry%20%26%20moe%20%26%20curly&some%3Dthing=else+entirely'); expect(parsed).toEqual({ @@ -1282,7 +1279,7 @@ describe('ParamParser', function() { }); }); - it('should detect and parse json', function() { + it('should detect and parse json', () => { var data = { foo: 'bar', baz: ['q', 'u', 'u', 'x'], @@ -1292,13 +1289,13 @@ describe('ParamParser', function() { } } }, - parser = this.parser.findParser({ contentType: function() { return 'application/json'; } }), + parser = this.parser.findParser({ contentType: () => 'application/json' }), parsed = parser.parse(JSON.stringify(data)); expect(parsed).toEqual(data); }); - it('should parse json with further qualifiers on content-type', function() { + it('should parse json with further qualifiers on content-type', () => { var data = { foo: 'bar', baz: ['q', 'u', 'u', 'x'], @@ -1308,13 +1305,13 @@ describe('ParamParser', function() { } } }, - parser = this.parser.findParser({ contentType: function() { return 'application/json; charset=utf-8'; } }), + parser = this.parser.findParser({ contentType: () => 'application/json; charset=utf-8' }), parsed = parser.parse(JSON.stringify(data)); expect(parsed).toEqual(data); }); - it('should have custom parsers take precedence', function() { + it('should have custom parsers take precedence', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(true), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1322,7 +1319,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual('parsedFormat'); @@ -1330,7 +1327,7 @@ describe('ParamParser', function() { expect(custom.parse).toHaveBeenCalledWith('custom_format'); }); - it('should skip custom parsers that do not match', function() { + it('should skip custom parsers that do not match', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(false), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1338,7 +1335,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual({ custom_format: ['undefined'] }); @@ -1346,7 +1343,7 @@ describe('ParamParser', function() { expect(custom.parse).not.toHaveBeenCalled(); }); - it('removes custom parsers when reset', function() { + it('removes custom parsers when reset', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(true), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1354,7 +1351,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual('parsedFormat'); @@ -1364,7 +1361,7 @@ describe('ParamParser', function() { this.parser.reset(); - parser = this.parser.findParser({ contentType: function() { } }); + parser = this.parser.findParser({ contentType: () => { } }); parsed = parser.parse('custom_format'); expect(parsed).toEqual({ custom_format: ['undefined'] }); @@ -1373,14 +1370,14 @@ describe('ParamParser', function() { }); }); -describe('RequestStub', function() { - beforeEach(function() { +describe('RequestStub', () => { + beforeEach(() => { this.RequestStub = getJasmineRequireObj().AjaxRequestStub(); jasmine.addMatchers({ - toMatchRequest: function(a, b) { + toMatchRequest(a, b) { return { - compare: function(actual): jasmine.CustomMatcherResult { + compare(actual): jasmine.CustomMatcherResult { return { message: '', pass: actual.matches.apply(actual, Array.prototype.slice.call(arguments, 1)) @@ -1391,31 +1388,31 @@ describe('RequestStub', function() { }); }); - it('matches just by exact url', function() { + it('matches just by exact url', () => { var stub = new this.RequestStub('www.example.com/foo'); expect(stub)['toMatchRequest']('www.example.com/foo'); }); - it('does not match if the url differs', function() { + it('does not match if the url differs', () => { var stub = new this.RequestStub('www.example.com/foo'); expect(stub).not['toMatchRequest']('www.example.com/bar'); }); - it('matches unordered query params', function() { + it('matches unordered query params', () => { var stub = new this.RequestStub('www.example.com?foo=bar&baz=quux'); expect(stub)['toMatchRequest']('www.example.com?baz=quux&foo=bar'); }); - it('requires all specified query params to be there', function() { + it('requires all specified query params to be there', () => { var stub = new this.RequestStub('www.example.com?foo=bar&baz=quux'); expect(stub).not['toMatchRequest']('www.example.com?foo=bar'); }); - it('can match the url with a RegExp', function() { + it('can match the url with a RegExp', () => { var stub = new this.RequestStub(/ba[rz]/); expect(stub)['toMatchRequest']('bar'); @@ -1423,7 +1420,7 @@ describe('RequestStub', function() { expect(stub).not['toMatchRequest']('foo'); }); - it('requires the method to match if supplied', function() { + it('requires the method to match if supplied', () => { var stub = new this.RequestStub('www.example.com/foo', null, 'POST'); expect(stub).not['toMatchRequest']('www.example.com/foo'); @@ -1431,7 +1428,7 @@ describe('RequestStub', function() { expect(stub)['toMatchRequest']('www.example.com/foo', null, 'POST'); }); - it('requires the data submitted to match if supplied', function() { + it('requires the data submitted to match if supplied', () => { var stub = new this.RequestStub('/foo', 'foo=bar&baz=quux'); expect(stub)['toMatchRequest']('/foo', 'baz=quux&foo=bar'); @@ -1439,13 +1436,13 @@ describe('RequestStub', function() { }); }); -describe('RequestTracker', function() { - beforeEach(function() { +describe('RequestTracker', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxRequestTracker(); this.tracker = new Constructor(); }); - it('tracks the number of times ajax requests are made', function() { + it('tracks the number of times ajax requests are made', () => { expect(this.tracker.count()).toBe(0); this.tracker.track(); @@ -1453,29 +1450,29 @@ describe('RequestTracker', function() { expect(this.tracker.count()).toBe(1); }); - it('simplifies access to the last (most recent) request', function() { + it('simplifies access to the last (most recent) request', () => { this.tracker.track(); this.tracker.track('request'); expect(this.tracker.mostRecent()).toEqual('request'); }); - it('returns a useful falsy value when there is no last (most recent) request', function() { + it('returns a useful falsy value when there is no last (most recent) request', () => { expect(this.tracker.mostRecent()).toBeFalsy(); }); - it('simplifies access to the first (oldest) request', function() { + it('simplifies access to the first (oldest) request', () => { this.tracker.track('request'); this.tracker.track(); expect(this.tracker.first()).toEqual('request'); }); - it('returns a useful falsy value when there is no first (oldest) request', function() { + it('returns a useful falsy value when there is no first (oldest) request', () => { expect(this.tracker.first()).toBeFalsy(); }); - it('allows the requests list to be reset', function() { + it('allows the requests list to be reset', () => { this.tracker.track(); this.tracker.track(); @@ -1486,7 +1483,7 @@ describe('RequestTracker', function() { expect(this.tracker.count()).toBe(0); }); - it('allows retrieval of an arbitrary request by index', function() { + it('allows retrieval of an arbitrary request by index', () => { this.tracker.track('1'); this.tracker.track('2'); this.tracker.track('3'); @@ -1494,14 +1491,14 @@ describe('RequestTracker', function() { expect(this.tracker.at(1)).toEqual('2'); }); - it('allows retrieval of all requests that are for a given url', function() { + it('allows retrieval of all requests that are for a given url', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); expect(this.tracker.filter('bar')).toEqual([{ url: 'bar' }]); }); - it('allows retrieval of all requests that match a given RegExp', function() { + it('allows retrieval of all requests that match a given RegExp', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); this.tracker.track({ url: 'baz' }); @@ -1509,29 +1506,27 @@ describe('RequestTracker', function() { expect(this.tracker.filter(/ba[rz]/)).toEqual([{ url: 'bar' }, { url: 'baz' }]); }); - it('allows retrieval of all requests that match based on a function', function() { + it('allows retrieval of all requests that match based on a function', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); this.tracker.track({ url: 'baz' }); - var func = function(request) { - return request.url === 'bar'; - }; + var func = request => request.url === 'bar'; expect(this.tracker.filter(func)).toEqual([{ url: 'bar' }]); }); - it('filters to nothing if no requests have been tracked', function() { + it('filters to nothing if no requests have been tracked', () => { expect(this.tracker.filter('foo')).toEqual([]); }); }); -describe('EventBus', function() { - beforeEach(function() { +describe('EventBus', () => { + beforeEach(() => { this.bus = getJasmineRequireObj().AjaxEventBus()(); }); - it('calls an event listener', function() { + it('calls an event listener', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1540,7 +1535,7 @@ describe('EventBus', function() { expect(callback).toHaveBeenCalled(); }); - it('calls an event listener with additional arguments', function() { + it('calls an event listener with additional arguments', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1549,7 +1544,7 @@ describe('EventBus', function() { expect(callback).toHaveBeenCalledWith('bar'); }); - it('only triggers callbacks for the specified event', function() { + it('only triggers callbacks for the specified event', () => { var fooCallback = jasmine.createSpy('foo'), barCallback = jasmine.createSpy('bar'); @@ -1562,7 +1557,7 @@ describe('EventBus', function() { expect(barCallback).not.toHaveBeenCalled(); }); - it('calls all the callbacks for the specified event', function() { + it('calls all the callbacks for the specified event', () => { var callback1 = jasmine.createSpy('callback'); var callback2 = jasmine.createSpy('otherCallback'); @@ -1575,14 +1570,14 @@ describe('EventBus', function() { expect(callback2).toHaveBeenCalled(); }); - it('works if there are no callbacks for the event', function() { + it('works if there are no callbacks for the event', () => { var bus = this.bus; - expect(function() { + expect(() => { bus.trigger('notActuallyThere'); }).not.toThrow(); }); - it('does not call listeners that have been removed', function() { + it('does not call listeners that have been removed', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1592,7 +1587,7 @@ describe('EventBus', function() { expect(callback).not.toHaveBeenCalled(); }); - it('only removes the specified callback', function() { + it('only removes the specified callback', () => { var callback1 = jasmine.createSpy('callback'); var callback2 = jasmine.createSpy('otherCallback'); @@ -1607,14 +1602,14 @@ describe('EventBus', function() { }); }); -describe("Webmock style mocking", function() { +describe("Webmock style mocking", () => { var successSpy, errorSpy, response, fakeGlobal, mockAjax; var sendRequest = function(fakeGlobal, url?, method?) { url = url || "http://example.com/someApi"; method = method || 'GET'; var xhr = new fakeGlobal.XMLHttpRequest(); - xhr.onreadystatechange = function(args) { + xhr.onreadystatechange = args => { if (this.readyState === (this.DONE || 4)) { // IE 8 doesn't support DONE response = this; successSpy(); @@ -1625,7 +1620,7 @@ describe("Webmock style mocking", function() { xhr.send(); }; - beforeEach(function() { + beforeEach(() => { successSpy = jasmine.createSpy('success'); fakeGlobal = { XMLHttpRequest: jasmine.createSpy('realXMLHttpRequest') }; mockAjax = new MockAjax(fakeGlobal); @@ -1634,33 +1629,33 @@ describe("Webmock style mocking", function() { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "hi!" }); }); - it("allows a url to be setup as a stub", function() { + it("allows a url to be setup as a stub", () => { sendRequest(fakeGlobal); expect(successSpy).toHaveBeenCalled(); }); - it("should allow you to clear all the ajax stubs", function() { + it("should allow you to clear all the ajax stubs", () => { mockAjax.stubs.reset(); sendRequest(fakeGlobal); expect(successSpy).not.toHaveBeenCalled(); }); - it("should set the contentType", function() { + it("should set the contentType", () => { sendRequest(fakeGlobal); expect(response.getResponseHeader('Content-Type')).toEqual('application/json'); }); - it("should set the responseText", function() { + it("should set the responseText", () => { sendRequest(fakeGlobal); expect(response.responseText).toEqual('hi!'); }); - it("should default the status to 200", function() { + it("should default the status to 200", () => { sendRequest(fakeGlobal); expect(response.status).toEqual(200); }); - it("should set the responseHeaders", function() { + it("should set the responseHeaders", () => { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "hi!", responseHeaders: [{ name: "X-Custom", value: "header value" }] @@ -1669,37 +1664,37 @@ describe("Webmock style mocking", function() { expect(response.getResponseHeader('X-Custom')).toEqual('header value'); }); - describe("with another stub for the same url", function() { - beforeEach(function() { + describe("with another stub for the same url", () => { + beforeEach(() => { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "no", status: 403 }); sendRequest(fakeGlobal); }); - it("should set the status", function() { + it("should set the status", () => { expect(response.status).toEqual(403); }); - it("should allow the latest stub to win", function() { + it("should allow the latest stub to win", () => { expect(response.responseText).toEqual('no'); }); }); }); -describe("withMock", function() { - var sendRequest = function(fakeGlobal) { +describe("withMock", () => { + var sendRequest = fakeGlobal => { var xhr = new fakeGlobal.XMLHttpRequest(); xhr.open("GET", "http://example.com/someApi"); xhr.send(); }; - it("installs the mock for passed in function, and uninstalls when complete", function() { + it("installs the mock for passed in function, and uninstalls when complete", () => { var xmlHttpRequest = jasmine.createSpyObj('XMLHttpRequest', ['open', 'send']), - xmlHttpRequestCtor = spyOn(window, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), + xmlHttpRequestCtor = spyOn(window as any, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), fakeGlobal = { XMLHttpRequest: xmlHttpRequestCtor }, mockAjax = new MockAjax(fakeGlobal); - mockAjax.withMock(function() { + mockAjax.withMock(() => { sendRequest(fakeGlobal); expect(xmlHttpRequest.open).not.toHaveBeenCalled(); }); @@ -1708,15 +1703,15 @@ describe("withMock", function() { expect(xmlHttpRequest.open).toHaveBeenCalled(); }); - it("properly uninstalls when the passed in function throws", function() { + it("properly uninstalls when the passed in function throws", () => { var xmlHttpRequest = jasmine.createSpyObj('XMLHttpRequest', ['open', 'send']), - xmlHttpRequestCtor = spyOn(window, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), + xmlHttpRequestCtor = spyOn(window as any, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), fakeGlobal = { XMLHttpRequest: xmlHttpRequestCtor }, mockAjax = new MockAjax(fakeGlobal); - expect(function() { - mockAjax.withMock(function() { - throw "error"; + expect(() => { + mockAjax.withMock(() => { + throw "error"; // tslint:disable-line:no-string-throw }); }).toThrow("error"); @@ -1725,8 +1720,8 @@ describe("withMock", function() { }); }); -describe("mockAjax", function() { - it("throws an error if installed multiple times", function() { +describe("mockAjax", () => { + it("throws an error if installed multiple times", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1739,7 +1734,7 @@ describe("mockAjax", function() { expect(doubleInstall).toThrow(); }); - it("does not throw an error if uninstalled between installs", function() { + it("does not throw an error if uninstalled between installs", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1753,7 +1748,7 @@ describe("mockAjax", function() { expect(sequentialInstalls).not.toThrow(); }); - it("does not replace XMLHttpRequest until it is installed", function() { + it("does not replace XMLHttpRequest until it is installed", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1767,7 +1762,7 @@ describe("mockAjax", function() { expect(fakeXmlHttpRequest).not.toHaveBeenCalled(); }); - it("replaces the global XMLHttpRequest on uninstall", function() { + it("replaces the global XMLHttpRequest on uninstall", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1779,14 +1774,14 @@ describe("mockAjax", function() { expect(fakeXmlHttpRequest).toHaveBeenCalledWith('foo'); }); - it("clears requests and stubs upon uninstall", function() { + it("clears requests and stubs upon uninstall", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - mockAjax.requests.track({ url: '/testurl' }); + mockAjax.requests.track( { url: '/testurl' }); mockAjax.stubRequest('/bobcat'); expect(mockAjax.requests.count()).toEqual(1); @@ -1798,25 +1793,25 @@ describe("mockAjax", function() { expect(mockAjax.stubs.findStub('/bobcat')).not.toBeDefined(); }); - it("allows the httpRequest to be retrieved", function() { + it("allows the httpRequest to be retrieved", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - var request = new (fakeGlobal.XMLHttpRequest)(); + var request = new ( fakeGlobal.XMLHttpRequest)(); expect(mockAjax.requests.count()).toBe(1); expect(mockAjax.requests.mostRecent()).toBe(request); }); - it("allows the httpRequests to be cleared", function() { + it("allows the httpRequests to be cleared", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - var request = new (fakeGlobal.XMLHttpRequest)(); + var request = new ( fakeGlobal.XMLHttpRequest)(); expect(mockAjax.requests.mostRecent()).toBe(request); mockAjax.requests.reset(); diff --git a/jasmine-ajax/tslint.json b/jasmine-ajax/tslint.json new file mode 100644 index 0000000000..fe03bea79d --- /dev/null +++ b/jasmine-ajax/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "unified-signatures": false + } +} diff --git a/jasmine-data_driven_tests/index.d.ts b/jasmine-data_driven_tests/index.d.ts index 9874f61cb8..a2a7415093 100644 --- a/jasmine-data_driven_tests/index.d.ts +++ b/jasmine-data_driven_tests/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine Data Driven Tests +// Type definitions for Jasmine Data Driven Tests 1.0 // Project: https://github.com/gburghardt/jasmine-data_driven_tests // Definitions by: Anthony MacKinnon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jasmine-data_driven_tests/tslint.json b/jasmine-data_driven_tests/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jasmine-data_driven_tests/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jasmine-es6-promise-matchers/index.d.ts b/jasmine-es6-promise-matchers/index.d.ts index 493a6a5312..89e3146c2c 100644 --- a/jasmine-es6-promise-matchers/index.d.ts +++ b/jasmine-es6-promise-matchers/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bvaughn/jasmine-es6-promise-matchers // Definitions by: Stephen Lautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/jasmine-expect/index.d.ts b/jasmine-expect/index.d.ts index c8ffd8dced..c2ee7e0ee5 100644 --- a/jasmine-expect/index.d.ts +++ b/jasmine-expect/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/JamieMason/Jasmine-Matchers // Definitions by: UserPixel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/jasmine-fixture/index.d.ts b/jasmine-fixture/index.d.ts index 77d9c740b1..8ea5956f1e 100644 --- a/jasmine-fixture/index.d.ts +++ b/jasmine-fixture/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine-fixture 1.0.7 +// Type definitions for Jasmine-fixture 1.0 // Project: https://github.com/searls/jasmine-fixture // Definitions by: Craig Brett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jasmine-fixture/tslint.json b/jasmine-fixture/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jasmine-fixture/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jasmine-jquery/index.d.ts b/jasmine-jquery/index.d.ts index cbd713fd37..fb91e0c37b 100644 --- a/jasmine-jquery/index.d.ts +++ b/jasmine-jquery/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/velesin/jasmine-jquery // Definitions by: Gregor Stamac // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// diff --git a/jasmine-matchers/index.d.ts b/jasmine-matchers/index.d.ts index 23990c8364..ac44d25c1c 100644 --- a/jasmine-matchers/index.d.ts +++ b/jasmine-matchers/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/uxebu/jasmine-matchers // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /* Typings 2013 Bart van der Schoor diff --git a/jasmine-node/index.d.ts b/jasmine-node/index.d.ts index 59a3b11d8a..5c8022d706 100644 --- a/jasmine-node/index.d.ts +++ b/jasmine-node/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mhevery/jasmine-node // Definitions by: Sven Reglitzki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/jasmine-promise-matchers/index.d.ts b/jasmine-promise-matchers/index.d.ts index 1693c9fdca..c511019b62 100644 --- a/jasmine-promise-matchers/index.d.ts +++ b/jasmine-promise-matchers/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bvaughn/jasmine-promise-matchers // Definitions by: Matthew Hill // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/jasmine/index.d.ts b/jasmine/index.d.ts index 7bf232acba..e18361dec4 100644 --- a/jasmine/index.d.ts +++ b/jasmine/index.d.ts @@ -2,6 +2,7 @@ // Project: http://jasmine.github.io/ // Definitions by: Boris Yankov , Theodore Brown , David Pärsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 // For ddescribe / iit use : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts @@ -35,7 +36,7 @@ interface DoneFn extends Function { fail: (message?: Error|string) => void; } -declare function spyOn(object: any, method: string): jasmine.Spy; +declare function spyOn(object: T, method: keyof T): jasmine.Spy; declare function runs(asyncMethod: Function): void; declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; diff --git a/jasmine/package.json b/jasmine/package.json new file mode 100644 index 0000000000..7e47d54c61 --- /dev/null +++ b/jasmine/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "typescript": ">=2.1.4" + } +} \ No newline at end of file diff --git a/jasminewd2/index.d.ts b/jasminewd2/index.d.ts new file mode 100644 index 0000000000..9d8ecde76e --- /dev/null +++ b/jasminewd2/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for jasminewd2 2.0 +// Project: https://github.com/angular/jasminewd +// Definitions by: Sammy Jelin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare function it(expectation: string, assertion?: () => Promise, timeout?: number): void; +declare function fit(expectation: string, assertion?: () => Promise, timeout?: number): void; +declare function xit(expectation: string, assertion?: () => Promise, timeout?: number): void; +declare function beforeEach(action: () => Promise, timeout?: number): void; +declare function afterEach(action: () => Promise, timeout?: number): void; +declare function beforeAll(action: () => Promise, timeout?: number): void; +declare function afterAll(action: () => Promise, timeout?: number): void; + +declare namespace jasmine { + // The global `Promise` type is too strict and kinda wrong + interface Promise { + then(onFulfill?: (value: T) => U | Promise, onReject?: (error: any) => U | Promise): Promise; + } + + interface Matchers { + toBe(expected: any, expectationFailOutput?: any): Promise; + toEqual(expected: any, expectationFailOutput?: any): Promise; + toMatch(expected: string | RegExp | Promise, expectationFailOutput?: any): Promise; + toBeDefined(expectationFailOutput?: any): Promise; + toBeUndefined(expectationFailOutput?: any): Promise; + toBeNull(expectationFailOutput?: any): Promise; + toBeNaN(): Promise; + toBeTruthy(expectationFailOutput?: any): Promise; + toBeFalsy(expectationFailOutput?: any): Promise; + toHaveBeenCalled(): Promise; + toHaveBeenCalledWith(...params: any[]): Promise; + toHaveBeenCalledTimes(expected: number | Promise): Promise; + toContain(expected: any, expectationFailOutput?: any): Promise; + toBeLessThan(expected: number | Promise, expectationFailOutput?: any): Promise; + toBeLessThanOrEqual(expected: number | Promise, expectationFailOutput?: any): Promise; + toBeGreaterThan(expected: number | Promise, expectationFailOutput?: any): Promise; + toBeGreaterThanOrEqual(expected: number | Promise, expectationFailOutput?: any): Promise; + toBeCloseTo(expected: number | Promise, precision?: any, expectationFailOutput?: any): Promise; + toThrow(expected?: any): Promise; + toThrowError(message?: string | RegExp | Promise): Promise; + toThrowError(expected?: new (...args: any[]) => Error | Promise Error>, message?: string | RegExp | Promise): Promise; + } + + function addMatchers(matchers: AsyncCustomMatcherFactories): void; + + interface Env { + addMatchers(matchers: AsyncCustomMatcherFactories): void; + } + + interface Spec { + addMatchers(matchers: AsyncCustomMatcherFactories): void; + } + + interface AsyncCustomMatcherFactories { + [index: string]: AsyncCustomMatcherFactory; + } + + interface AsyncCustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]): AsyncCustomMatcher; + } + + interface AsyncCustomMatcher { + compare(actual: T, expected: T): AsyncCustomMatcherResult; + compare(actual: any, expected: any): AsyncCustomMatcherResult; + } + + interface AsyncCustomMatcherResult { + pass: boolean | Promise; + message?: string; + } +} diff --git a/jasminewd2/jasminewd2-tests.ts b/jasminewd2/jasminewd2-tests.ts new file mode 100644 index 0000000000..e201ed3cc0 --- /dev/null +++ b/jasminewd2/jasminewd2-tests.ts @@ -0,0 +1,123 @@ +let promise = new Promise((resolve, reject) => { + resolve(); +}); + +describe('jasminewd', () => { + describe('global it, fit, xit, before and after', () => { + it('should be able to return promises', () => { + return promise; + }); + + fit('should be able to return promises', () => { + return promise; + }); + + xit('should be able to return promises', () => { + return promise; + }); + + beforeEach(() => { + return promise; + }); + + afterEach(() => { + return promise; + }); + + beforeAll(() => { + return promise; + }); + + afterAll(() => { + return promise; + }); + }); + + describe('matchers', () => { + it('should work', () => { + let expectedAny: any; + let expectationFailOutputAny: any; + let expectedString: string; + let expectedNumber: number; + let expectedRegExp: RegExp; + let expectedPromiseString: Promise; + let expectedPromiseNumber: Promise; + let expectedPromiseRegExp: Promise; + let paramsAny: any[]; + let error: Error; + let errorPromise: Promise; + + expect(expectedAny).toBe(expectationFailOutputAny); + expect(expectedAny).toEqual(expectationFailOutputAny); + expect(expectedString).toMatch(expectationFailOutputAny); + expect(expectedRegExp).toMatch(expectationFailOutputAny); + expect(expectedPromiseString).toMatch(expectationFailOutputAny); + expect(expectedPromiseRegExp).toMatch(expectationFailOutputAny); + expect(expectationFailOutputAny).toBeDefined(); + expect(expectationFailOutputAny).toBeUndefined(); + expect(expectationFailOutputAny).toBeNull(); + expect(expectedAny).toBeNaN(); + expect(expectedAny).toBeTruthy(); + expect(expectedAny).toBeFalsy(); + expect(expectedAny).toHaveBeenCalled(); + expect(expectedAny).toHaveBeenCalledWith(paramsAny); + expect(expectedAny).toHaveBeenCalledTimes(expectedNumber); + expect(expectedAny).toHaveBeenCalledTimes(expectedPromiseNumber); + expect(expectedAny).toContain(expectationFailOutputAny); + expect(expectedNumber).toBeLessThan(expectedNumber); + expect(expectedNumber).toBeLessThan(expectedPromiseNumber); + expect(expectedNumber).toBeLessThanOrEqual(expectedNumber); + expect(expectedNumber).toBeLessThanOrEqual(expectedPromiseNumber); + expect(expectedNumber).toBeGreaterThan(expectedNumber); + expect(expectedNumber).toBeGreaterThan(expectedPromiseNumber); + expect(expectedNumber).toBeGreaterThanOrEqual(expectedNumber); + expect(expectedNumber).toBeGreaterThanOrEqual(expectedPromiseNumber); + expect(expectedNumber).toBeCloseTo(expectedNumber, expectedNumber); + expect(expectedPromiseNumber).toBeCloseTo(expectationFailOutputAny, expectedNumber); + expect(expectedAny).toThrow(expectationFailOutputAny); + expect(expectedAny).toThrowError(expectedString); + expect(expectedAny).toThrowError(expectedRegExp); + expect(expectedAny).toThrowError(expectedPromiseString); + expect(expectedAny).toThrowError(expectedPromiseRegExp); + expect(error).toThrowError(expectedString); + expect(error).toThrowError(expectedRegExp); + expect(error).toThrowError(expectedPromiseString); + expect(error).toThrowError(expectedPromiseRegExp); + expect(error).toThrowError(expectedString); + expect(errorPromise).toThrowError(expectedString); + expect(errorPromise).toThrowError(expectedRegExp); + expect(errorPromise).toThrowError(expectedPromiseString); + expect(errorPromise).toThrowError(expectedPromiseRegExp); + expect(errorPromise).toThrowError(expectedString); + }); + }); + + describe('jasmine matchers', () => { + it('should be able to add matchers', () => { + let matchers = { + toBeLotsMoreThan() { + return { + compare(actual: number, expected: number) { + return { + pass: actual > expected + 100 + }; + } + }; + }, + // Example custom matcher returning a promise that resolves to true/false. + toBeDisplayed() { + return { + compare(actual: any, expected: void) { + return { + pass: (actual.isDisplayed() as Promise) + }; + } + }; + } + }; + jasmine.addMatchers(matchers); + jasmine.getEnv().addMatchers(matchers); + jasmine.getEnv().currentSpec.addMatchers(matchers); + }); + }); +}); diff --git a/jasminewd2/tsconfig.json b/jasminewd2/tsconfig.json new file mode 100644 index 0000000000..81aa80fe8e --- /dev/null +++ b/jasminewd2/tsconfig.json @@ -0,0 +1,20 @@ +{ + "files": [ + "index.d.ts", + "jasminewd2-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ "es6" ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/jasminewd2/tslint.json b/jasminewd2/tslint.json new file mode 100644 index 0000000000..e689d36e71 --- /dev/null +++ b/jasminewd2/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "prefer-const": false, + "void-return": false + } +} diff --git a/jenkins/jenkins-tests.ts b/jenkins/jenkins-tests.ts index c3def89156..0b409a4b87 100644 --- a/jenkins/jenkins-tests.ts +++ b/jenkins/jenkins-tests.ts @@ -2,19 +2,19 @@ import * as J from 'jenkins'; const jenkins = J({ baseUrl: 'http://user:pass@localhost:8080', crumbIssuer: true }); -jenkins.info(function(err, data) { +jenkins.info((err, data) => { if (err) throw err; console.log('info', data); }); -jenkins.build.get('example', 1, function(err, data) { +jenkins.build.get('example', 1, (err, data) => { if (err) throw err; console.log('build', data); }); -jenkins.build.log('example', 1, function(err, data) { +jenkins.build.log('example', 1, (err, data) => { if (err) throw err; console.log('log', data); @@ -22,181 +22,181 @@ jenkins.build.log('example', 1, function(err, data) { var log = jenkins.build.logStream('example', 1); -log.on('data', function(text: string) { +log.on('data', (text: string) => { process.stdout.write(text); }); -log.on('error', function(err: Error) { +log.on('error', (err: Error) => { console.log('error', err); }); -log.on('end', function() { +log.on('end', () => { console.log('end'); }); -jenkins.build.stop('example', 1, function(err) { +jenkins.build.stop('example', 1, (err) => { if (err) throw err; }); -jenkins.job.build('example', function(err, data) { +jenkins.job.build('example', (err, data) => { if (err) throw err; console.log('queue item number', data); }); -jenkins.job.build({ name: 'example', parameters: { name: 'value' } }, function(err) { +jenkins.job.build({ name: 'example', parameters: { name: 'value' } }, (err) => { if (err) throw err; }); -jenkins.job.config('example', function(err, data) { +jenkins.job.config('example', (err, data) => { if (err) throw err; console.log('xml', data); }); -jenkins.job.config('example', '', function(err) { +jenkins.job.config('example', '', (err) => { if (err) throw err; }); -jenkins.job.copy('fromJob', 'example', function(err) { +jenkins.job.copy('fromJob', 'example', (err) => { if (err) throw err; }); -jenkins.job.create('example', '', function(err) { +jenkins.job.create('example', '', (err) => { if (err) throw err; }); -jenkins.job.destroy('example', function(err) { +jenkins.job.destroy('example', (err) => { if (err) throw err; }); -jenkins.job.disable('example', function(err) { +jenkins.job.disable('example', (err) => { if (err) throw err; }); -jenkins.job.enable('example', function(err) { +jenkins.job.enable('example', (err) => { if (err) throw err; }); -jenkins.job.exists('example', function(err, exists) { +jenkins.job.exists('example', (err, exists) => { if (err) throw err; console.log('exists', exists); }); -jenkins.job.get('example', function(err, data) { +jenkins.job.get('example', (err, data) => { if (err) throw err; console.log('job', data); }); -jenkins.job.list(function(err, data) { +jenkins.job.list((err, data) => { if (err) throw err; console.log('jobs', data); }); -jenkins.node.config('example', function(err, data) { +jenkins.node.config('example', (err, data) => { if (err) throw err; console.log('xml', data); }); -jenkins.node.create('slave', function(err) { +jenkins.node.create('slave', (err) => { if (err) throw err; }); -jenkins.node.destroy('slave', function(err) { +jenkins.node.destroy('slave', (err) => { if (err) throw err; }); -jenkins.node.disconnect('slave', 'no longer used', function(err) { +jenkins.node.disconnect('slave', 'no longer used', (err) => { if (err) throw err; }); -jenkins.node.disable('slave', 'network failure', function(err) { +jenkins.node.disable('slave', 'network failure', (err) => { if (err) throw err; }); -jenkins.node.enable('slave', function(err) { +jenkins.node.enable('slave', (err) => { if (err) throw err; }); -jenkins.node.exists('slave', function(err, exists) { +jenkins.node.exists('slave', (err, exists) => { if (err) throw err; console.log('exists', exists); }); -jenkins.node.get('slave', function(err, data) { +jenkins.node.get('slave', (err, data) => { if (err) throw err; console.log('node', data); }); -jenkins.node.list(function(err, data) { +jenkins.node.list((err, data) => { if (err) throw err; console.log('nodes', data); }); -jenkins.queue.list(function(err, data) { +jenkins.queue.list((err, data) => { if (err) throw err; console.log('queues', data); }); -jenkins.queue.item(130, function(err, data) { +jenkins.queue.item(130, (err, data) => { if (err) throw err; console.log('item', data); }); -jenkins.queue.cancel(23, function(err) { +jenkins.queue.cancel(23, (err) => { if (err) throw err; }); -jenkins.view.config('example', function(err, data) { +jenkins.view.config('example', (err, data) => { if (err) throw err; console.log('xml', data); }); -jenkins.view.config('example', '', function(err) { +jenkins.view.config('example', '', (err) => { if (err) throw err; }); -jenkins.view.create('example', 'list', function(err) { +jenkins.view.create('example', 'list', (err) => { if (err) throw err; }); -jenkins.view.destroy('example', function(err) { +jenkins.view.destroy('example', (err) => { if (err) throw err; }); -jenkins.view.exists('example', function(err, exists) { +jenkins.view.exists('example', (err, exists) => { if (err) throw err; console.log('exists', exists); }); -jenkins.view.get('example', function(err, data) { +jenkins.view.get('example', (err, data) => { if (err) throw err; console.log('view', data); }); -jenkins.view.list(function(err, data) { +jenkins.view.list((err, data) => { if (err) throw err; console.log('views', data); }); -jenkins.view.add('example', 'jobExample', function(err) { +jenkins.view.add('example', 'jobExample', (err) => { if (err) throw err; }); -jenkins.view.remove('example', 'jobExample', function(err) { +jenkins.view.remove('example', 'jobExample', (err) => { if (err) throw err; }); diff --git a/jest/index.d.ts b/jest/index.d.ts index f376ea5bcc..9f945ba426 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Jest 16.0.0 +// Type definitions for Jest 18.1.0 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev , jwbay +// Definitions by: Asana , Ivo Stratev , jwbay , Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare var beforeAll: jest.Lifecycle; declare var beforeEach: jest.Lifecycle; @@ -16,7 +17,7 @@ declare var xit: jest.It; declare var test: jest.It; declare var xtest: jest.It; -declare function expect(actual: any): jest.Matchers; +declare const expect: jest.Expect; interface NodeRequire { /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ @@ -26,13 +27,18 @@ interface NodeRequire { } declare namespace jest { + /** Provides a way to add Jasmine-compatible matchers into your Jest context. */ function addMatchers(matchers: jasmine.CustomMatcherFactories): typeof jest; /** Disables automatic mocking in the module loader. */ function autoMockOff(): typeof jest; /** Enables automatic mocking in the module loader. */ function autoMockOn(): typeof jest; - /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */ + /** + * @deprecated use resetAllMocks instead + */ function clearAllMocks(): typeof jest; + /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */ + function resetAllMocks(): typeof jest; /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ function clearAllTimers(): typeof jest; /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ @@ -46,6 +52,7 @@ declare namespace jest { /** Enables automatic mocking in the module loader. */ function enableAutomock(): typeof jest; /** Creates a mock function. Optionally takes a mock implementation. */ + function fn(implementation: (...args: any[]) => T): Mock; function fn(implementation?: Function): Mock; /** Use the automatic mocking system to generate a mocked version of the given module. */ function genMockFromModule(moduleName: string): T; @@ -98,8 +105,16 @@ declare namespace jest { (fn: ProvidesCallback): any; } + /** Creates a test closure */ interface It { + /** + * Creates a test closure. + * + * @param {string} name The name of your test + * @param {fn?} ProvidesCallback The function for your test + */ (name: string, fn?: ProvidesCallback): void; + /** Only runs this test in the current file. */ only: It; skip: It; concurrent: It; @@ -111,35 +126,113 @@ declare namespace jest { skip: Describe; } + interface MatcherUtils { + readonly isNot: boolean; + utils: { + readonly EXPECTED_COLOR: string; + readonly RECEIVED_COLOR: string; + ensureActualIsNumber(actual: any, matcherName?: string): void; + ensureExpectedIsNumber(actual: any, matcherName?: string): void; + ensureNoExpected(actual: any, matcherName?: string): void; + ensureNumbers(actual: any, expected: any, matcherName?: string): void; + /** get the type of a value with handling of edge cases like `typeof []` and `typeof null` */ + getType(value: any): string; + matcherHint(matcherName: string, received?: string, expected?: string, options?: { secondArgument?: string, isDirectExpectCall?: boolean }): string; + pluralize(word: string, count: number): string; + printExpected(value: any): string; + printReceived(value: any): string; + printWithType(name: string, received: any, print: (value: any) => string): string; + stringify(object: {}, maxDepth?: number): string; + } + } + + interface ExpectExtendMap { + [key: string]: (this: MatcherUtils, received: any, actual: any) => { message: () => string, pass: boolean }; + } + + /** The `expect` function is used every time you want to test a value. You will rarely call `expect` by itself. */ + interface Expect { + /** + * The `expect` function is used every time you want to test a value. You will rarely call `expect` by itself. + * + * @param {any} actual The value to apply matchers against. + */ + (actual: any): Matchers; + anything(): void; + /** Matches anything that was created with the given constructor. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. */ + any(classType: any): void; + /** Matches any array made up entirely of elements in the provided array. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. */ + arrayContaining(arr: any[]): void; + /** Verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. */ + assertions(num: number): void; + /** You can use `expect.extend` to add your own matchers to Jest. */ + extend(obj: ExpectExtendMap): void; + /** Matches any object that recursively matches the provided keys. This is often handy in conjunction with other asymmetric matchers. */ + objectContaining(obj: {}): void; + /** Matches any string that contains the exact provided string */ + stringMatching(str: string | RegExp): void; + } + interface Matchers { + /** If you know how to test something, `.not` lets you test its opposite. */ not: Matchers; lastCalledWith(...args: any[]): void; + /** Checks that a value is what you expect. It uses `===` to check strict equality. Don't use `toBe` with floating-point numbers. */ toBe(expected: any): void; + /** Ensures that a mock function is called. */ toBeCalled(): void; + /** Ensure that a mock function is called with specific arguments. */ toBeCalledWith(...args: any[]): void; - toBeCloseTo(expected: number, delta: number): void; + /** Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. */ + toBeCloseTo(expected: number, delta?: number): void; + /** Ensure that a variable is not undefined. */ toBeDefined(): void; + /** When you don't care what a value is, you just want to ensure a value is false in a boolean context. */ toBeFalsy(): void; + /** For comparing floating point numbers. */ toBeGreaterThan(expected: number): void; + /** For comparing floating point numbers. */ toBeGreaterThanOrEqual(expected: number): void; + /** Ensure that an object is an instance of a class. This matcher uses `instanceof` underneath. */ toBeInstanceOf(expected: any): void + /** For comparing floating point numbers. */ toBeLessThan(expected: number): void; + /** For comparing floating point numbers. */ toBeLessThanOrEqual(expected: number): void; + /** This is the same as `.toBe(null)` but the error messages are a bit nicer. So use `.toBeNull()` when you want to check that something is null. */ toBeNull(): void; + /** Use when you don't care what a value is, you just want to ensure a value is true in a boolean context. In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. */ toBeTruthy(): void; + /** Used to check that a variable is undefined. */ toBeUndefined(): void; + /** Used when you want to check that an item is in a list. For testing the items in the list, this uses `===`, a strict equality check. */ toContain(expected: any): void; + /** Used when you want to check that an item is in a list. For testing the items in the list, this matcher recursively checks the equality of all fields, rather than checking for object identity. */ toContainEqual(expected: any): void; + /** Used when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity. */ toEqual(expected: any): void; + /** Ensures that a mock function is called. */ toHaveBeenCalled(): boolean; + /** Ensures that a mock function is called an exact number of times. */ toHaveBeenCalledTimes(expected: number): boolean; + /** Ensure that a mock function is called with specific arguments. */ toHaveBeenCalledWith(...params: any[]): boolean; + /** If you have a mock function, you can use `.toHaveBeenLastCalledWith` to test what arguments it was last called with. */ toHaveBeenLastCalledWith(...params: any[]): boolean; + /** Used to check that an object has a `.length` property and it is set to a certain numeric value. */ + toHaveLength(expected: number): void; + toHaveProperty(propertyPath: string, value?: any): void; + /** Check that a string matches a regular expression. */ toMatch(expected: string | RegExp): void; + /** Used to check that a JavaScript object matches a subset of the properties of an objec */ toMatchObject(expected: {}): void; - toMatchSnapshot(): void; + /** 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): void; + /** Used to test that a function throws when it is called. */ toThrow(): void; + /** If you want to test that a specific error is thrown inside a function. */ toThrowError(error?: string | Constructable | RegExp): void; + /** Used to test that a function throws a error matching the most recent snapshot when it is called. */ toThrowErrorMatchingSnapshot(): void; } @@ -147,9 +240,25 @@ declare namespace jest { new (...args: any[]): any } - interface Mock extends Function { + interface Mock extends Function, MockInstance { new (): T; (...args: any[]): any; + } + + /** + * Wrap module with mock definitions + * @example + * jest.mock("../api"); + * import { Api } from "../api"; + * + * const myApi: jest.Mocked = new Api() as any; + * myApi.myApiMethod.mockImplementation(() => "test"); + */ + type Mocked = { + [P in keyof T]: T[P] & MockInstance; + } & T; + + interface MockInstance { mock: MockContext; mockClear(): void; mockReset(): void; diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index 913a671fa1..a3d84a09e3 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -147,6 +147,10 @@ describe('compartion', function () { it('works sanely with simple decimals', function () { expect(0.2 + 0.1).toBeCloseTo(0.3, 5); }); + + it('works sanely with simple decimals and the default delta', function () { + expect(0.2 + 0.1).toBeCloseTo(0.3); + }); }); describe('toThrow API', function () { @@ -171,6 +175,60 @@ describe('toThrow API', function () { }); }); +describe('Assymetric matchers', function () { + it('works', function () { + expect({ + timestamp: 1480807810388, + text: 'Some text content, but we care only about *this part*' + }).toEqual({ + timestamp: expect.any(Number), + text: expect.stringMatching('*this part*') + }); + + const callback = jest.fn(); + expect(callback).toEqual(expect.any(Function)); + callback(5, "test"); + expect(callback).toBeCalledWith(expect.any(Number), expect.any(String)) + const obj = { + items: [1] + }; + expect(obj).toEqual(expect.objectContaining({ + items: expect.arrayContaining([ + expect.any(Number) + ]) + })); + + expect.assertions(4); + }); +}); + +describe('Extending extend', function () { + it('works', function () { + expect.extend({ + toBeNumber(received: any, actual: any) { + const pass = received === actual; + const message = + () => `expected ${received} ${pass ? 'not ' : ''} to be ${actual}`; + return { message, pass }; + }, + toBeTest(received: any, actual: any) { + this.utils.ensureNoExpected(received); + this.utils.ensureActualIsNumber(received); + this.utils.ensureExpectedIsNumber(actual); + this.utils.ensureNumbers(received, actual); + + return { + message: () => ` + ${this.utils.getType(received).toLowerCase()} \n\n + ${this.utils.matcherHint(".not.toBe")} ${this.utils.printExpected(actual)} ${this.utils.printReceived(received)}\n\n + `, + pass: true + }; + } + }); + }); +}); + describe('missing tests', function () { it('creates closures', function () { class Closure { @@ -208,7 +266,7 @@ describe('missing tests', function () { expect(getFruits()).toContain('Orange'); mock.mockReturnValueOnce(['Apple', 'Plum']); expect(mock()).not.toContain('Orange'); - const myBeverage: any = {delicious: true, sour: false}; + const myBeverage: any = {delicious: true, sour: false}; expect(myBeverage).toContainEqual({delicious: true, sour: false}); mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. mock.mockClear(); @@ -248,6 +306,10 @@ describe('toMatchSnapshot', function () { it('compares snapshots', function () { expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); }); + + it('can give name to snapshot', function () { + expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot('given name'); + }); }); describe('toThrowErrorMatchingSnapshot', function () { @@ -367,3 +429,58 @@ describe('strictNullChecks', function () { done(); }) }); + +class TestApi { + constructor() { }; + testProp: boolean; + private anotherProp: string; + testMethod(a: number): string { return ""; } +} + +declare function mockedFunc(a: number): string; + +declare function mockedFuncWithApi(api: TestApi): void; + +describe('Mocked type', function () { + it('Works', function () { + const mock: jest.Mocked = new TestApi() as any; + mock.testProp; + mock.testMethod.mockImplementation(() => 'test'); + mock.testMethod(5).toUpperCase(); + + mockedFuncWithApi(mock); + }); +}); + +describe('Mocks', function () { + it('jest.fn() without args is a function type', function () { + const test = jest.fn(); + test(); + new test(); + test.mock.instances[0]; + test.mockImplementation(() => { }); + }); + + it('jest.fn() with returned object infers type', function () { + const testMock = jest.fn(() => ({ a: 5, test: jest.fn() })); + + testMock(5, 5, 'a'); + testMock.mockImplementation(() => { }); + testMock.caller; + + const ins = new testMock(); + ins.a; + ins.test(); + ins.test.mockImplementation(() => 5); + ins.test.mock.calls; + + const anotherMock = jest.fn(() => { + const api: Partial = { + testMethod: jest.fn() + }; + return api; + }); + const anotherIns: jest.Mocked = new anotherMock() as any; + anotherIns.testMethod.mockImplementation(() => 1); + }); +}); diff --git a/jest/v16/index.d.ts b/jest/v16/index.d.ts new file mode 100644 index 0000000000..f376ea5bcc --- /dev/null +++ b/jest/v16/index.d.ts @@ -0,0 +1,303 @@ +// Type definitions for Jest 16.0.0 +// Project: http://facebook.github.io/jest/ +// Definitions by: Asana , Ivo Stratev , jwbay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var beforeAll: jest.Lifecycle; +declare var beforeEach: jest.Lifecycle; +declare var afterAll: jest.Lifecycle; +declare var afterEach: jest.Lifecycle; +declare var describe: jest.Describe; +declare var fdescribe: jest.Describe; +declare var xdescribe: jest.Describe; +declare var it: jest.It; +declare var fit: jest.It; +declare var xit: jest.It; +declare var test: jest.It; +declare var xtest: jest.It; + +declare function expect(actual: any): jest.Matchers; + +interface NodeRequire { + /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ + requireActual(moduleName: string): any; + /** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */ + requireMock(moduleName: string): any; +} + +declare namespace jest { + function addMatchers(matchers: jasmine.CustomMatcherFactories): typeof jest; + /** Disables automatic mocking in the module loader. */ + function autoMockOff(): typeof jest; + /** Enables automatic mocking in the module loader. */ + function autoMockOn(): typeof jest; + /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */ + function clearAllMocks(): typeof jest; + /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ + function clearAllTimers(): typeof jest; + /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ + function deepUnmock(moduleName: string): typeof jest; + /** Disables automatic mocking in the module loader. */ + function disableAutomock(): typeof jest; + /** Mocks a module with an auto-mocked version when it is being required. */ + function doMock(moduleName: string): typeof jest; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function dontMock(moduleName: string): typeof jest; + /** Enables automatic mocking in the module loader. */ + function enableAutomock(): typeof jest; + /** Creates a mock function. Optionally takes a mock implementation. */ + function fn(implementation?: Function): Mock; + /** Use the automatic mocking system to generate a mocked version of the given module. */ + function genMockFromModule(moduleName: string): T; + /** Returns whether the given function is a mock function. */ + function isMockFunction(fn: any): fn is Mock; + /** Mocks a module with an auto-mocked version when it is being required. */ + function mock(moduleName: string, factory?: any, options?: MockOptions): typeof jest; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModuleRegistry(): typeof jest; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModules(): typeof jest; + /** Exhausts tasks queued by setImmediate(). */ + function runAllImmediates(): typeof jest; + /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ + function runAllTicks(): typeof jest; + /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ + function runAllTimers(): typeof jest; + /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). + * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */ + function runOnlyPendingTimers(): typeof jest; + /** Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */ + function runTimersToTime(msToRun: number): typeof jest; + /** Explicitly supplies the mock object that the module system should return for the specified module. */ + function setMock(moduleName: string, moduleExports: T): typeof jest; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function unmock(moduleName: string): typeof jest; + /** Instructs Jest to use fake versions of the standard timer functions. */ + function useFakeTimers(): typeof jest; + /** Instructs Jest to use the real versions of the standard timer functions. */ + function useRealTimers(): typeof jest; + + interface MockOptions { + virtual?: boolean; + } + + interface EmptyFunction { + (): void; + } + + interface DoneCallback { + (...args: any[]): any + fail(error?: string | { message: string }): any; + } + + interface ProvidesCallback { + (cb: DoneCallback): any; + } + + interface Lifecycle { + (fn: ProvidesCallback): any; + } + + interface It { + (name: string, fn?: ProvidesCallback): void; + only: It; + skip: It; + concurrent: It; + } + + interface Describe { + (name: string, fn: EmptyFunction): void + only: Describe; + skip: Describe; + } + + interface Matchers { + not: Matchers; + lastCalledWith(...args: any[]): void; + toBe(expected: any): void; + toBeCalled(): void; + toBeCalledWith(...args: any[]): void; + toBeCloseTo(expected: number, delta: number): void; + toBeDefined(): void; + toBeFalsy(): void; + toBeGreaterThan(expected: number): void; + toBeGreaterThanOrEqual(expected: number): void; + toBeInstanceOf(expected: any): void + toBeLessThan(expected: number): void; + toBeLessThanOrEqual(expected: number): void; + toBeNull(): void; + toBeTruthy(): void; + toBeUndefined(): void; + toContain(expected: any): void; + toContainEqual(expected: any): void; + toEqual(expected: any): void; + toHaveBeenCalled(): boolean; + toHaveBeenCalledTimes(expected: number): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toHaveBeenLastCalledWith(...params: any[]): boolean; + toMatch(expected: string | RegExp): void; + toMatchObject(expected: {}): void; + toMatchSnapshot(): void; + toThrow(): void; + toThrowError(error?: string | Constructable | RegExp): void; + toThrowErrorMatchingSnapshot(): void; + } + + interface Constructable { + new (...args: any[]): any + } + + interface Mock extends Function { + new (): T; + (...args: any[]): any; + mock: MockContext; + mockClear(): void; + mockReset(): void; + mockImplementation(fn: Function): Mock; + mockImplementationOnce(fn: Function): Mock; + mockReturnThis(): Mock; + mockReturnValue(value: any): Mock; + mockReturnValueOnce(value: any): Mock; + } + + interface MockContext { + calls: any[][]; + instances: T[]; + } +} + +//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected. +//Relevant parts of Jasmine's API are below so they can be changed and removed over time. +//This file can't reference jasmine.d.ts since the globals aren't compatible. + +declare function spyOn(object: any, method: string): jasmine.Spy; +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; +/** Fails a test when called within one. */ +declare function fail(error?: any): void; +declare namespace jasmine { + var clock: () => Clock; + function any(aclass: any): Any; + function anything(): Any; + function arrayContaining(sample: any[]): ArrayContaining; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + function stringMatching(value: string | RegExp): Any; + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + mockDate(date?: Date): void; + } + + interface Any { + new (expectedClass: any): any; + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + interface ArrayContaining { + new (sample: any[]): any; + asymmetricMatch(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: any): any; + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Spy { + (...params: any[]): any; + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): Spy; + /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */ + returnValues(...values: any[]): Spy; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): Spy; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ + all(): CallInfo[]; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ + mostRecent(): CallInfo; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ + first(): CallInfo; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ + reset(): void; + } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: any[]; + /** The return value of the call */ + returnValue: any; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherResult { + pass: boolean; + message: string | (() => string); + } + + interface ArrayLike { + length: number; + [n: number]: T; + } +} diff --git a/jest/v16/jest-tests.ts b/jest/v16/jest-tests.ts new file mode 100644 index 0000000000..c69eae61a2 --- /dev/null +++ b/jest/v16/jest-tests.ts @@ -0,0 +1,369 @@ +/// + +// Tests based on the Jest website +jest.unmock('../sum'); + +describe('sum', function() { + it('adds 1 + 2 to equal 3', function() { + var sum: (a: number, b: number) => number = require('../sum'); + expect(sum(1, 2)).toBe(3); + }); +}); + +describe('fetchCurrentUser', function() { + it('calls the callback when $.ajax requests are finished', function() { + var $ = require('jquery'); + var fetchCurrentUser = require('../fetchCurrentUser'); + + // Create a mock function for our callback + var callback = jest.fn(); + fetchCurrentUser(callback); + + // Now we emulate the process by which `$.ajax` would execute its own + // callback + $.ajax.mock.calls[0 /*first call*/][0 /*first argument*/].success({ + firstName: 'Bobby', + lastName: '");DROP TABLE Users;--' + }); + + // And finally we assert that this emulated call by `$.ajax` incurred a + // call back into the mock function we provided as a callback + expect(callback.mock.calls[0/*first call*/][0/*first arg*/]).toEqual({ + loggedIn: true, + fullName: 'Bobby ");DROP TABLE Users;--' + }); + }); +}); + +// unmock is the recommended approach for unmocking... +jest.unmock('../displayUser.js') + +describe('displayUser', function() { + it('displays a user after a click', function() { + // Set up our document body + document.body.innerHTML = + '
' + + ' ' + + '
'; + + var displayUser = require.requireActual('../displayUser'); + var $ = require('jquery'); + var fetchCurrentUser = require('../fetchCurrentUser'); + + // Tell the fetchCurrentUser mock function to automatically invoke + // its callback with some data + fetchCurrentUser.mockImplementation(function(cb: Function) { + cb({ + loggedIn: true, + fullName: 'Johnny Cash' + }); + }); + + // Use jquery to emulate a click on our button + $('#button').click(); + + // Assert that the fetchCurrentUser function was called, and that the + // #username span's innter text was updated as we'd it expect. + expect(fetchCurrentUser).toBeCalled(); + expect($('#username').text()).toEqual('Johnny Cash - Logged In'); + }); +}); + +jest.unmock('../CheckboxWithLabel.js'); +describe('CheckboxWithLabel', function() { + it('changes the text after click', function() { + var React = require('react/addons'); + var CheckboxWithLabel = require('../CheckboxWithLabel.js'); + var TestUtils = React.addons.TestUtils; + + // Render a checkbox with label in the document + var checkbox = TestUtils.renderIntoDocument( + CheckboxWithLabel({ + labelOn: "On", + labelOff: "Off" + }) + ); + + // Verify that it's Off by default + var label = TestUtils.findRenderedDOMComponentWithTag( + checkbox, 'label'); + expect(label.getDOMNode().textContent).toEqual('Off'); + + // Simulate a click and verify that it is now On + var input = TestUtils.findRenderedDOMComponentWithTag( + checkbox, 'input'); + TestUtils.Simulate.change(input); + expect(label.getDOMNode().textContent).toEqual('On'); + }); +}); + +jest.runAllTicks(); +xdescribe('Hooks and Suits', function () { + let tested: boolean; + + beforeEach(function () { + tested = false; + }); + + afterEach(function () { + tested = true; + }); + + test('tested', function () { + expect(tested).toBeTruthy(); + expect(tested).not.toBeFalsy(); + }); + + fit('tested', function () { + expect(tested).toBeDefined(); + expect(tested).not.toBeUndefined(); + }); + + xit('expect null to be null', function () { + expect(null).toBeNull(); + }); +}); + +describe('compartion', function () { + var sum: (a: number, b: number) => number = require.requireMock('../sum'); + + it('compares is 7 + 2 greater than 3', function () { + expect(sum(7, 2)).toBeGreaterThan(3); + }); + + it('compares is 2 + 7 greater than or equal to 3', function () { + expect(sum(2, 7)).toBeGreaterThanOrEqual(3); + }); + + it('compares is 3 less than 3 + 4', function () { + expect(3).toBeLessThan(sum(3, 4)); + }); + + it('compares is 3 less than or equal to 4 + 3', function () { + expect(3).toBeLessThanOrEqual(sum(4, 3)); + }); + + it('works sanely with simple decimals', function () { + expect(0.2 + 0.1).toBeCloseTo(0.3, 5); + }); +}); + +describe('toThrow API', function () { + function throwTypeError(): void { + throw new TypeError('toThrow Definition was out of date'); + } + + it('throws', function () { + expect(throwTypeError()).toThrow(); + }); + + it('throws TypeError', function () { + expect(throwTypeError()).toThrowError(TypeError); + }); + + it('throws \'Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError(/Definition was out of date/); + }); + + it('throws \'toThorow Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); + }); +}); + +describe('missing tests', function () { + it('creates closures', function () { + class Closure { + private arg: T; + + public constructor(private fn: (arg: T) => void) { + this.fn = fn; + } + + public bind(arg: T): void { + this.arg = arg; + } + + public call(): void { + this.fn(this.arg); + } + } + + type StringClosure = (arg: string) => void; + let spy: jest.Mock = jest.fn(); + let closure: Closure = new Closure(spy); + closure.bind('jest'); + closure.call(); + expect(spy).lastCalledWith('jest'); + expect(spy).toBeCalledWith('jest'); + expect(jest.isMockFunction(spy)).toBeTruthy(); + }); + + it('tests all mising Mocks functionality', function () { + type FruitsGetter = () => Array; + let mock: jest.Mock = jest.fn(); + mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']) + jest.setMock('./../tesks/getFruits', mock); + const getFruits: FruitsGetter = require('./../tesks/getFruits'); + expect(getFruits()).toContain('Orange'); + mock.mockReturnValueOnce(['Apple', 'Plum']); + expect(mock()).not.toContain('Orange'); + const myBeverage: any = {delicious: true, sour: false}; + expect(myBeverage).toContainEqual({delicious: true, sour: false}); + mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. + mock.mockClear(); + let thisMock: jest.Mock = jest.fn().mockReturnThis(); + expect(thisMock()).toBe(this); + }); + + it('creates snapshoter', function () { + jest.disableAutomock().mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); + const render: () => string = require('./render'); + expect(render()).toMatch(/Link/); + jest.enableAutomock(); + }); + + it('runs only pending timers', function () { + jest.useRealTimers(); + setTimeout(() => expect(1).not.toEqual(0), 3000); + jest.runOnlyPendingTimers().runTimersToTime(300); + }); + + it('runs all timers', function () { + jest.clearAllTimers(); + jest.useFakeTimers(); + setTimeout(() => expect(0).not.toEqual(1), 3000); + jest.runAllTimers(); + }); + + it('cleares cache', function () { + const sum1 = require('../sum'); + jest.resetModules(); + const sum2 = require('../sum'); + expect(sum1).not.toBe(sum2); + }) +}); + +describe('toMatchSnapshot', function () { + it('compares snapshots', function () { + expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); + }); +}); + +describe('toThrowErrorMatchingSnapshot', function () { + it('compares snapshots', function () { + expect(() => { throw new Error('descriptiton') }).toThrowErrorMatchingSnapshot(); + }); +}); + +function testInstances() { + var mockFn = jest.fn(); + var a = new mockFn(); + var b = new mockFn(); + + mockFn.mock.instances[0] === a; // true + mockFn.mock.instances[1] === b; // true +} + +function testMockImplementation() { + var mockFn = jest.fn().mockImplementation(function (scalar:number):number { + return 42 + scalar; + }); + + var a = mockFn(0); + var b = mockFn(1); + + a === 42; // true + b === 43; // true + + mockFn.mock.calls[0][0] === 0; // true + mockFn.mock.calls[1][0] === 1; // true +} + +// Test from jest Docs: +describe('genMockFromModule', function () { + // Interfaces: + interface MockFiles { + [index: string]: string; + } + + interface MockedFS { + readdirSync: (dir: string) => string[]; + __setMockFiles: (newMockFiles: MockFiles) => void ; + } + + // ------------------------------------------------------------------------------------ + // FileSummarizer.ts + + const fs = require('fs'); + + function summarizeFilesInDirectorySync(directory: string): string[] { + return fs.readdirSync(directory).map((fileName: string) => ({ + fileName, + directory, + })); + } + + //export default summarizeFilesInDirectorySync; // For sake of compilation + + // ------------------------------------------------------------------------------------ + // __mocks__/fs.js + + const path = require('path'); + + const mockedFS: MockedFS = jest.genMockFromModule('fs'); + + let mockFiles: any = Object.create(null); + function __setMockFiles(newMockFiles: MockFiles): void { + mockFiles = Object.create(null); + for(const file in newMockFiles) { + const dir: string = path.dirname(file); + + if (!mockFiles[dir]) { + mockFiles[dir] = []; + } + mockFiles[dir].push(path.basename(file)); + } + } + + function readdirSync(directoryPath: string): string[] { + return mockFiles[directoryPath] || []; + } + + mockedFS.readdirSync = readdirSync; + mockedFS.__setMockFiles = __setMockFiles; + + //export = mockedFS; // For sake of compilation + // ------------------------------------------------------------------------------------ + // __tests__/FileSummarizer-test.js + + jest.mock('fs'); + + describe('listFilesInDirectorySync', () => { + const MOCK_FILE_INFO: MockFiles = { + '/path/to/file1.js': 'console.log("file1 contents");', + '/path/to/file2.txt': 'file2 contents', + }; + + beforeEach(() => { + // Set up some mocked out file info before each test + (require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO); + }); + + it('includes all files in the directory in the summary', () => { + const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer'); + const fileSummary = FileSummarizer('/path/to'); + + expect(fileSummary.length).toBe(2); + }); + }); +}); + +/** + * Pass strictNullChecks + */ +describe('strictNullChecks', function () { + it('does not complain when using done callback', (done) => { + done(); + }) +}); diff --git a/jest/v16/tsconfig.json b/jest/v16/tsconfig.json new file mode 100644 index 0000000000..2e023e1205 --- /dev/null +++ b/jest/v16/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "jest": ["jest/v16"], + "jest/*": ["jest/v16/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jest-tests.ts" + ] +} diff --git a/jfs/jfs-tests.ts b/jfs/jfs-tests.ts index 0deebbd4a4..d53d1305a2 100644 --- a/jfs/jfs-tests.ts +++ b/jfs/jfs-tests.ts @@ -8,19 +8,19 @@ interface TestStore { const db = new Store('data', {type: 'memory'}); // save with custom ID -db.save('bar', 123, function(err, id) { +db.save('bar', 123, (err, id) => { // now the data is stored in the file data/anId.json }); // save with generated ID -db.save(333, function(err, id) { +db.save(333, (err, id) => { // id is a unique ID }); // save synchronously db.saveSync('foo', 'test'); -db.get('bar', function(err, obj) { +db.get('bar', (err, obj) => { // obj = { foo: ''bar' } }); @@ -28,7 +28,7 @@ db.get('bar', function(err, obj) { const val = db.getSync('bar'); // get all available objects -db.all(function(err, objs) { +db.all((err, objs) => { // objs is a map: ID => OBJECT }); @@ -36,7 +36,7 @@ db.all(function(err, objs) { var objs = db.allSync(); // delete by ID -db.delete('foo', function(err) { +db.delete('foo', err => { // the file data/myId.json was removed }); diff --git a/jfs/tslint.json b/jfs/tslint.json index ec365f164b..377cc837d4 100644 --- a/jfs/tslint.json +++ b/jfs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/jimp/index.d.ts b/jimp/index.d.ts new file mode 100644 index 0000000000..b8988e2ad4 --- /dev/null +++ b/jimp/index.d.ts @@ -0,0 +1,207 @@ +// Type definitions for jimp 0.2 +// Project: https://github.com/oliver-moran/jimp#readme +// Definitions by: Jack Works +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace jimp { + type Callback = (this: JimpImage, err: Error, data: T) => void; + type ResizeMode = string; + type PresetFont = string; + type FileMINE = string; + type AlignMode = number; + type FilterType = number; + + // Used in font info provided by parse-bmfont-ascii + type FontBoolean = 0 | 1; + interface FontChar { + id: number; + x: number; + y: number; + weight: number; + height: number; + xoffset: number; + yoffset: number; + xadvance: number; + page: number; + chnl: number; + } + type Font = { + common: {lineHeight: number, base: number, scaleW: number, scaleH: number, pages: number, packed: number}, + info: { + face: string, + size: number, + bold: FontBoolean, + italic: FontBoolean, + charset: string, + unicode: FontBoolean, + stretchH: number, + smooth: FontBoolean, + aa: number, + padding: [number, number, number, number], + spacing: [number, number] + }, + kernings: any, + pages: JIMP[], + chars: { + [char: number]: FontChar, + [char: string]: FontChar + } + } | PresetFont; + + + class JimpImage { + constructor(width: number, height: number, callback?: Callback); + constructor(width: number, height: number, initialColor: number, callback?: Callback); + + /* Get/set meta data */ + hash(n?: number): string; + + getExtension(): string; + getMIME(): FileMINE; + + getPixelColor(x: number, y: number): number; + setPixelColor(hex: number, x: number, y: number): void; + + /* Save */ + write(path: string, callback?: Callback): void; + getBase64(mine: FileMINE, callback?: Callback): void; + getBuffer(mine: FileMINE, callback?: Callback): void; + + /* Parameter */ + quality(n: number): JimpImage; + rgba(is: boolean): JimpImage; + filterType(type: FilterType): JimpImage; + deflateLevel(level: number): JimpImage; + + /* Operation */ + clone(): JimpImage; + print(font: Font, x: number, y: number, text: string, width?: number): JimpImage; + + /* Adv */ + color( + params: Array<{ + apply: 'lighten' | 'brighten' | 'darken' | 'desaturate' | 'saturate' | 'greyscale' | 'spin' | 'hue' | 'tint' | 'shade' | 'red' | 'green' | 'blue', + params: [number] + } | { + apply: 'mix', + params: [string, number] + } | { + apply: 'xor', + params: [string] + }>): JimpImage; + + convolution(matrix: number[][]): JimpImage; + scan(x: number, y: number, width: number, height: number, callback?: (this: JimpImage, x: number, y: number, idx: number) => void): JimpImage; + + /* Low level data */ + bitmap: {data: Buffer, readonly width: number, readonly height: number}; + readonly _originalMime: string; + + /* Resize */ + contain(width: number, height: number, callback?: Callback): JimpImage; + contain(width: number, height: number, alignBitsOrMode?: number | ResizeMode, callback?: Callback): JimpImage; + contain(width: number, height: number, alignBits: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + cover(width: number, height: number, callback?: Callback): JimpImage; + cover(width: number, height: number, alignBitsOrmode?: ResizeMode | number, callback?: Callback): JimpImage; + cover(width: number, height: number, alignBits: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + resize(width: number, height: number, callback?: Callback): JimpImage; + resize(width: number, height: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + scale(factor: any, callback?: Callback): JimpImage; + scale(factor: any, mode?: ResizeMode, callback?: Callback): JimpImage; + + scaleToFit(width: number, height: number, callback?: Callback): JimpImage; + scaleToFit(width: number, height: number, mode?: ResizeMode, callback?: Callback): JimpImage; + + /* Crop */ + autocrop(callback?: Callback): JimpImage; + crop(x: number, y: number, width: number, height: number, callback?: Callback): JimpImage; + + /* Composing */ + blit(scr: string, x: number, y: number, callback?: Callback): JimpImage; + blit(scr: string, x: number, y: number, srcx?: number, srcy?: number, callback?: Callback): JimpImage; + blit(scr: string, x: number, y: number, srcx?: number, srcy?: number, srcw?: number, srch?: number, callback?: Callback): JimpImage; + + composite(scr: string, x: number, y: number, callback?: Callback): JimpImage; + mask(scr: string, x: number, y: number, callback?: Callback): JimpImage; + + /* Flip and rotate */ + flip(horz: any, vert: any, callback?: Callback): JimpImage; + mirror(horz: any, vert: any, callback?: Callback): JimpImage; + rotate(deg: number, callback?: Callback): JimpImage; + rotate(deg: number, mode?: any, callback?: Callback): JimpImage; + + /* Colour */ + brightness(val: number, callback?: Callback): JimpImage; + contrast(val: number, callback?: Callback): JimpImage; + dither565(callback?: Callback): JimpImage; + greyscale(callback?: Callback): JimpImage; + invert(callback?: Callback): JimpImage; + normalize(callback?: Callback): JimpImage; + + /* Alpha channel */ + fade(val: number, callback?: Callback): JimpImage; + opacity(val: number, callback?: Callback): JimpImage; + opaque(callback?: Callback): JimpImage; + background(hex: number, callback?: Callback): JimpImage; + + /* Blurs */ + gaussian(pixel: number, callback?: Callback): JimpImage; + blur(pixel: number, callback?: Callback): JimpImage; + + /* Effects */ + posterize(level: number, callback?: Callback): JimpImage; + sepia(callback?: Callback): JimpImage; + } + class JIMP extends JimpImage { + static read(path: string | Buffer, callback?: Callback): Promise; + static loadFont(path: string | PresetFont, callback?: Callback): Promise; + static rgbaToInt(r: number, g: number, b: number, alpha: number): number; + static intToRGBA(hex: number): {r: number, g: number, b: number, a: number}; + static distance(image: JimpImage, image2: JimpImage): number; + static diff(image1: JimpImage, image2: JimpImage, threshold?: number): {image: JimpImage, percent: number}; + static deflateStrategy(deflate: number): void; + + static readonly RESIZE_NEAREST_NEIGHBOR: ResizeMode; + static readonly RESIZE_BILINEAR: ResizeMode; + static readonly RESIZE_BICUBIC: ResizeMode; + static readonly RESIZE_HERMITE: ResizeMode; + static readonly RESIZE_BEZIER: ResizeMode; + + static readonly FONT_SANS_8_BLACK: PresetFont; + static readonly FONT_SANS_16_BLACK: PresetFont; + static readonly FONT_SANS_32_BLACK: PresetFont; + static readonly FONT_SANS_64_BLACK: PresetFont; + static readonly FONT_SANS_128_BLACK: PresetFont; + + static readonly FONT_SANS_8_WHITE: PresetFont; + static readonly FONT_SANS_16_WHITE: PresetFont; + static readonly FONT_SANS_32_WHITE: PresetFont; + static readonly FONT_SANS_64_WHITE: PresetFont; + static readonly FONT_SANS_128_WHITE: PresetFont; + + static readonly MIME_PNG: FileMINE; + static readonly MIME_JPEG: FileMINE; + static readonly MIME_BMP: FileMINE; + static readonly AUTO: number; + + static readonly HORIZONTAL_ALIGN_LEFT: AlignMode; + static readonly HORIZONTAL_ALIGN_CENTER: AlignMode; + static readonly HORIZONTAL_ALIGN_RIGHT: AlignMode; + static readonly VERTICAL_ALIGN_TOP: AlignMode; + static readonly VERTICAL_ALIGN_MIDDLE: AlignMode; + static readonly VERTICAL_ALIGN_BOTTOM: AlignMode; + + static readonly PNG_FILTER_AUTO: FilterType; + static readonly PNG_FILTER_NONE: FilterType; + static readonly PNG_FILTER_SUB: FilterType; + static readonly PNG_FILTER_UP: FilterType; + static readonly PNG_FILTER_AVERAGE: FilterType; + static readonly PNG_FILTER_PAETH: FilterType; + } +} +export = jimp.JIMP; diff --git a/jimp/jimp-tests.ts b/jimp/jimp-tests.ts new file mode 100644 index 0000000000..180ce27d7f --- /dev/null +++ b/jimp/jimp-tests.ts @@ -0,0 +1,215 @@ +import Jimp = require('jimp') + +// All code below is from node-jimp document +Jimp.read("lenna.png", function (err, data) { + if (err) throw err; + data.resize(256, 256) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .write("lena-small-bw.jpg"); // save +}); + +Jimp.read("lenna.png").then(function (lenna) { + lenna.resize(256, 256) // resize + .quality(60) // set JPEG quality + .greyscale() // set greyscale + .write("lena-small-bw.jpg"); // save +}).catch(function (err) { + console.error(err); +}); + +Jimp.read("./path/to/image.jpg", function (err, image) { + // do stuff with the image (if no exception) +}); + +Jimp.read("./path/to/image.jpg").then(function (image) { + // do stuff with the image +}).catch(function (err) { + // handle an exception +}); + +Jimp.read(new Buffer(''), function (err, image) { + // do stuff with the image (if no exception) +}); + +Jimp.read("http://www.example.com/path/to/lenna.jpg", function (err, image) { + // do stuff with the image (if no exception) +}); + +var image = new Jimp(1, 2) +var w = 0 +var h = 0 +var x = 0 +var y = 0 +var f = 0 +var src = '' +var horz = Jimp.HORIZONTAL_ALIGN_CENTER +var vert = Jimp.VERTICAL_ALIGN_BOTTOM +var deg = 90 +var val = 0.5 +var hex = 0xFFFFFFFF +var r = 0 +var n = 1 +/* Resize */ +image.contain( w, h); // scale the image to the given width and height, some parts of the image may be letter boxed +image.cover( w, h); // scale the image to the given width and height, some parts of the image may be clipped +image.resize( w, h); // resize the image. Jimp.AUTO can be passed as one of the values. +image.scale(f ); // scale the image by the factor f +image.scaleToFit( w, h ); // scale the image to the largest size that fits inside the given width and height + +// An optional resize mode can be passed with all resize methods. + +/* Crop */ +image.autocrop(); // automatically crop same-color borders from image (if any) +image.crop( x, y, w, h ); // crop to the given region + +/* Composing */ +image.blit( src, x, y ); + // blit the image with another Jimp image at x, y, optionally cropped. +image.composite( src, x, y ); // composites another Jimp image over this image at x, y +image.mask( src, x, y ); // masks the image with another Jimp image at x, y using average pixel value + +/* Flip and rotate */ +image.flip( horz, vert ); // flip the image horizontally or vertically +image.mirror( horz, vert ); // an alias for flip +image.rotate( deg ); // rotate the image clockwise by a number of degrees. Optionally, a resize mode can be passed. If `false` is passed as the second parameter, the image width and height will not be resized. + +// JPEG images with EXIF orientation data will be automatically re-orientated as appropriate. + +/* Colour */ +image.brightness( val ); // adjust the brighness by a value -1 to +1 +image.contrast( val ); // adjust the contrast by a value -1 to +1 +image.dither565(); // ordered dithering of the image and reduce color space to 16-bits (RGB565) +image.greyscale(); // remove colour from the image +image.invert(); // invert the image colours +image.normalize(); // normalize the channels in an image + +/* Alpha channel */ +image.fade( f ); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image +image.opacity( f ); // multiply the alpha channel by each pixel by the factor f, 0 - 1 +image.opaque(); // set the alpha channel on every pixel to fully opaque +image.background( hex ); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and + +/* Blurs */ +image.gaussian( r ); // Gaussian blur the image by r pixels (VERY slow) +image.blur( r ); // fast blur the image by r pixels + +/* Effects */ +image.posterize( n ); // apply a posterization effect with n level +image.sepia(); // apply a sepia wash to the image + +image.clone(); // returns a clone of the image +image.resize(250, 250); // resize the image to 250 x 250 +image.resize(Jimp.AUTO, 250); // resize the height to 250 and scale the width accordingly +image.resize(250, Jimp.AUTO); // resize the width to 250 and scale the height accordingly + +image.resize(250, 250, Jimp.RESIZE_BEZIER); + +image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); + +var path = '' +var str = '' +var width = 0 +Jimp.loadFont( path ).then(function (font) { // load font from .fnt file + image.print(font, x, y, str); // print a message on an image + image.print(font, x, y, str, width); // print a message on an image with text wrapped at width +}); + +var cb = (err: Error, data: any) => {} +Jimp.loadFont( path, cb ); // using a callback pattern + +Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(function (font) { + image.print(font, 10, 10, "Hello world!"); +}); + +image.write( path, cb ); // Node-style callback will be fired when write is successful + +var file = "new_name." + image.getExtension(); +image.write(file) + + +var mime = 'image/png' +image.getBuffer( mime, cb ); // Node-style callback will be fired with result +image.getBase64( mime, cb ); // Node-style callback will be fired with result +image.quality( n ); // set the quality of saved JPEG, 0 - 100 + +var bool = true +var number = 0 +image.rgba( bool ); // set whether PNGs are saved as RGBA (true, default) or RGB (false) +image.filterType( number ); // set the filter type for the saved PNG +image.deflateLevel( number ); // set the deflate level for the saved PNG +Jimp.deflateStrategy( number ); // set the deflate for the saved PNG (0-3) + +image.color([ + { apply: 'hue', params: [ -90 ] }, + { apply: 'lighten', params: [ 50 ] }, + { apply: 'xor', params: [ '#06D' ] } +]); + image.convolution([ + [-2,-1, 0], + [-1, 1, 1], + [ 0, 1, 2] + ]) +image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { + // x, y is the position of this pixel on the image + // idx is the position start position of this rgba tuple in the bitmap Buffer + // this is the image + + var red = this.bitmap.data[ idx + 0 ]; + var green = this.bitmap.data[ idx + 1 ]; + var blue = this.bitmap.data[ idx + 2 ]; + var alpha = this.bitmap.data[ idx + 3 ]; + + // rgba values run from 0 - 255 + // e.g. this.bitmap.data[idx] = 0; // removes red from this pixel +}); +image.getPixelColor(x, y); // returns the colour of that pixel e.g. 0xFFFFFFFF +image.setPixelColor(hex, x, y); // sets the colour of that pixel + +var g = 0 +var b = 0 +var a = 0 +Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFF +Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255} + +var image = new Jimp(256, 256, function (err, image) { + // this image is 256 x 256, every pixel is set to 0x00000000 +}); + +var image = new Jimp(256, 256, 0xFF0000FF, function (err, image) { + // this image is 256 x 256, every pixel is set to 0xFF0000FF +}); + +image.hash(); // aHgG4GgoFjA +image.hash(2); // 1010101011010000101010000100101010010000011001001001010011100100 + +var image1 = new Jimp(0, 1) +var image2 = new Jimp(0, 1) +Jimp.distance(image1, image2); // returns a number 0-1, where 0 means the two images are perceived to be identical + +var threshold = 0 +var diff = Jimp.diff(image1, image2, threshold); // threshold ranges 0-1 (default: 0.1) +diff.image; // a Jimp image showing differences +diff.percent; // the proportion of different pixels (0-1), where 0 means the images are pixel identical + + +var distance = Jimp.distance(image, image2); // perceived distance +var diff = Jimp.diff(image, image2); // pixel difference + +if (distance < 0.15 || diff.percent < 0.15) { + // images match +} else { + // not a match +} + +Jimp.read("lenna.png", function (err, image) { + this.greyscale().scale(0.5).write("lena-half-bw.png"); +}); + +Jimp.read("lenna.png", function (err, image) { + image.greyscale(function(err, image) { + image.scale(0.5, function (err, image) { + image.write("lena-half-bw.png"); + }); + }); +}); \ No newline at end of file diff --git a/jimp/tsconfig.json b/jimp/tsconfig.json new file mode 100644 index 0000000000..d03d20f554 --- /dev/null +++ b/jimp/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jimp-tests.ts" + ] +} diff --git a/jimp/tslint.json b/jimp/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jimp/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jointjs/index.d.ts b/jointjs/index.d.ts index aec9f1237d..c8ef9ae302 100644 --- a/jointjs/index.d.ts +++ b/jointjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Joint JS 1.0.1 // Project: http://www.jointjs.com/ -// Definitions by: Aidan Reel , David Durman , Ewout Van Gossum , Federico Caselli +// Definitions by: Aidan Reel , David Durman , Ewout Van Gossum , Federico Caselli , Chris Moran // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // typings: https://github.com/CaselIT/typings-jointjs @@ -188,6 +188,7 @@ declare namespace joint { vertices?: Point[]; smooth?: boolean; attrs?: TextAttrs; + z?: number; } class Link extends Cell { @@ -249,6 +250,7 @@ declare namespace joint { cellViewNamespace?: Object; /** useful undocumented option */ clickThreshold?: number; + highlighting?: any; } interface ScaleContentOptions { @@ -466,40 +468,319 @@ declare namespace joint { cy?: string | number; height?: string | number; width?: string | number; + transform?: string; + points?: string; + 'stroke-width'?: string | number; + 'ref-x'?: string | number; + 'ref-y'?: string | number; + ref?: string } + namespace basic { class Generic extends dia.Element { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } interface RectAttrs extends dia.TextAttrs { rect?: ShapeAttrs; } class Rect extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } class Text extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } interface CircleAttrs extends dia.TextAttrs { circle?: ShapeAttrs; } class Circle extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } interface EllipseAttrs extends dia.TextAttrs { ellipse?: ShapeAttrs; } class Ellipse extends Generic { - constructor(attributes?: GenericAttributes, options?: Object) + constructor(attributes?: GenericAttributes, options?: Object); } - class Image extends Generic { - } - class Path extends Generic { + interface PolygonAttrs extends dia.TextAttrs { + polygon?: ShapeAttrs; } class Polygon extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface PolylineAttrs extends dia.TextAttrs { + polyline?: ShapeAttrs; } class Polyline extends Generic { } + class Image extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface PathAttrs extends dia.TextAttrs { + path?: ShapeAttrs; + } + class Path extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface RhombusAttrs extends dia.TextAttrs { + path?: ShapeAttrs; + } + class Rhombus extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + interface TextBlockAttrs extends dia.TextAttrs { + rect?: ShapeAttrs; + } + class TextBlock extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); + updateSize(cell: dia.Cell, size: dia.Size): void; + updateContent(cell: dia.Cell, content: string): void; + } + } + + namespace chess { + class KingWhite extends basic.Generic { + } + class KingBlack extends basic.Generic { + } + class QueenWhite extends basic.Generic { + } + class QueenBlack extends basic.Generic { + } + class RookWhite extends basic.Generic { + } + class RookBlack extends basic.Generic { + } + class BishopWhite extends basic.Generic { + } + class BishopBlack extends basic.Generic { + } + class KnightWhite extends basic.Generic { + } + class KnightBlack extends basic.Generic { + } + class PawnWhite extends basic.Generic { + } + class PawnBlack extends basic.Generic { + } + } + + namespace devs { + interface ModelAttributes extends GenericAttributes { + inPorts?: string[]; + outPorts?: string[]; + ports?: Object; + } + class Model extends basic.Generic { + constructor(attributes?: ModelAttributes, options?: Object); + changeInGroup(properties: any, opt?: any): boolean; + changeOutGroup(properties: any, opt?: any): boolean; + createPortItem(group: string, port: string): any; + createPortItems(group: string, ports: string[]): any[]; + addOutPort(port: string, opt?: any): this; + addInPort(port: string, opt?: any): this; + removeOutPort(port: string, opt?: any): this; + removeInPort(port: string, opt?: any): this; + } + class Coupled extends Model { + } + class Atomic extends Model { + } + class Link extends dia.Link { + } + } + + namespace erd { + class Entity extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + class WeakEntity extends Entity { + } + class Relationship extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class IdentifyingRelationship extends Relationship { + } + interface AttributeAttrs extends dia.TextAttrs { + ellipse?: ShapeAttrs; + } + class Attribute extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Multivalued extends Attribute { + } + class Derived extends Attribute { + } + class Key extends Attribute { + } + class Normal extends Attribute { + } + interface ISAAttrs extends dia.Element { + polygon?: ShapeAttrs; + } + class ISA extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Line extends dia.Link { + cardinality(value: string | number): void; + } + } + + namespace fsa { + class State extends basic.Circle { + } + class StartState extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class EndState extends dia.Element { + } + class Arrow extends dia.Link { + } + } + + namespace logic { + interface LogicAttrs extends ShapeAttrs { + ref?: string; + 'ref-x'?: number | string; + 'ref-dx'?: number | string; + 'ref-y'?: number | string; + 'ref-dy'?: number | string; + magnet?: boolean; + 'class'?: string; + port?: string; + } + interface IOAttrs extends dia.TextAttrs { + circle?: LogicAttrs; + } + class Gate extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + class IO extends Gate { + } + class Input extends IO { + } + class Output extends IO { + } + class Gate11 extends Gate { + } + class Gate21 extends Gate { + } + interface Image { + 'xlink:href'?: string; + } + interface ImageAttrs extends LogicAttrs { + image?: Image; + } + class Repeater extends Gate11 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input: any): any; + } + class Note extends Gate11 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input: any): boolean; + } + class Or extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class And extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Nor extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Nand extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Xor extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + class Xnor extends Gate21 { + constructor(attributes?: GenericAttributes, options?: Object); + operation(input1: any, input2: any): boolean; + } + interface WireArgs extends dia.LinkAttributes { + router?: Object; + connector?: Object; + } + class Wire extends dia.Link { + constructor(attributes?: WireArgs, options?: Object); + } + } + + namespace org { + interface MemberAttrs { + rect?: ShapeAttrs; + image?: ShapeAttrs; + } + class Member extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Arrow extends dia.Link { + } + } + + namespace pn { + class Place extends basic.Generic { + } + class PlaceView extends dia.ElementView { + renderTokens(): void; + } + class Transition extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); + } + class Link extends dia.Link { + } + } + + namespace uml { + interface ClassAttributes extends GenericAttributes { + name: string[]; + attributes: string[]; + methods: string[]; + } + class Class extends basic.Generic { + constructor(attributes?: ClassAttributes, options?: Object); + getClassName(): string[]; + updateRectangles(): void; + } + class ClassView extends dia.ElementView { + } + class Abstract extends Class { + } + class AbstractView extends ClassView { + } + class Interface extends Class { + } + class InterfaceView extends ClassView { + } + class Generalization extends dia.Link { + } + class Implementation extends dia.Link { + } + class Aggregation extends dia.Link { + } + class Composition extends dia.Link { + } + class Association extends dia.Link { + } + interface StateAttributes extends GenericAttributes { + events?: string[]; + } + class State extends basic.Generic { + updateName(): void; + updateEvents(): void; + updatePath(): void; + } + class StartState extends basic.Circle { + } + class EndState extends basic.Generic { + } + class Transition extends dia.Link { + } } } @@ -553,7 +834,7 @@ declare namespace joint { } class DirectedGraph { - static layout(graph: dia.Graph, options?: LayoutOptions): dia.BBox; + static layout(graph: dia.Graph | dia.Cell[], options?: LayoutOptions): dia.BBox; } } -} \ No newline at end of file +} diff --git a/jquery-mask-plugin/jquery-mask-plugin-tests.ts b/jquery-mask-plugin/jquery-mask-plugin-tests.ts index 269bc0719e..36362eccf7 100644 --- a/jquery-mask-plugin/jquery-mask-plugin-tests.ts +++ b/jquery-mask-plugin/jquery-mask-plugin-tests.ts @@ -1,6 +1,6 @@ // basic usage -$(document).ready(function () { +$(document).ready(() => { $('.date').mask('00/00/0000'); $('.time').mask('00:00:00'); $('.date_time').mask('00/00/0000 00:00:00'); @@ -15,7 +15,7 @@ $(document).ready(function () { $('.money2').mask("#.##0,00", { reverse: true }); $('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', { translation: { - 'Z': { + Z: { pattern: /[0-9]/, optional: true } } @@ -30,7 +30,7 @@ $(document).ready(function () { }); $('.fallback').mask("00r00r0000", { translation: { - 'r': { + r: { pattern: /[\/]/, fallback: '/' }, @@ -42,17 +42,17 @@ $(document).ready(function () { // callback examples let options: jQueryMask.Options = { - onComplete: function (cep: Object) { + onComplete(cep: Object) { alert('CEP Completed!:' + cep); }, - onKeyPress: function (cep: Object, event: Event, currentField: JQuery, options: jQueryMask.Options) { + onKeyPress(cep: Object, event: Event, currentField: JQuery, options: jQueryMask.Options) { console.log('An key was pressed!:', cep, ' event: ', event, 'currentField: ', currentField, ' options: ', options); }, - onChange: function (cep: Object) { + onChange(cep: Object) { console.log('cep changed! ', cep); }, - onInvalid: function (val: Object, e: Event, f: JQuery, invalid: jQueryMask.Invalid[], options: jQueryMask.Options) { + onInvalid(val: Object, e: Event, f: JQuery, invalid: jQueryMask.Invalid[], options: jQueryMask.Options) { var error = invalid[0]; console.log("Digit: ", error.v, " is invalid for the position: ", error.p, ". We expect something like: ", error.e); } @@ -62,9 +62,9 @@ $('.cep_with_callback').mask('00000-000', options); // on the fly mask changed options = { - onKeyPress: function (cep, e, field, options) { - let masks: string[] = ['00000-000', '0-00-00-00']; - let mask: string = (cep.length > 7) ? masks[1] : masks[0]; + onKeyPress(cep, e, field, options) { + const masks: string[] = ['00000-000', '0-00-00-00']; + const mask: string = (cep.length > 7) ? masks[1] : masks[0]; $('.crazy_cep').mask(mask, options); } }; @@ -72,12 +72,12 @@ options = { $('.crazy_cep').mask('00000-000', options); // mask as a function -let maskBehavior: (value: string) => string = function (val: string) { +let maskBehavior: (value: string) => string = val => { return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; }; options = { - onKeyPress: function(val: string, e: Event, field: JQuery, options: jQueryMask.Options) { + onKeyPress(val: string, e: Event, field: JQuery, options: jQueryMask.Options) { field.mask(maskBehavior.apply({}, arguments), options); } }; @@ -87,13 +87,13 @@ $('.sp_celphones').mask(maskBehavior, options); // translation // now the digit 0 on your mask pattern will be interpreted // as valid characters like 0,1,2,3,4,5,6,7,8,9 and * -$('.your-field').mask('00/00/0000', {'translation': {0: {pattern: /[0-9*]/}}}); +$('.your-field').mask('00/00/0000', {translation: {0: {pattern: /[0-9*]/}}}); // optional digits // way 1 $('.ip_address').mask('099.099.099.099'); // way 2 -$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}}); +$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {Z: {pattern: /[0-9]/, optional: true}}}); // recursive digits $('.money_example').mask('#.##0,00', {reverse: true}); @@ -101,7 +101,7 @@ $('.money_example').mask('#.##0,00', {reverse: true}); // fallback digits $('.field_with_fallback').mask("00r00r0000", { translation: { - 'r': { + r: { pattern: /[\/]/, fallback: '/' }, diff --git a/jquery-mask-plugin/tslint.json b/jquery-mask-plugin/tslint.json index 192203ab54..f05741c59b 100644 --- a/jquery-mask-plugin/tslint.json +++ b/jquery-mask-plugin/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" -} \ No newline at end of file + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/jquery.datatables/index.d.ts b/jquery.datatables/index.d.ts index c7c4bd8682..2640dbabe6 100644 --- a/jquery.datatables/index.d.ts +++ b/jquery.datatables/index.d.ts @@ -908,7 +908,7 @@ declare namespace DataTables { * @param d Data to use for the row. */ data(d: any[] | Object): DataTable; - + /** * Get the id of the selected row. Since: 1.10.8 @@ -1456,9 +1456,9 @@ declare namespace DataTables { } export interface AjaxData { - draw: number; - recordsTotal: number; - recordsFiltered: number; + draw?: number; + recordsTotal?: number; + recordsFiltered?: number; data: any; error?: string; } @@ -1587,7 +1587,8 @@ declare namespace DataTables { } interface FunctionColumnData { - (row: any, t: string, s: any, meta: CellMetaSettings): void; + (row: any, t: 'set', s: any, meta: CellMetaSettings): void; + (row: any, t: 'display' | 'sort' | 'filter' | 'type', s: undefined, meta: CellMetaSettings): any; } interface ObjectColumnData { diff --git a/jquery.datatables/jquery.datatables-tests.ts b/jquery.datatables/jquery.datatables-tests.ts index 1bf6e26593..3bcc931a5f 100644 --- a/jquery.datatables/jquery.datatables-tests.ts +++ b/jquery.datatables/jquery.datatables-tests.ts @@ -43,10 +43,17 @@ $(document).ready(function () { sort: "asc" }; - var colDataFunc: DataTables.FunctionColumnData = function (row, type, set, meta) { + var colDataFunc: DataTables.FunctionColumnData = (row: any, type: 'set' | 'display' | 'sort' | 'filter' | 'type', set: any, meta: DataTables.CellMetaSettings) => { meta.col; meta.row; meta.settings; + switch (type) { + case 'set': + row.value = set; + return; + default: + return row.value; + } }; var colRenderObject: DataTables.ObjectColumnRender = { @@ -276,7 +283,7 @@ $(document).ready(function () { bScrollbarLeft: true, bScrollOversize: true } - + //#endregion //#region "Init" diff --git a/jquery.fileupload/index.d.ts b/jquery.fileupload/index.d.ts index 54ebb89c5c..e113d2733c 100644 --- a/jquery.fileupload/index.d.ts +++ b/jquery.fileupload/index.d.ts @@ -198,7 +198,7 @@ interface JQueryFileInputOptions { * handlers using jQuery's Deferred callbacks: * data.submit().done(func).fail(func).always(func); */ - add?: any; + add?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: @@ -228,7 +228,7 @@ interface JQueryFileInputOptions { // Other callbacks: submit?: Function; done?: (e: JQueryEventObject, data: JQueryFileUploadDone) => void; - fail?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; + fail?: (e: JQueryEventObject, data: JQueryFileUploadDone) => void; always?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; progressall?: (e: JQueryEventObject, data: JQueryFileUploadProgressAllObject) => void; start?: (e: JQueryEventObject) => void; @@ -284,6 +284,7 @@ interface JQueryFileUploadXhr { jqXHR: JQueryXHR; result: any; textStatus: string; + errorThrown: any; headers: {[key: string]: any}; } diff --git a/jquery.noty/index.d.ts b/jquery.noty/index.d.ts index 85fc2fca4c..f4bfe4bcb9 100644 --- a/jquery.noty/index.d.ts +++ b/jquery.noty/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for jQuery.noty v2.0 +// Type definitions for jQuery.noty v2.4 // Project: http://needim.github.io/noty/ -// Definitions by: Aaron King +// Definitions by: Aaron King , Tim Helfensdörfer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Project by: Nedim Carter @@ -11,51 +11,60 @@ interface NotyOptions { theme?: string; type?: string; /** Text to show. Can be html or string. */ - text?: string; + text?: string; /** If you want to use queue feature set this true. */ - dismissQueue?: boolean; - /** The note`s optional template like '
' */ - template?: string; - animation?: NotyAnimationOptions; - /** Delay for closing event. Set false for sticky notifications */ - timeout?: any; - /** Adds notification to the beginning of queue when set to true */ - force?: boolean; - modal?: boolean; + dismissQueue?: boolean; + /** adds notification to the beginning of queue when set to true */ + force?: boolean; /** You can set max visible notification for dismissQueue true option */ maxVisible?: number; - /** To close all notifications before show */ + /** The note`s optional template like '
' */ + template?: string; + /** Delay for closing event. Set false for sticky notifications */ + timeout?: any; + /** displays a progress bar */ + progressBar?: boolean; + + animation?: NotyAnimationOptions; + /** backdrop click will close all notifications */ + closeWith?: ('click' | 'button' | 'hover' | 'backdrop')[]; + + /** if true adds an overlay */ + modal?: boolean; + /** if true closes all notifications and shows itself */ killer?: boolean; - closeWith?: any[]; + callback?: NotyCallbackOptions; - /** An array of buttons or false to hide them */ + + /** an array of buttons, for creating confirmation dialogs. */ buttons?: any; } interface NotyAnimationOptions { - open?: any; - close?: any; - easing?: string; - speed?: number; + open?: any; + close?: any; + easing?: string; + speed?: number; } interface NotyCallbackOptions { - onShow?: Function; - afterShow?: Function; - onClose?: Function; - afterClose?: Function; + onShow?: Function; + afterShow?: Function; + onClose?: Function; + afterClose?: Function; + onCloseClick?: Function; } interface NotyStatic { - (notyOptions: NotyOptions); - defaults: NotyOptions; + (notyOptions: NotyOptions); + defaults: NotyOptions; - get(id: any); - close(id: any); - clearQueue(); - closeAll(); - setText(id: any, text: string); - setType(id: any, type: string); + get(id: any); + close(id: any); + clearQueue(); + closeAll(); + setText(id: any, text: string); + setType(id: any, type: string); } interface Noty { @@ -72,7 +81,7 @@ interface Noty { } interface JQueryStatic { - noty: NotyStatic; + noty: NotyStatic; } interface JQuery { diff --git a/jquery.pnotify/index.d.ts b/jquery.pnotify/index.d.ts index 668590e4d6..1d222efb26 100644 --- a/jquery.pnotify/index.d.ts +++ b/jquery.pnotify/index.d.ts @@ -1,12 +1,12 @@ // Type definitions for jquery.pnotify 3.x // Project: https://github.com/sciactive/pnotify -// Definitions by: David Sichau +// Definitions by: David Sichau , Robin Maenhaut // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// type NoticeTypeOptions = "notice" | "info" | "success" | "error"; -type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; +type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome" | PNotifyStyling; type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; interface PNotifyStack { @@ -134,7 +134,7 @@ interface PNotifyOptions { */ text_escape?: boolean; /** - * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) + * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", "fontawesome" or a custom style object) */ styling?: StylingOptions; /** @@ -257,6 +257,36 @@ interface PNotifyOptions { labels?: PNotifyLabel; } +interface PNotifyStyling { + container?: string, + notice?: string, + notice_icon?: string, + info?: string, + info_icon?: string, + success?: string, + success_icon?: string, + error?: string, + error_icon?: string, + // buttons + closer?: string, + pin_down?: string, + pin_up?: string, + // confirm + btn?: string, + btnhover?: string, + btnactive?: string, + btnfocus?: string, + input?: string, + text?: string, + // history + hi_menu?: string, + hi_btn?: string, + hi_btnhov?: string, + hi_hnd?: string, + // reference + athing?: string +} + interface PNotify { /** diff --git a/jquery.pnotify/jquery.pnotify-tests.ts b/jquery.pnotify/jquery.pnotify-tests.ts index c9465e0444..41cd7d3fda 100644 --- a/jquery.pnotify/jquery.pnotify-tests.ts +++ b/jquery.pnotify/jquery.pnotify-tests.ts @@ -243,5 +243,24 @@ function test_pnotify() { animation: 'show' }); + new PNotify({ + title: 'Custom styling', + text: 'Test all custom styling properties', + styling: { + container: "alert", + notice: "alert-warning", + notice_icon: "fa fa-exclamation-circle", + info: "alert-info", + info_icon: "fa fa-info", + success: "alert-success", + success_icon: "fa fa-check", + error: "alert-danger", + error_icon: "fa fa-warning", + closer: "fa fa-times", + pin_up: "fa fa-pause", + pin_down: "fa fa-play" + } + }); + PNotify.removeAll(); } diff --git a/jquery.tools/index.d.ts b/jquery.tools/index.d.ts new file mode 100644 index 0000000000..e511a961fd --- /dev/null +++ b/jquery.tools/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for jQuery TOOLS 1.2 +// Project: https://github.com/jquerytools/jquerytools +// Definitions by: Joe Skeen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare interface JQuery { + overlay(opts?: JQueryTools.overlay.OverlayOptions): JQuery; + overlay(opts?: JQueryTools.overlay.OverlayOptions): T; + data(key: 'overlay'): JQueryTools.overlay.Overlay; +} + +declare interface JQueryStatic { + tools: JQueryTools.ToolsStatic; +} + +/** jQuery Tools (http://jquerytools.github.io/documentation/overlay/index.html) */ +declare namespace JQueryTools { + interface ToolsStatic { + overlay: overlay.OverlayStatic; + } + + namespace overlay { + interface OverlayStatic { + addEffect(effectName: string, + effectFn: (this: Overlay, position: CssOptions, done: () => void) => void, + closeFn: (this: Overlay, done: () => void) => void): void; + } + + interface CssOptions { + [key: string]: any; + } + + interface OverlayOptions { + /** + * A jQuery selector for the closing elements inside the overlay. These + * can be any elements such as links, buttons or images. If this is not + * supplied, a close element is auto-generated. Read more about this in + * defining close actions. + */ + close?: JQuery; + /** + * By default, overlays are closed when the mouse is clicked outside the + * overlay area. Setting this property to false suppresses this behaviour + * which is suitable for modal dialogs. + * @default true + */ + closeOnClick?: boolean; + /** + * By default, overlays are closed when the ESC keyboard key is pressed. + * Setting this property to false suppresses this behaviour. + * @default true + */ + closeOnEsc?: boolean; + /** The speed to close the overlay, in milliseconds */ + closeSpeed?: number; + /** + * The effect to be used when an overlay is opened and closed. This can + * dramatically change the behaviour of the overlay. By default this tool + * uses an effect called "default" which is a simple show/hide effect. + * @default 'default' + */ + effect?: string; + /** + * since 1.2.0. whether overlay stays in the same position while the screen + * is scrolled. This is the default behaviour for all browsers except IE6 + * and below. IE6 does not support fixed positioning. If this property is + * set to false then the overlay is positioned in relationship to the document + * so that when the screen is scrolled then the overlay moves along with the document. + * @default true + */ + fixed?: boolean; + /** + * Previously known as expose. Overlay is very often used together with the + * Mask Tool. Because of this, the support for this feature has been built + * inside the tool. This option accepts the mask configuration. This is either + * a simple string specifying the background color of the mask or a more complex + * object literal specifying more configuration variables. See an example of an + * overlay together with mask. By default masking is disabled. + */ + mask?: string | MaskOptions; + /** + * Specifies how far from the left-hand edge of the screen the overlay should be + * placed. By default the overlay is horizontally centered with the value "center" + * but you can also supply a numerical value specifying a distance in pixels. + * @default 'center' + */ + left?: 'center' | number; + /** + * If enabled then the overlay loads immediately after it has been initialized. + * @default false + */ + load?: boolean; + /** + * By default, there can be only one overlay on the page at once. Setting this + * property to false allows you to have multiple overlay instances. + * @default true + */ + oneInstance?: boolean; + /** + * The speed of the fade-in animation on the "default" effect. Valid values are + * 'slow', 'normal' and 'fast', or you can supply a numerical value (in milliseconds). + * By setting this property to 0, the overlay will appear immediately without any animation. + * @default 'normal' + */ + speed?: 'slow' | 'normal' | 'fast' | number; + /** + * The element to be overlayed (if not specified in the rel attribute of the triggering element). + */ + target?: Element; + /** + * Specifies how far from the top edge of the screen the overlay should be placed. + * Acceptable values are an integer number specifying a distance in pixels, a string + * (such as '15%') specifying a percentage value or "center" in which case the overlay + * is vertically centered. Percentage values work consistently at different screen resolutions. + * @default '10%' + */ + top?: string | number; + + /** + * before the overlay is displayed. The overlay has already been positioned at the + * location from where it will start animating. + */ + onBeforeLoad?: (this: Overlay, event: JQueryEventObject) => void; + /** when the overlay has completely been displayed */ + onLoad?: (this: Overlay, event: JQueryEventObject) => void; + /** before the overlay is closed */ + onBeforeClose?: (this: Overlay, event: JQueryEventObject) => void; + /** when the overlay is closed */ + onClose?: (this: Overlay, event: JQueryEventObject) => void; + } + + interface MaskOptions { + /** CSS color string (i.e. hex value) */ + color?: string; + /** load speed in milliseconds */ + loadSpeed?: number; + /** Opacity of mask. Between 0 and 1. */ + opacity?: number; + } + + interface Overlay { + /** Closes the overlay. */ + close(): Overlay; + /** Returns the closing element(s) as a jQuery object. */ + getClosers(): JQuery; + /** Returns the configuration for the overlay. */ + getConf(): OverlayOptions; + /** Returns the overlayed element as a jQuery object. */ + getOverlay(): JQuery; + /** Returns the triggering element as a jQuery object. */ + getTrigger(): JQuery; + /** Returns `true` if the overlay is opened. */ + isOpened(): boolean; + /** Opens the overlay. */ + load(): Overlay; + } + } +} diff --git a/jquery.tools/jquery.tools-tests.ts b/jquery.tools/jquery.tools-tests.ts new file mode 100644 index 0000000000..f8a4e39f90 --- /dev/null +++ b/jquery.tools/jquery.tools-tests.ts @@ -0,0 +1,182 @@ +/// + +/* from documentation at http://jquerytools.github.io/documentation/overlay/index.html */ + + $("img[rel]").overlay(); + + var triggers = $(".modalInput").overlay({ +  + // some mask tweaks suitable for modal dialogs + mask: { + color: '#ebecff', + loadSpeed: 200, + opacity: 0.9 + }, +  + closeOnClick: false + }); + + var buttons = $("#yesno button").click(function(this: JQuery, e: JQueryEventObject) { +  + // get user input + var yes = buttons.index(this) === 0; +  + // do something with the answer + triggers.eq(0).html("You clicked " + (yes ? "yes" : "no")); + }); + +// select one or more elements to be overlay triggers +$(".my_overlay_trigger").overlay({ + // one configuration property + mask: { + color: '#ccc' + }, + // another property + top: 50 + // ... the rest of the configuration properties +}); + +$("#prompt form").submit(function(this: JQuery, e: JQueryEventObject) { +  + // close the overlay + triggers.eq(1).overlay().close(); + //or more straightforward: + triggers.data('overlay').close(); +  + // get user input + var input = $("input", this).val(); +  + // do something with the answer + triggers.eq(1).html(input); +  + // do not submit the form + return e.preventDefault(); + }); + +$.tools.overlay.addEffect('', function() {}, function() {}); + +/* custom effects */ +$.tools.overlay.addEffect("myEffect", function(position, done) { + /* + - 'this' variable is a reference to the overlay API + - here we use jQuery's fadeIn() method to perform the effect + */ + this.getOverlay().css(position).fadeIn(this.getConf().speed, done); + }, +  + // close function + function(done) { + // fade out the overlay + this.getOverlay().fadeOut(this.getConf().closeSpeed, done); + } +); + +$("#apple img[rel]").overlay({effect: 'apple'}); + + // select the overlay element - and "make it an overlay" + $("#facebox").overlay({ + // custom top position + top: 260, + // some mask tweaks suitable for facebox-looking dialogs + mask: { + // you might also consider a "transparent" color for the mask + color: '#fff', + // load mask a little faster + loadSpeed: 200, + // very transparent + opacity: 0.5 + }, + // disable this for modal dialog-type of overlays + closeOnClick: false, + // load it immediately after the construction + load: true +}); + +$(function() { +  + // if the function argument is given to overlay, + // it is assumed to be the onBeforeLoad event listener + $("a[rel]").overlay({ +  + mask: 'darkred', + effect: 'apple', +  + onBeforeLoad: function() { +  + // grab wrapper element inside content + var wrap = this.getOverlay().find(".contentWrap"); +  + // load the page specified in the trigger + wrap.load(this.getTrigger().attr("href")); + } +  + }); +}); + +$(function() { + // positions for each overlay + var positions = [ + [0, 530], + [400, 20], + [400, 530], + [0, 20] + ]; +  + // setup triggers + $("button[rel]").each(function(this: JQuery, i: number) { +  + $(this).overlay({ +  + // common configuration for each overlay + oneInstance: false, + closeOnClick: false, +  + // setup custom finish position + top: positions[i][0], + left: positions[i][1], +  + // use apple effect + effect: 'apple' +  + }); + }); +}); + +// loading animation +$.tools.overlay.addEffect("drop", function(css, done) { +  + // use Overlay API to gain access to crucial elements + var conf = this.getConf(), + overlay = this.getOverlay(); +  + // determine initial position for the overlay + if (conf.fixed) { + css['position'] = 'fixed'; + } else { + css['top'] += $(window).scrollTop(); + css['left'] += $(window).scrollLeft(); + css['position'] = 'absolute'; + } +  + // position the overlay and show it + overlay.css(css).show(); +  + // begin animating with our custom easing + overlay.animate( + { top: '+=55', opacity: 1, width: '+=20'}, 400, 'drop', done + ); +  + /* closing animation */ +}, function(done) { + this.getOverlay().animate( + {top:'-=55', opacity:0, width:'-=20'}, 300, 'drop', + function(this: JQuery) { + $(this).hide(); + done.call(null); + }); +}); + +$("img[rel]").overlay({ + effect: 'drop', + mask: '#789' +}); diff --git a/jquery.tools/tsconfig.json b/jquery.tools/tsconfig.json new file mode 100644 index 0000000000..64e79cb10d --- /dev/null +++ b/jquery.tools/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", + "jquery.tools-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.tools/tslint.json b/jquery.tools/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jquery.tools/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jquery.validation/index.d.ts b/jquery.validation/index.d.ts index 953755a065..2bb690c07e 100644 --- a/jquery.validation/index.d.ts +++ b/jquery.validation/index.d.ts @@ -217,6 +217,7 @@ declare namespace JQueryValidation interface Validator { element(element: string|JQuery): boolean; + checkForm(): boolean; /** * Validates the form, returns true if it is valid, false otherwise. */ diff --git a/jquery.validation/jquery.validation-tests.ts b/jquery.validation/jquery.validation-tests.ts index 15bb9f790c..0b2de520f2 100644 --- a/jquery.validation/jquery.validation-tests.ts +++ b/jquery.validation/jquery.validation-tests.ts @@ -208,6 +208,7 @@ function test_methods() { $("#myform").submit(); $("#myinput").attr(rules); }); + $("#myform").validate().checkForm(); $("#myform").validate().form(); $("#myform").validate().element("#myselect"); $("#myform").validate().element($("#myselect")); diff --git a/jquery/index.d.ts b/jquery/index.d.ts index e0bf072983..3a785530aa 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -786,6 +786,15 @@ interface JQueryStatic { */ ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * 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/} + */ + ajaxTransport(dataType: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + ajaxSettings: JQueryAjaxSettings; /** diff --git a/js-data-http/index.d.ts b/js-data-http/index.d.ts index 7fe3b50ff0..2fa9c0e09a 100644 --- a/js-data-http/index.d.ts +++ b/js-data-http/index.d.ts @@ -1,22 +1,20 @@ -// Type definitions for JSData Http Adapter v1.2.0 -// Project: https://github.com/js-data/js-data-http +// Type definitions for JSData Http Adapter 1.2 +// Project: https://github.com/js-data/js-data-http 2.2 // Definitions by: Stefan Steinhart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - import * as JSData from 'js-data'; declare module 'js-data' { interface DSHttpAdapterOptions { - serialize?: (resourceName:string, data:any)=>any; - deserialize?: (resourceName:string, data:any)=>any; - queryTransform?: (resourceName:string, params:DSFilterParams)=>any; + serialize?: (resourceName: string, data: any) => any; + deserialize?: (resourceName: string, data: any) => any; + queryTransform?: (resourceName: string, params: DSFilterParams) => any; httpConfig?: any; forceTrailingSlash?: boolean; - log?: boolean | ((message?:any, ...optionalParams:any[])=> void); - error?: boolean | ((message?:any, ...optionalParams:any[])=> void); + log?: boolean | ((message?: any, ...optionalParams: any[]) => void); + error?: boolean | ((message?: any, ...optionalParams: any[]) => void); basePath?: string; verbsUseBasePath?: string; } @@ -30,20 +28,20 @@ declare module 'js-data' { interface DSHttpAdapter extends IDSAdapter { - new(options?:DSHttpAdapterOptions):DSHttpAdapter; + new(options?: DSHttpAdapterOptions): DSHttpAdapter; defaults: DSHttpAdapterOptions; http: any; // DSHttpAdapter uses axios so options are axios config objects. - HTTP(options?:Object):JSDataPromise; - DEL(url:string, data?:Object, options?:Object):JSDataPromise; - GET(url:string, data?:Object, options?:Object):JSDataPromise; - POST(url:string, data?:Object, options?:Object):JSDataPromise; - PUT(url:string, data?:Object, options?:Object):JSDataPromise; + HTTP(options?: Object): JSDataPromise; + DEL(url: string, data?: Object, options?: Object): JSDataPromise; + GET(url: string, data?: Object, options?: Object): JSDataPromise; + POST(url: string, data?: Object, options?: Object): JSDataPromise; + PUT(url: string, data?: Object, options?: Object): JSDataPromise; } } -declare var DSHttpAdapter:JSData.DSHttpAdapter; +declare var DSHttpAdapter: JSData.DSHttpAdapter; export = DSHttpAdapter; export as namespace DSHttpAdapter; \ No newline at end of file diff --git a/js-data-http/js-data-http-tests.ts b/js-data-http/js-data-http-tests.ts index 1b863737ea..d98cdd642a 100644 --- a/js-data-http/js-data-http-tests.ts +++ b/js-data-http/js-data-http-tests.ts @@ -1,8 +1,7 @@ -/// import * as JSData from 'js-data'; import DSHttpAdapter = require("js-data-http"); -import * as axios from 'axios'; +declare var axios: any; var adapter = new DSHttpAdapter(); var store = new JSData.DS(); @@ -11,12 +10,12 @@ store.registerAdapter('http', adapter, { default: true }); adapter.defaults.basePath = '/api'; adapter.http = axios; -var ADocument:JSData.DSResourceDefinition = store.defineResource('document'); +var ADocument: JSData.DSResourceDefinition = store.defineResource('document'); ADocument.inject({ id: 5, author: 'John' }); // bypass the data store -adapter.update(ADocument, 5, { author: 'Johnny' }).then(function (document:any) { +adapter.update(ADocument, 5, { author: 'Johnny' }).then((document: any) => { document; // { id: 5, author: 'Johnny' } // The updated document has NOT been injected into the data store because we bypassed the data store @@ -24,7 +23,7 @@ adapter.update(ADocument, 5, { author: 'Johnny' }).then(function (document:any) }); // Normally you would just go through the data store -ADocument.update(5, { author: 'Johnny' }).then(function (document:any) { +ADocument.update(5, { author: 'Johnny' }).then((document: any) => { document; // { id: 5, author: 'Johnny' } // the updated document has been injected into the data store @@ -35,7 +34,7 @@ ADocument.inject({ id: 5, author: 'John' }); ADocument.inject({ id: 6, author: 'John' }); // bypass the data store -adapter.updateAll(ADocument, { author: 'Johnny' }, { author: 'John' }).then(function (documents) { +adapter.updateAll(ADocument, { author: 'Johnny' }, { author: 'John' }).then(documents => { documents[0]; // { id: 5, author: 'Johnny' } // The updated documents have NOT been injected into the data store because we bypassed the data store @@ -44,7 +43,7 @@ adapter.updateAll(ADocument, { author: 'Johnny' }, { author: 'John' }).then(func }); // Normally you would just go through the data store -ADocument.updateAll({ author: 'Johnny' }, { author: 'John' }).then(function (documents) { +ADocument.updateAll({ author: 'Johnny' }, { author: 'John' }).then(documents => { documents[0]; // { id: 5, author: 'Johnny' } // the updated documents have been injected into the data store @@ -52,44 +51,44 @@ ADocument.updateAll({ author: 'Johnny' }, { author: 'John' }).then(function (doc ADocument.filter({ author: 'Johnny' }); // [{...}, {...}] }); -adapter.PUT('/user/1', { name: 'Johnny' }).then(function (data) { +adapter.PUT('/user/1', { name: 'Johnny' }).then(data => { data.data; // { id: 1, name: 'Johnny', ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -adapter.POST('/user/1', { name: 'John' }).then(function (data) { +adapter.POST('/user/1', { name: 'John' }).then(data => { data.data; // { id: 1, name: 'John', ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -adapter.HTTP({ url: '/user/1', method: 'put', data: { name: 'Johnny' }}).then(function (data) { +adapter.HTTP({ url: '/user/1', method: 'put', data: { name: 'Johnny' }}).then(data => { data.data; // { id: 1, name: 'Johnny', ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -adapter.GET('/user/1').then(function (data) { +adapter.GET('/user/1').then(data => { data.data; // { id: 1, ... } data.headers; // {...} data.status; // 200 - data.config; //{...} + data.config; // {...} }); -var User:JSData.DSResourceDefinition = store.defineResource('user'); +var User: JSData.DSResourceDefinition = store.defineResource('user'); -var params:any = { +var params: any = { age: { '>': 30 } }; // bypass the data store -adapter.findAll(User, params).then(function (users) { +adapter.findAll(User, params).then(users => { // users[0].age; 55 // etc., etc. // the users have NOT been injected into the data store because we bypassed the data store @@ -97,7 +96,7 @@ adapter.findAll(User, params).then(function (users) { }); // normally you would go through the data store -User.findAll(params).then(function (users) { +User.findAll(params).then(users => { // users[0].age; 55 // etc., etc. // the users have been injected into the data store @@ -105,7 +104,7 @@ User.findAll(params).then(function (users) { }); // bypass the data store -adapter.find(ADocument, 5).then(function (document:any) { +adapter.find(ADocument, 5).then((document: any) => { document; // { id: 5, author: 'John Anderson' } // the document has NOT been injected into the data store because we bypassed the data store @@ -113,25 +112,25 @@ adapter.find(ADocument, 5).then(function (document:any) { }); // Normally you would just go through the data store -ADocument.find(5).then(function (document:any) { +ADocument.find(5).then((document: any) => { document; // { id: 5, author: 'John Anderson' } // the document has been injected into the data store ADocument.get(document.id); // { id: 5, author: 'John Anderson' } }); -var params:any = { +var params: any = { author: 'John' }; // bypass the data store -adapter.destroyAll(ADocument, params).then(function () { +adapter.destroyAll(ADocument, params).then(() => { // the documents have NOT been ejected from the data store because we bypassed the data store ADocument.filter(params); // [{...}, {...}, ...] }); // normally you would go through the data store -ADocument.destroyAll(params).then(function () { +ADocument.destroyAll(params).then(() => { // the documents have been ejected from the data store ADocument.filter(params); // [] }); @@ -139,26 +138,26 @@ ADocument.destroyAll(params).then(function () { ADocument.inject({ id: 5, author: 'John' }); // bypass the data store -adapter.destroy(ADocument, 5).then(function () { +adapter.destroy(ADocument, 5).then(() => { // the document is still in the data store because we bypassed the data store - //ADocument.get(document.id); // { id: 5, author: 'John' } + // ADocument.get(document.id); // { id: 5, author: 'John' } }); // Normally you would just go through the data store -ADocument.destroy(5).then(function () { +ADocument.destroy(5).then(() => { // the document has been ejected from the data store - //ADocument.get(document.id); // undefined + // ADocument.get(document.id); // undefined }); -adapter.DEL('/user/1').then(function (data) { +adapter.DEL('/user/1').then(data => { data.data; // 1 data.headers; // {...} data.status; // 204 - data.config; //{...} + data.config; // {...} }); // bypass the data store -adapter.create(ADocument, { author: 'John' }).then(function (document:any) { +adapter.create(ADocument, { author: 'John' }).then((document: any) => { document; // { id: 5, author: 'John' } // The new document has NOT been injected into the data store because we bypassed the data store @@ -166,7 +165,7 @@ adapter.create(ADocument, { author: 'John' }).then(function (document:any) { }); // Normally you would just go through the data store -ADocument.create({ author: 'John' }).then(function (document:any) { +ADocument.create({ author: 'John' }).then((document: any) => { document; // { id: 5, author: 'John' } // the new document has been injected into the data store diff --git a/js-data-http/tslint.json b/js-data-http/tslint.json new file mode 100644 index 0000000000..394d3ce319 --- /dev/null +++ b/js-data-http/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-misused-new": false + } +} diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 32ef8b30ff..690279bbe4 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,36 +1,32 @@ -// Type definitions for js-md5 v0.3.0 +// Type definitions for js-md5 0.4 // Project: https://github.com/emn178/js-md5 -// Definitions by: Roland Greim +// Definitions by: Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ -/// +declare namespace md5 { + type message = string | any[] | Uint8Array | ArrayBuffer; -interface JQuery { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; + interface Md5 { + array: () => number[]; + arrayBuffer: () => ArrayBuffer; + buffer: () => ArrayBuffer; + digest: () => number[]; + hex: () => string; + toString: () => string; + update: (message: message) => Md5; + } + + interface md5 { + (message: message): string; + hex: (message: message) => string; + array: (message: message) => number[]; + digest: (message: message) => number[]; + arrayBuffer: (message: message) => ArrayBuffer; + buffer: (message: message) => ArrayBuffer; + create: () => Md5; + update: (message: message) => Md5; + } } -interface JQueryStatic { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; -} - -interface md5 { - (value: string): string; - (value: Array): string; - (value: Uint8Array): string; -} - -interface String { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; -} - -declare module "js-md5" { - export = md5; -} - -declare var md5: md5; +declare const md5: md5.md5; +export = md5; diff --git a/js-md5/js-md5-tests.ts b/js-md5/js-md5-tests.ts index 984a919ec3..231b12ebf2 100644 --- a/js-md5/js-md5-tests.ts +++ b/js-md5/js-md5-tests.ts @@ -1,20 +1,29 @@ +import md5 = require("js-md5"); +let str: string = md5.hex('The quick brown fox jumps over the lazy dog'); +str = md5('The quick brown fox jumps over the lazy dog'); +let arr: number[] = md5.digest('The quick brown fox jumps over the lazy dog'); +arr = md5.array('The quick brown fox jumps over the lazy dog'); +let buf: ArrayBuffer = md5.arrayBuffer('The quick brown fox jumps over the lazy dog'); +buf = md5.buffer('The quick brown fox jumps over the lazy dog'); -md5('Message to hash'); -md5(''); -md5('中文'); -md5([]); -md5(new Uint8Array([])); +const hash1 = md5.create(); +hash1.update('The quick brown fox jumps over the lazy dog'); +str = hash1.hex(); +str = hash1.toString(); +arr = hash1.digest(); +arr = hash1.array(); +buf = hash1.arrayBuffer(); +buf = hash1.buffer(); -$.md5('message'); -$.md5('Message to hash'); -$.md5(''); -$.md5('中文'); -$.md5([]); -$.md5(new Uint8Array([])); +const hash2 = md5.update('The quick brown fox jumps over the lazy dog'); +str = hash2.hex(); +str = hash2.toString(); +arr = hash2.digest(); +arr = hash2.array(); +buf = hash2.arrayBuffer(); +buf = hash2.buffer(); -'message'.md5('Message to hash'); -'message'.md5(''); -'message'.md5('中文'); -'message'.md5([]); -'message'.md5(new Uint8Array([])); \ No newline at end of file +str = md5([]); +str = md5(new Uint8Array([])); +str = md5(new ArrayBuffer(0)); diff --git a/js-md5/tsconfig.json b/js-md5/tsconfig.json index eceeb1fb3d..f0ae291e30 100644 --- a/js-md5/tsconfig.json +++ b/js-md5/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +19,4 @@ "index.d.ts", "js-md5-tests.ts" ] -} \ No newline at end of file +} diff --git a/js-md5/tslint.json b/js-md5/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/js-md5/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/js-quantities/js-quantities-tests.ts b/js-quantities/js-quantities-tests.ts index f743d9a8e5..95819381b5 100644 --- a/js-quantities/js-quantities-tests.ts +++ b/js-quantities/js-quantities-tests.ts @@ -123,8 +123,8 @@ qty = Qty('1.1234 m'); qty.format(); // same units, default formatter => '1.234 m' qty.format('cm'); // converted to 'cm', default formatter => '123.45 cm' -var configurableRoundingFormatter = function (maxDecimals: number) { - return function (scalar: number, units: string) { +var configurableRoundingFormatter = (maxDecimals: number) => { + return (scalar: number, units: string) => { var pow = Math.pow(10, maxDecimals); var rounded = Math.round(scalar * pow) / pow; @@ -146,7 +146,7 @@ qty.format(); // same units, current default formatter => '1.12 m' Qty('37 tempC').to('tempF'); // => 98.6 tempF -let scalar: number = 42; +const scalar: number = 42; Qty('100 tempC').add('10 degC'); // 110 tempC Qty('100 tempC').sub('10 degC'); // 90 tempC @@ -180,17 +180,17 @@ try { // From project spec -describe("js-quantities", function () { +describe("js-quantities", () => { "use strict"; - describe("initialization", function () { - it("should create unit only", function () { + describe("initialization", () => { + it("should create unit only", () => { var qty = Qty("m"); expect(qty.numerator).toEqual([""]); expect(qty.scalar).toBe(1); }); - it("should create unitless", function () { + it("should create unitless", () => { var qty = Qty("1"); expect(qty.toFloat()).toBe(1); expect(qty.numerator).toEqual(["<1>"]); @@ -201,21 +201,21 @@ describe("js-quantities", function () { expect(qty.denominator).toEqual(["<1>"]); }); - it("should create unitless from numbers", function () { + it("should create unitless from numbers", () => { var qty = Qty(1.5); expect(qty.toFloat()).toBe(1.5); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create from numbers with explicit units", function () { + it("should create from numbers with explicit units", () => { var qty = Qty(1.5, "m"); expect(qty.scalar).toBe(1.5); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("temperatures should have base unit in kelvin", function () { + it("temperatures should have base unit in kelvin", () => { var qty = Qty("1 tempK").toBase(); expect(qty.scalar).toBe(1); expect(qty.units()).toBe("tempK"); @@ -233,7 +233,7 @@ describe("js-quantities", function () { expect(qty.units()).toBe("tempK"); }); - it("temperature degrees should have base unit in kelvin", function () { + it("temperature degrees should have base unit in kelvin", () => { var qty = Qty("1 degK").toBase(); expect(qty.scalar).toBe(1); expect(qty.units()).toBe("degK"); @@ -251,50 +251,50 @@ describe("js-quantities", function () { expect(qty.units()).toBe("degK"); }); - it("should not create temperatures below absolute zero", function () { - expect(function () { Qty("-1 tempK"); }).toThrow("Temperatures must not be less than absolute zero"); - expect(function () { Qty("-273.16 tempC"); }).toThrow("Temperatures must not be less than absolute zero"); - expect(function () { Qty("-459.68 tempF"); }).toThrow("Temperatures must not be less than absolute zero"); - expect(function () { Qty("-1 tempR"); }).toThrow("Temperatures must not be less than absolute zero"); + it("should not create temperatures below absolute zero", () => { + expect(() => { Qty("-1 tempK"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { Qty("-273.16 tempC"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { Qty("-459.68 tempF"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { Qty("-1 tempR"); }).toThrow("Temperatures must not be less than absolute zero"); var qty = Qty("1 tempK"); - expect(function () { qty.mul("-1"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.mul("-1"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("0 tempK"); - expect(function () { qty.sub("1 degK"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degK"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("-273.15 tempC"); - expect(function () { qty.sub("1 degC"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degC"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("-459.67 tempF"); - expect(function () { qty.sub("1 degF"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degF"); }).toThrow("Temperatures must not be less than absolute zero"); qty = Qty("0 tempR"); - expect(function () { qty.sub("1 degR"); }).toThrow("Temperatures must not be less than absolute zero"); + expect(() => { qty.sub("1 degR"); }).toThrow("Temperatures must not be less than absolute zero"); }); - it("should create simple", function () { + it("should create simple", () => { var qty = Qty("1m"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create negative", function () { + it("should create negative", () => { var qty = Qty("-1m"); expect(qty.scalar).toBe(-1); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create compound", function () { + it("should create compound", () => { var qty = Qty("1 N*m"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["", ""]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create pressure units in term of height of water", function () { + it("should create pressure units in term of height of water", () => { var qty = Qty("1 inH2O"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual([""]); @@ -304,14 +304,14 @@ describe("js-quantities", function () { expect(qty.numerator).toEqual([""]); }); - it("should create with denominator", function () { + it("should create with denominator", () => { var qty = Qty("1 m/s"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual([""]); expect(qty.denominator).toEqual([""]); }); - it("should create with denominator only", function () { + it("should create with denominator only", () => { var qty = Qty("1 /s"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); @@ -328,7 +328,7 @@ describe("js-quantities", function () { expect(qty.denominator).toEqual([""]); }); - it("should create with powers", function () { + it("should create with powers", () => { var qty = Qty("1 m^2/s^2"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["", ""]); @@ -343,14 +343,14 @@ describe("js-quantities", function () { expect(qty.denominator).toEqual(["", "", "", "", ""]); }); - it("should create with zero power", function () { + it("should create with zero power", () => { var qty = Qty("1 m^0"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["<1>"]); expect(qty.denominator).toEqual(["<1>"]); }); - it("should create with negative powers", function () { + it("should create with negative powers", () => { var qty = Qty("1 m^2 s^-2"); expect(qty.scalar).toBe(1); expect(qty.numerator).toEqual(["", ""]); @@ -358,57 +358,57 @@ describe("js-quantities", function () { expect(qty.same(Qty("1 m^2/s^2"))).toBe(true); }); - it("should accept powers without ^ syntax (simple)", function () { + it("should accept powers without ^ syntax (simple)", () => { var qty1 = Qty("1 m2"); var qty2 = Qty("1 m^2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should accept powers without ^ syntax (negative power)", function () { + it("should accept powers without ^ syntax (negative power)", () => { var qty1 = Qty("1 m-2"); var qty2 = Qty("1 m^-2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should accept powers without ^ syntax (compound)", function () { + it("should accept powers without ^ syntax (compound)", () => { var qty1 = Qty("1 m^2 kg^2 J^2/s^2"); var qty2 = Qty("1 m2 kg2 J2/s2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should accept powers without ^ syntax (compound and negative power)", function () { + it("should accept powers without ^ syntax (compound and negative power)", () => { var qty1 = Qty("1 m^2 kg^2 J^2 s^-2"); var qty2 = Qty("1 m2 kg2 J2 s-2"); expect(qty1.eq(qty2)).toBe(true); }); - it("should throw 'Unit not recognized' error when initializing with an invalid unit", function () { - expect(function () { Qty("aa"); }).toThrow("Unit not recognized"); - expect(function () { Qty("m/aa"); }).toThrow("Unit not recognized"); - expect(function () { Qty("m-"); }).toThrow("Unit not recognized"); - expect(function () { Qty("N*m"); }).not.toThrow("Unit not recognized"); + it("should throw 'Unit not recognized' error when initializing with an invalid unit", () => { + expect(() => { Qty("aa"); }).toThrow("Unit not recognized"); + expect(() => { Qty("m/aa"); }).toThrow("Unit not recognized"); + expect(() => { Qty("m-"); }).toThrow("Unit not recognized"); + expect(() => { Qty("N*m"); }).not.toThrow("Unit not recognized"); // mm is millimeter, but mmm is not a valid unit - expect(function () { Qty("mmm"); }).toThrow("Unit not recognized"); + expect(() => { Qty("mmm"); }).toThrow("Unit not recognized"); }); - it("should accept empty string as unitless 1", function () { + it("should accept empty string as unitless 1", () => { expect(Qty("").same(Qty("1"))).toBe(true); expect(Qty(" ").same(Qty("1"))).toBe(true); }); - it("should throw error when passing NaN", function () { + it("should throw error when passing NaN", () => { expect( - function () { Qty(NaN); } + () => { Qty(NaN); } ).toThrow("Only string, number or quantity accepted as single " + "initialization value"); }); - it("should throw 'Unit not recognized' error when initializing with an invalid unit and a 0 exponent", function () { - expect(function () { Qty("3p0"); }).toThrow("Unit not recognized"); - expect(function () { Qty("3p-0"); }).toThrow("Unit not recognized"); + it("should throw 'Unit not recognized' error when initializing with an invalid unit and a 0 exponent", () => { + expect(() => { Qty("3p0"); }).toThrow("Unit not recognized"); + expect(() => { Qty("3p-0"); }).toThrow("Unit not recognized"); }); - it("should set baseScalar", function () { + it("should set baseScalar", () => { var qty = Qty("0.018 MPa"); expect(qty.baseScalar).toBe(18000); @@ -416,18 +416,18 @@ describe("js-quantities", function () { expect(qty.baseScalar).toBe(0.000066); }); - it("should keep init value as is", function () { + it("should keep init value as is", () => { var initValue = " 66 cm3 "; var qty = Qty(initValue); expect(qty.initValue).toEqual(initValue); }); - it("should allow whitespace-wrapped value", function () { - expect(function () { Qty(" 2 MPa "); }).not.toThrow(); + it("should allow whitespace-wrapped value", () => { + expect(() => { Qty(" 2 MPa "); }).not.toThrow(); }); - it("should allow whitespaces between sign and scalar", function () { + it("should allow whitespaces between sign and scalar", () => { var qty = Qty("- 1m"); expect(qty.scalar).toEqual(-1); @@ -435,13 +435,13 @@ describe("js-quantities", function () { }); it("should throw an error when parsing negative quantity " + - "with no scalar", function () { - expect(function () { Qty("-m"); }).toThrow("Unit not recognized"); + "with no scalar", () => { + expect(() => { Qty("-m"); }).toThrow("Unit not recognized"); }); }); - describe("isCompatible", function () { - it("should return true with compatible quantities", function () { + describe("isCompatible", () => { + it("should return true with compatible quantities", () => { var qty1 = Qty("1 m*kg/s"); var qty2 = Qty("1 in*pound/min"); expect(qty1.isCompatible(qty2)).toBe(true); @@ -449,15 +449,15 @@ describe("js-quantities", function () { expect(qty1.isCompatible(qty2)).toBe(false); }); - it("should return true with dimensionless quantities", function () { + it("should return true with dimensionless quantities", () => { var qty1 = Qty("1"); var qty2 = Qty("2"); expect(qty1.isCompatible(qty2)).toBe(true); }); }); - describe("conversion", function () { - it("should convert to base units", function () { + describe("conversion", () => { + it("should convert to base units", () => { var qty = Qty("100 cm"); expect(qty.toBase().scalar).toBe(1); expect(qty.toBase().units()).toBe("m"); @@ -469,7 +469,7 @@ describe("js-quantities", function () { expect(qty.toBase().units()).toBe("m2/s2"); }); - it("should convert to compatible units", function () { + it("should convert to compatible units", () => { var qty = Qty("10 cm"); expect(qty.to("ft").scalar).toBe(Qty.divSafe(0.1, 0.3048)); qty = Qty("2m^3"); @@ -492,17 +492,17 @@ describe("js-quantities", function () { expect(qty.to("cm^3").scalar).toBe(773); }); - describe('percents', function () { - it("should convert from % to unitless", function () { + describe('percents', () => { + it("should convert from % to unitless", () => { expect(Qty("10 %").to("").same(Qty("0.1"))).toBe(true); }); - it("should convert from unitless to %", function () { + it("should convert from unitless to %", () => { expect(Qty("0.1").to("%").same(Qty("10 %"))).toBe(true); }); }); - it("should convert temperatures to compatible units", function () { + it("should convert temperatures to compatible units", () => { var qty = Qty("0 tempK"); expect(qty.to("tempC").scalar).toBe(-273.15); @@ -516,7 +516,7 @@ describe("js-quantities", function () { expect(qty.to("tempF").scalar).toBeCloseTo(32, 10); }); - it("should convert temperature degrees to compatible units", function () { + it("should convert temperature degrees to compatible units", () => { var qty = Qty("0 degK"); expect(qty.to("degC").scalar).toBe(0); @@ -530,7 +530,7 @@ describe("js-quantities", function () { expect(qty.to("degF").scalar).toBe(18); }); - it("should convert temperature degrees to temperatures", function () { + it("should convert temperature degrees to temperatures", () => { // according to ruby-units, deg -> temp conversion adds the degress to 0 kelvin before converting var qty = Qty("100 degC"); expect(qty.to("tempC").scalar).toBeCloseTo(-173.15, 10); @@ -542,7 +542,7 @@ describe("js-quantities", function () { expect(qty.to("tempF").scalar).toBeCloseTo(1, 10); }); - it("should convert temperatures to temperature degrees", function () { + it("should convert temperatures to temperature degrees", () => { // according to ruby-units, temp -> deg conversion always uses the 0 relative degrees var qty = Qty("100 tempC"); expect(qty.to("degC").scalar).toBe(100); @@ -560,7 +560,7 @@ describe("js-quantities", function () { expect(qty.to("degF").scalar).toBe(18); }); - it("should calculate inverses", function () { + it("should calculate inverses", () => { var qty = Qty("1 ohm"); var result = qty.to("siemens"); expect(result.scalar).toBe(1); @@ -583,7 +583,7 @@ describe("js-quantities", function () { // cannot inverse a quantity with a 0 scalar qty = Qty("0 ohm"); - expect(function () { qty.inverse(); }).toThrow("Divide by zero"); + expect(() => { qty.inverse(); }).toThrow("Divide by zero"); qty = Qty("10 ohm").inverse(); result = qty.to("S"); @@ -595,7 +595,7 @@ describe("js-quantities", function () { expect(qty.to("ft").scalar).toBeCloseTo(1, 10); }); - it("should return itself if target units are the same", function () { + it("should return itself if target units are the same", () => { var qty = Qty("123 cm3"); expect(qty.to("cm3")).toBe(qty); @@ -605,7 +605,7 @@ describe("js-quantities", function () { expect(qty.to("ug")).toBe(qty); }); - it("should be cached", function () { + it("should be cached", () => { var qty = Qty("100 m"), converted = qty.to("ft"); @@ -613,14 +613,14 @@ describe("js-quantities", function () { }); }); - describe("comparison", function () { - it("should return true when comparing equal quantities", function () { + describe("comparison", () => { + it("should return true when comparing equal quantities", () => { var qty1 = Qty("1cm"); var qty2 = Qty("10mm"); expect(qty1.eq(qty2)).toBe(true); }); - it("should compare compatible quantities", function () { + it("should compare compatible quantities", () => { var qty1 = Qty("1cm"); var qty2 = Qty("1mm"); var qty3 = Qty("10mm"); @@ -628,7 +628,7 @@ describe("js-quantities", function () { expect(qty1.compareTo(qty2)).toBe(1); expect(qty2.compareTo(qty1)).toBe(-1); expect(qty1.compareTo(qty3)).toBe(0); - expect(function () { qty1.compareTo(qty4); }).toThrow("Incompatible units"); + expect(() => { qty1.compareTo(qty4); }).toThrow("Incompatible units"); expect(qty1.lt(qty2)).toBe(false); expect(qty1.lt(qty3)).toBe(false); @@ -638,7 +638,7 @@ describe("js-quantities", function () { expect(qty2.gt(qty1)).toBe(false); }); - it("should compare identical quantities", function () { + it("should compare identical quantities", () => { var qty1 = Qty("1cm"); var qty2 = Qty("1cm"); var qty3 = Qty("10mm"); @@ -646,7 +646,7 @@ describe("js-quantities", function () { expect(qty1.same(qty3)).toBe(false); }); - it("should accept strings as parameter", function () { + it("should accept strings as parameter", () => { var qty = Qty("1 cm"); expect(qty.lt("0.5 cm")).toBe(false); expect(qty.lte("1 cm")).toBe(true); @@ -656,9 +656,9 @@ describe("js-quantities", function () { }); - describe("non-ASCII character", function () { - describe("µ", function () { - it("should be supported as prefix", function () { + describe("non-ASCII character", () => { + describe("µ", () => { + it("should be supported as prefix", () => { // µ as greek letter expect(Qty("1 \u03BCm").eq(Qty("1 um"))).toBe(true); // µ as micro sign @@ -666,8 +666,8 @@ describe("js-quantities", function () { }); }); - describe("Ω", function () { - it("should be accepted as unit for ohm", function () { + describe("Ω", () => { + it("should be accepted as unit for ohm", () => { // Ω as greek letter expect(Qty("1 \u03A9").eq(Qty("1 ohm"))).toBe(true); // Ω as ohm sign @@ -676,9 +676,9 @@ describe("js-quantities", function () { }); }); - describe("math", function () { + describe("math", () => { - it("should add quantities", function () { + it("should add quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); expect(qty1.add(qty2).scalar).toBe(5.5); @@ -700,26 +700,26 @@ describe("js-quantities", function () { expect(result.units()).toBe("cm"); }); - it("should fail to add unlike quantities", function () { + it("should fail to add unlike quantities", () => { var qty1 = Qty("3m"); var qty2 = Qty("2s"); - expect(function () { qty1.add(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.add(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.add(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.add(qty1); }).toThrow("Incompatible units"); }); - it("should fail to add inverse quantities", function () { + it("should fail to add inverse quantities", () => { var qty1 = Qty("10S"); var qty2 = qty1.inverse(); - expect(function () { qty1.add(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.add(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.add(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.add(qty1); }).toThrow("Incompatible units"); qty1 = Qty("10S"); qty2 = Qty("0.1ohm"); - expect(function () { qty1.add(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.add(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.add(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.add(qty1); }).toThrow("Incompatible units"); }); - it("should subtract quantities", function () { + it("should subtract quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); expect(qty1.sub(qty2).scalar).toBe(-0.5); @@ -737,26 +737,26 @@ describe("js-quantities", function () { expect(result.units()).toBe("cm"); }); - it("should fail to subtract unlike quantities", function () { + it("should fail to subtract unlike quantities", () => { var qty1 = Qty("3m"); var qty2 = Qty("2s"); - expect(function () { qty1.sub(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.sub(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.sub(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.sub(qty1); }).toThrow("Incompatible units"); }); - it("should fail to subtract inverse quantities", function () { + it("should fail to subtract inverse quantities", () => { var qty1 = Qty("10S"); var qty2 = qty1.inverse(); - expect(function () { qty1.sub(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.sub(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.sub(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.sub(qty1); }).toThrow("Incompatible units"); qty1 = Qty("10S"); qty2 = Qty("0.1ohm"); - expect(function () { qty1.sub(qty2); }).toThrow("Incompatible units"); - expect(function () { qty2.sub(qty1); }).toThrow("Incompatible units"); + expect(() => { qty1.sub(qty2); }).toThrow("Incompatible units"); + expect(() => { qty2.sub(qty1); }).toThrow("Incompatible units"); }); - it("should multiply quantities", function () { + it("should multiply quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); var result = qty1.mul(qty2); @@ -791,7 +791,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("m2"); }); - it("should multiply unlike quantities", function () { + it("should multiply unlike quantities", () => { var qty1 = Qty("2.5 m"); var qty2 = Qty("3 N"); @@ -806,7 +806,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("kg"); }); - it("should multiply inverse quantities", function () { + it("should multiply inverse quantities", () => { var qty1 = Qty("10S"); var qty2 = Qty(".5S").inverse(); // 2/S var qty3 = qty1.inverse(); // .1/S @@ -832,13 +832,13 @@ describe("js-quantities", function () { expect(result.units()).toBe(""); }); - it("should divide quantities", function () { + it("should divide quantities", () => { var qty1 = Qty("2.5m"); var qty2 = Qty("3m"); var qty3 = Qty("0m"); - expect(function () { qty1.div(qty3); }).toThrow("Divide by zero"); - expect(function () { qty1.div(0); }).toThrow("Divide by zero"); + expect(() => { qty1.div(qty3); }).toThrow("Divide by zero"); + expect(() => { qty1.div(0); }).toThrow("Divide by zero"); expect(qty3.div(qty1).scalar).toBe(0); var result = qty1.div(qty2); @@ -860,7 +860,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("m"); }); - it("should divide unlike quantities", function () { + it("should divide unlike quantities", () => { var qty1 = Qty("7.5kg"); var qty2 = Qty("2.5m^2"); @@ -869,7 +869,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("kg/m2"); }); - it("should divide inverse quantities", function () { + it("should divide inverse quantities", () => { var qty1 = Qty("10 S"); var qty2 = Qty(".5 S").inverse(); // 2/S var qty3 = qty1.inverse(); // .1/S @@ -893,9 +893,9 @@ describe("js-quantities", function () { }); - describe("math with temperatures", function () { + describe("math with temperatures", () => { - it("should add temperature degrees", function () { + it("should add temperature degrees", () => { var qty = Qty("2degC"); expect(qty.add("3degF").scalar).toBeCloseTo(11 / 3, 10); expect(qty.add("-1degC").scalar).toBe(1); @@ -916,13 +916,13 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC"); }); - it("should not add two temperatures", function () { + it("should not add two temperatures", () => { var qty = Qty("2tempC"); - expect(function () { qty.add("1 tempF"); }).toThrow("Cannot add two temperatures"); - expect(function () { qty.add("1 tempC"); }).toThrow("Cannot add two temperatures"); + expect(() => { qty.add("1 tempF"); }).toThrow("Cannot add two temperatures"); + expect(() => { qty.add("1 tempC"); }).toThrow("Cannot add two temperatures"); }); - it("should add temperatures to degrees", function () { + it("should add temperatures to degrees", () => { var qty = Qty("2degC"); var result = qty.add("3tempF"); expect(result.scalar).toBe(33 / 5); @@ -938,7 +938,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("tempC"); }); - it("should subtract degrees from degrees", function () { + it("should subtract degrees from degrees", () => { var qty = Qty("2degC"); expect(qty.sub("1.5degK").scalar).toBe(0.5); expect(qty.sub("-2degC").scalar).toBe(4); @@ -950,7 +950,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC"); }); - it("should subtract degrees from temperatures", function () { + it("should subtract degrees from temperatures", () => { var qty = Qty("2tempC"); expect(qty.sub("1.5degK").scalar).toBe(0.5); expect(qty.sub("-2degC").scalar).toBe(4); @@ -962,7 +962,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("tempC"); }); - it("should subtract temperatures from temperatures", function () { + it("should subtract temperatures from temperatures", () => { var qty = Qty("2tempC"); var result = qty.sub("1.5tempK"); @@ -978,13 +978,13 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC"); }); - it("should not subtract temperatures from degrees", function () { + it("should not subtract temperatures from degrees", () => { var qty = Qty("2degC"); - expect(function () { qty.sub("1 tempF"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); - expect(function () { qty.sub("1 tempC"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); + expect(() => { qty.sub("1 tempF"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); + expect(() => { qty.sub("1 tempC"); }).toThrow("Cannot subtract a temperature from a differential degree unit"); }); - it("should multiply temperature degrees", function () { + it("should multiply temperature degrees", () => { var qty = Qty("2degF"); var result = qty.mul(3); expect(result.scalar).toBe(6); @@ -1006,11 +1006,11 @@ describe("js-quantities", function () { expect(result.units()).toBe("degC*degF"); }); - it("should not multiply temperatures except by scalar", function () { + it("should not multiply temperatures except by scalar", () => { var qty = Qty("2tempF"); - expect(function () { qty.mul("1 tempC"); }).toThrow("Cannot multiply by temperatures"); - expect(function () { qty.mul("1 degC"); }).toThrow("Cannot multiply by temperatures"); - expect(function () { Qty("1 tempC*s"); }).toThrow("Cannot multiply by temperatures"); + expect(() => { qty.mul("1 tempC"); }).toThrow("Cannot multiply by temperatures"); + expect(() => { qty.mul("1 degC"); }).toThrow("Cannot multiply by temperatures"); + expect(() => { Qty("1 tempC*s"); }).toThrow("Cannot multiply by temperatures"); var result = qty.mul(2); expect(result.scalar).toBe(4); @@ -1021,7 +1021,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("tempF"); }); - it("should multiply temperature degrees with unlike quantities", function () { + it("should multiply temperature degrees with unlike quantities", () => { var qty1 = Qty("2.5 degF"); var qty2 = Qty("3 m"); @@ -1036,7 +1036,7 @@ describe("js-quantities", function () { expect(result.units()).toBe("kg"); }); - it("should divide temperature degrees with unlike quantities", function () { + it("should divide temperature degrees with unlike quantities", () => { var qty1 = Qty("7.5degF"); var qty2 = Qty("2.5m^2"); @@ -1045,11 +1045,11 @@ describe("js-quantities", function () { expect(result.units()).toBe("degF/m2"); }); - it("should divide temperature degree quantities", function () { + it("should divide temperature degree quantities", () => { var qty = Qty("2.5 degF"); - expect(function () { qty.div("0 degF"); }).toThrow("Divide by zero"); - expect(function () { qty.div(0); }).toThrow("Divide by zero"); + expect(() => { qty.div("0 degF"); }).toThrow("Divide by zero"); + expect(() => { qty.div(0); }).toThrow("Divide by zero"); expect(Qty("0 degF").div(qty).scalar).toBe(0); expect(Qty("0 degF").div(qty).units()).toBe(""); @@ -1069,15 +1069,15 @@ describe("js-quantities", function () { expect(result.units()).toBe("degF/degC"); }); - it("should not divide with temperatures except by scalar", function () { - expect(function () { Qty("tempF").div("1 tempC"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("tempF").div("1 degC"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("2").div("tempF"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("2 tempF/s"); }).toThrow("Cannot divide with temperatures"); - expect(function () { Qty("2 s/tempF"); }).toThrow("Cannot divide with temperatures"); + it("should not divide with temperatures except by scalar", () => { + expect(() => { Qty("tempF").div("1 tempC"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("tempF").div("1 degC"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("2").div("tempF"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("2 tempF/s"); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("2 s/tempF"); }).toThrow("Cannot divide with temperatures"); // inverse is division: 1/x - expect(function () { Qty("tempF").inverse(); }).toThrow("Cannot divide with temperatures"); + expect(() => { Qty("tempF").inverse(); }).toThrow("Cannot divide with temperatures"); var result = Qty("4 tempF").div(2); expect(result.scalar).toBe(2); @@ -1086,8 +1086,8 @@ describe("js-quantities", function () { }); - describe("errors", function () { - it("should be instance of Qty.Error", function () { + describe("errors", () => { + it("should be instance of Qty.Error", () => { try { Qty("aa"); } catch (e) { @@ -1096,16 +1096,16 @@ describe("js-quantities", function () { }); }); - describe("utility methods", function () { + describe("utility methods", () => { - it("should accept string as parameter for compatibility tests", function () { + it("should accept string as parameter for compatibility tests", () => { var qty = Qty("1 mm"); expect(qty.isCompatible("2 mm")).toBe(true); expect(qty.isCompatible("2 mm^3")).toBe(false); }); - it("should return kind", function () { + it("should return kind", () => { var qty = Qty("1 mm"); expect(qty.kind()).toBe("length"); @@ -1113,7 +1113,7 @@ describe("js-quantities", function () { expect(qty.kind()).toBe("force"); }); - it("should know if a quantity is in base units", function () { + it("should know if a quantity is in base units", () => { var qty = Qty("100 cm"); expect(qty.isBase()).toBe(false); @@ -1121,7 +1121,7 @@ describe("js-quantities", function () { expect(qty.isBase()).toBe(true); }); - it("should return unit part of quantities", function () { + it("should return unit part of quantities", () => { var qty = Qty("1"); expect(qty.units()).toBe(""); qty = Qty("1 /s"); @@ -1140,17 +1140,17 @@ describe("js-quantities", function () { }); - describe("toString", function () { - it("should generate readable human output", function () { + describe("toString", () => { + it("should generate readable human output", () => { var qty = Qty("2m"); expect(qty.toString()).toBe("2 m"); expect(qty.toString("cm")).toBe("200 cm"); expect(qty.toString("km")).toBe("0.002 km"); - expect(function () { qty.toString("A"); }).toThrow("Incompatible units"); + expect(() => { qty.toString("A"); }).toThrow("Incompatible units"); qty = Qty("24.5m/s"); expect(qty.toString()).toBe("24.5 m/s"); - expect(function () { qty.toString("m"); }).toThrow("Incompatible units"); + expect(() => { qty.toString("m"); }).toThrow("Incompatible units"); expect(qty.toString("km/h")).toBe("88.2 km/h"); qty = Qty("254kg/m^2"); @@ -1160,7 +1160,7 @@ describe("js-quantities", function () { expect(qty.toString()).toBe("2"); }); - it("should round readable human output when max decimals is specified", function () { + it("should round readable human output when max decimals is specified", () => { var qty = (Qty("2m")).div(3); expect(qty.toString("cm", 2)).toBe("66.67 cm"); @@ -1171,14 +1171,14 @@ describe("js-quantities", function () { expect(qty.toString("cm", 0)).toBe("282 cm"); }); - it("should round to max decimals", function () { + it("should round to max decimals", () => { var qty = (Qty("2.987654321 m")); expect(qty.toString(3)).toBe("2.988 m"); expect(qty.toString(0)).toBe("3 m"); }); - it("should round according to precision passed as quantity", function () { + it("should round according to precision passed as quantity", () => { var qty = Qty("5.17 ft"); expect(qty.toString(Qty("ft"))).toBe("5 ft"); @@ -1190,31 +1190,31 @@ describe("js-quantities", function () { expect(qty.toString(Qty("0.0001 ft"))).toBe("5.17 ft"); }); - it("should return same output with successive calls", function () { + it("should return same output with successive calls", () => { var qty = Qty("123 cm3"); expect(qty.toString("cm3", 0)).toBe("123 cm3"); expect(qty.toString("cm3", 0)).toBe("123 cm3"); }); - it("should return identical output when called with no parameters or same units", function () { + it("should return identical output when called with no parameters or same units", () => { var qty = Qty("123 cm3"); expect(qty.toString()).toBe(qty.toString("cm3")); }); }); - describe("format", function () { - describe("provided default formatter", function () { - it("should be applied to output", function () { + describe("format", () => { + describe("provided default formatter", () => { + it("should be applied to output", () => { var qty = (Qty("2.987654321 m")); expect(qty.format()).toBe("2.987654321 m"); }); }); - describe("custom formatter", function () { - var roundingFormatter = function (maxDecimals: number) { - return function (scalar: number, units: string) { + describe("custom formatter", () => { + var roundingFormatter = (maxDecimals: number) => { + return (scalar: number, units: string) => { var pow = Math.pow(10, maxDecimals); var rounded = Math.round(scalar * pow) / pow; @@ -1222,14 +1222,14 @@ describe("js-quantities", function () { }; }; - it("should be applied to output", function () { + it("should be applied to output", () => { var qty = (Qty("2.987654321 m")); expect(qty.format(roundingFormatter(3))).toBe("2.988 m"); expect(qty.format(roundingFormatter(0))).toBe("3 m"); }); - it("should be applied after conversion to target units", function () { + it("should be applied after conversion to target units", () => { var qty = (Qty("2m")).div(3); expect(qty.format("cm", roundingFormatter(2))).toBe("66.67 cm"); @@ -1241,20 +1241,20 @@ describe("js-quantities", function () { expect(qty.format("cm", intRoundingFormatter)).toBe("282 cm"); }); - describe("globally set as default formatter", function () { + describe("globally set as default formatter", () => { var previousFormatter: Qty.Formatter; - beforeEach(function () { + beforeEach(() => { previousFormatter = Qty.formatter; Qty.formatter = roundingFormatter(3); }); - afterEach(function () { + afterEach(() => { // Restore previous formatter Qty.formatter = previousFormatter; }); - it("should be applied when no formatter is passed", function () { + it("should be applied when no formatter is passed", () => { var qty = (Qty("2.987654321 m")); expect(qty.format()).toBe("2.988 m"); @@ -1263,8 +1263,8 @@ describe("js-quantities", function () { }); }); - describe("precision rounding", function () { - it("should round according to precision passed as quantity with same units", function () { + describe("precision rounding", () => { + it("should round according to precision passed as quantity with same units", () => { var qty = Qty("5.17 ft"); expect(qty.toPrec(Qty("ft")).toString()).toBe("5 ft"); @@ -1278,7 +1278,7 @@ describe("js-quantities", function () { expect(qty.toPrec(Qty("0.25 ft")).toString()).toBe("5.25 ft"); }); - it("should allow string as precision parameter", function () { + it("should allow string as precision parameter", () => { var qty = Qty("5.17 ft"); expect(qty.toPrec("ft").toString()).toBe("5 ft"); @@ -1286,7 +1286,7 @@ describe("js-quantities", function () { expect(qty.toPrec("0.05 ft").toString()).toBe("5.15 ft"); }); - it("should round according to precision passed as quantity with different prefixes", function () { + it("should round according to precision passed as quantity with different prefixes", () => { var qty = Qty("6.3782 m"); expect(qty.toPrec(Qty("dm")).toString()).toBe("6.4 m"); @@ -1296,7 +1296,7 @@ describe("js-quantities", function () { expect(qty.toPrec(Qty("5 cm")).toString()).toBe("6.4 m"); }); - it("should round according to precision passed as quantity with different compatible units", function () { + it("should round according to precision passed as quantity with different compatible units", () => { var qty = Qty("1.146 MPa"); expect(qty.toPrec(Qty("0.1 bar")).toString()).toBe("1.15 MPa"); expect(qty.toPrec(Qty("0.01 MPa")).toString()).toBe("1.15 MPa"); @@ -1312,48 +1312,48 @@ describe("js-quantities", function () { }); }); - describe("mulSafe", function () { - it("should multiply while trying to avoid numerical errors", function () { + describe("mulSafe", () => { + it("should multiply while trying to avoid numerical errors", () => { expect(Qty.mulSafe(0.1, 0.1)).toBe(0.01); expect(Qty.mulSafe(1e-11, 123.456789)).toBe(1.23456789e-9); expect(Qty.mulSafe(6e-12, 100000)).toBe(6e-7); }); }); - describe("divSafe", function () { - it("should divide while trying to avoid numerical errors", function () { + describe("divSafe", () => { + it("should divide while trying to avoid numerical errors", () => { expect(Qty.divSafe(0.000773, 0.000001)).toBe(773); // TODO uncomment and fix - //expect(Qty.divSafe(24.5, 0.2777777777777778)).toBe(88.2); + // expect(Qty.divSafe(24.5, 0.2777777777777778)).toBe(88.2); }); }); - describe("Qty.parse", function () { - it("should not throw if parsed argument is a string", function () { - expect(function () { Qty.parse("foo"); }).not.toThrow("Argument should be a string"); + describe("Qty.parse", () => { + it("should not throw if parsed argument is a string", () => { + expect(() => { Qty.parse("foo"); }).not.toThrow("Argument should be a string"); }); - it("should return parsed quantity when passing a valid quantity", function () { + it("should return parsed quantity when passing a valid quantity", () => { expect((Qty.parse("2.5 m") instanceof Qty)).toBe(true); }); - it("should return null when passing an invalid quantity", function () { + it("should return null when passing an invalid quantity", () => { expect(Qty.parse("aa")).toBeNull(); }); }); - describe("Qty.swiftConverter", function () { - it("should return a function", function () { + describe("Qty.swiftConverter", () => { + it("should return a function", () => { expect(typeof Qty.swiftConverter("m/h", "ft/s")).toBe("function"); }); - it("should throw when passing incompatible units", function () { - expect(function () { Qty.swiftConverter("m", "s"); }).toThrow("Incompatible units"); + it("should throw when passing incompatible units", () => { + expect(() => { Qty.swiftConverter("m", "s"); }).toThrow("Incompatible units"); }); - describe("converter", function () { - describe("single value", function () { - it("should convert value", function () { + describe("converter", () => { + describe("single value", () => { + it("should convert value", () => { // TODO Same test but with m/h -> ft/s triggers rounding issue // (For the sake of speed, converter does not check and fix rounding issues) var converter = Qty.swiftConverter("m/h", "m/s"); @@ -1361,27 +1361,27 @@ describe("js-quantities", function () { expect(converter(2500)).toEqual(Qty("2500 m/h").to("m/s").scalar); }); - it("should returned value unchanged when units are identical", function () { + it("should returned value unchanged when units are identical", () => { var converter = Qty.swiftConverter("m/h", "m/h"); expect(converter(2500)).toEqual(2500); }); - it("should convert temperatures", function () { + it("should convert temperatures", () => { var converter = Qty.swiftConverter("tempF", "tempC"); expect(converter(32)).toEqual(0); }); - it("should convert degrees", function () { + it("should convert degrees", () => { var converter = Qty.swiftConverter("degC", "degF"); expect(converter(10)).toEqual(18); }); }); - describe("array of values", function () { - it("should be converted", function () { + describe("array of values", () => { + it("should be converted", () => { var converter = Qty.swiftConverter("MPa", "bar"), values = [250, 10, 15], expected = [2500, 100, 150]; @@ -1392,106 +1392,106 @@ describe("js-quantities", function () { }); }); - describe("Qty.getKinds", function () { - it("should return an array of kind names", function () { + describe("Qty.getKinds", () => { + it("should return an array of kind names", () => { expect(Qty.getKinds()).toContain("resistance"); }); - it("should not contain duplicate kind names", function () { + it("should not contain duplicate kind names", () => { var kinds = Qty.getKinds(); var map: { [key: string]: number } = {}; - kinds.forEach(function (kind) { + kinds.forEach(kind => { map[kind] = 1; }); expect(kinds.length).toEqual(Object.keys(map).length); }); }); - describe("Qty.getUnits", function () { - it("should return an array of units of kind", function () { + describe("Qty.getUnits", () => { + it("should return an array of units of kind", () => { expect(Qty.getUnits("currency")).toContain("dollar"); }); - it("should return an array of all units without arg", function () { + it("should return an array of all units without arg", () => { expect(Qty.getUnits()).toContain("sievert"); }); - it("should throw unknown kind", function () { - expect(function () { Qty.getUnits('bogusKind'); }).toThrow("Kind not recognized"); + it("should throw unknown kind", () => { + expect(() => { Qty.getUnits('bogusKind'); }).toThrow("Kind not recognized"); }); }); - describe("Qty.getAliases", function () { - it("should return array of alternative names for unit", function () { + describe("Qty.getAliases", () => { + it("should return array of alternative names for unit", () => { expect(Qty.getAliases("m")).toContain("meter"); expect(Qty.getAliases("meter")).toContain("metre"); expect(Qty.getAliases("N")).toContain("newton"); }); }); - describe("information", function () { - describe("bits and bytes", function () { - it("should have 'information' as kind", function () { + describe("information", () => { + describe("bits and bytes", () => { + it("should have 'information' as kind", () => { expect(Qty("3 b").kind()).toBe("information"); expect(Qty("5 B").kind()).toBe("information"); }); - it("could be pluralized", function () { + it("could be pluralized", () => { expect(Qty("3 bits").eq(Qty("3 b"))).toBe(true); expect(Qty("5 bytes").eq(Qty("5 B"))).toBe(true); }); }); - describe("rate", function () { - it("should accept bps and Bps aliases", function () { + describe("rate", () => { + it("should accept bps and Bps aliases", () => { expect(Qty("3 bps").eq(Qty("3 b/s"))).toBe(true); expect(Qty("5 Bps").eq(Qty("5 B/s"))).toBe(true); }); - it("should be parsed when prefixed", function () { + it("should be parsed when prefixed", () => { expect(Qty("3 kbps").eq(Qty("3 kb/s"))).toBe(true); expect(Qty("5 MBps").eq(Qty("5 MB/s"))).toBe(true); }); - it("should have 'information_rate' as kind", function () { + it("should have 'information_rate' as kind", () => { expect(Qty("3 bps").kind()).toBe("information_rate"); expect(Qty("5 Bps").kind()).toBe("information_rate"); }); }); }); - describe("non regression tests", function () { - describe("Wh (#38)", function () { - it("should be parsed", function () { + describe("non regression tests", () => { + describe("Wh (#38)", () => { + it("should be parsed", () => { expect(Qty("Wh").eq(Qty("3600 J"))).toBe(true); }); - it("should be parsed when prefixed", function () { + it("should be parsed when prefixed", () => { expect(Qty("kWh").eq(Qty("1000 Wh"))).toBe(true); }); }); - describe("Ah (#25)", function () { - it("should be parsed", function () { + describe("Ah (#25)", () => { + it("should be parsed", () => { expect(Qty("Ah").eq(Qty("3600 C"))).toBe(true); }); - it("should be parsed when prefixed", function () { + it("should be parsed when prefixed", () => { expect(Qty("mAh").eq(Qty("3.6 C"))).toBe(true); }); }); - describe("Farad (#67)", function () { - it('should be equal to its definition', function () { + describe("Farad (#67)", () => { + it('should be equal to its definition', () => { expect(Qty("1 F").eq(Qty("1 C").div(Qty("1 V")))).toBe(true); }); - it('should not be defined as base unit', function () { + it('should not be defined as base unit', () => { var qty = Qty("F"); expect(qty.isBase()).toBe(false); expect(qty.toBase().units()).toEqual("s4*A2/m2*kg"); }); - it('should be parsed when prefixed', function () { + it('should be parsed when prefixed', () => { var qty = Qty("100 nF"); expect(qty.eq(Qty("100 F").div(1e9))).toBe(true); diff --git a/js-quantities/tslint.json b/js-quantities/tslint.json index f9e30021f4..377cc837d4 100644 --- a/js-quantities/tslint.json +++ b/js-quantities/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/jsdom/index.d.ts b/jsdom/index.d.ts index a7d8e1d58b..0f272a7c35 100644 --- a/jsdom/index.d.ts +++ b/jsdom/index.d.ts @@ -89,7 +89,7 @@ export interface DocumentWithParentWindow extends Document { * equivalent to what a browser will give if you open up an empty .html file. * @param options see the explanation of the config object above. */ -export declare function jsdom(markup: string, config?: Config): DocumentWithParentWindow; +export declare function jsdom(markup?: string, config?: Config): DocumentWithParentWindow; /** * Before creating any documents, you can modify the defaults for all future documents: diff --git a/jsnlog/index.d.ts b/jsnlog/index.d.ts index 4b525c75af..e252d5cf36 100644 --- a/jsnlog/index.d.ts +++ b/jsnlog/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for JSNLog 2.17.3 +// Type definitions for JSNLog 2.17 // Project: https://github.com/mperdeck/jsnlog.js // Definitions by: Mattijs Perdeck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ // http://jsnlog.com // ------------------------------- -/** +/** * Copyright 2016 Mattijs Perdeck. * * This project is licensed under the MIT license. @@ -33,6 +33,7 @@ declare namespace JL { clientIP?: string; requestId?: string; defaultBeforeSend?: (xhr: XMLHttpRequest) => void; + serialize?: (obj: any) => string; } interface JSNLogFilterOptions { @@ -87,7 +88,7 @@ declare namespace JL { declare function __jsnlog_configure(jsnlog: any): void; - + // Ambient declaration of the JL function itself declare function JL(loggerName?: string): JL.JSNLogLogger; diff --git a/jsnlog/jsnlog-tests.ts b/jsnlog/jsnlog-tests.ts index db2b2a2523..c988234394 100644 --- a/jsnlog/jsnlog-tests.ts +++ b/jsnlog/jsnlog-tests.ts @@ -18,7 +18,8 @@ JL.setOptions({ defaultAjaxUrl: '/jsnlog.logger', clientIP: '0.0.0.0', requestId: 'a reuest id', - defaultBeforeSend: null + defaultBeforeSend: null, + serialize: (obj) => JSON.stringify(obj) }); // ---------------------------------------------------------- @@ -69,7 +70,7 @@ var logger1: JL.JSNLogLogger = JL('mylogger'); var exception = {}; logger1.trace('log message').debug({ x: 1, y: 2}); -logger1.info(function() { return 5; }); +logger1.info(() => 5); logger1.warn('log message'); logger1.error('log message'); logger1.fatal('log message'); diff --git a/jsnlog/tslint.json b/jsnlog/tslint.json new file mode 100644 index 0000000000..1b7fef4ac6 --- /dev/null +++ b/jsnlog/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "max-line-length": false, + "no-empty-interface": false + } +} diff --git a/jsnox/index.d.ts b/jsnox/index.d.ts index f49cef58c4..9587afc8f1 100644 --- a/jsnox/index.d.ts +++ b/jsnox/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/af/jsnox // Definitions by: Steve Baker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/json-stable-stringify/index.d.ts b/json-stable-stringify/index.d.ts index 79402210f3..3339d8f28e 100644 --- a/json-stable-stringify/index.d.ts +++ b/json-stable-stringify/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for json-stable-stringify 1.0.0 +// Type definitions for json-stable-stringify 1.0 // Project: https://github.com/substack/json-stable-stringify // Definitions by: Matt Frantz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,13 +14,9 @@ declare namespace stringify { value: any; } - interface Comparator { - (a: Element, b: Element): number; - } + type Comparator = (a: Element, b: Element) => number; - interface Replacer { - (key: string, value: any): any; - } + type Replacer = (key: string, value: any) => any; interface Options { cmp?: Comparator; diff --git a/json-stable-stringify/json-stable-stringify-tests.ts b/json-stable-stringify/json-stable-stringify-tests.ts index dfd2ced587..761d01d06a 100644 --- a/json-stable-stringify/json-stable-stringify-tests.ts +++ b/json-stable-stringify/json-stable-stringify-tests.ts @@ -1,6 +1,6 @@ import stringify = require('json-stable-stringify'); -var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; +var obj = { c: 8, b: [{z: 6, y: 5, x: 4}, 7], a: 3 }; { console.log(stringify(obj)); diff --git a/json-stable-stringify/tsconfig.json b/json-stable-stringify/tsconfig.json index 65e9568adf..9ce550b0e8 100644 --- a/json-stable-stringify/tsconfig.json +++ b/json-stable-stringify/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/json-stable-stringify/tslint.json b/json-stable-stringify/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/json-stable-stringify/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jsonrpc-serializer/index.d.ts b/jsonrpc-serializer/index.d.ts new file mode 100644 index 0000000000..1f1b58551e --- /dev/null +++ b/jsonrpc-serializer/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for jsonrpc-serializer 0.2 +// Project: https://github.com/soggie/jsonrpc-serializer#readme +// Definitions by: Akim95 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function request(id: string | number, method: string, params?: T): string; +export function notification(method: string, params?: T): string; +export function success(id: string, result: T): string; +export function error(id: string, error: T): string; +export function deserialize(msg: string): T; +export function requestObject(id: string | number, method: string, params?: T): string; +export function notificationObject(method: string, params?: T): string; +export function successObject(id: string, result: T): string; +export function errorObject(id: string, error: T): string; +export function deserializeObject(msg: T): void; + +export const errorHandler: any; + +export namespace err { + class JsonRpcError { + constructor(msg: string); + serialize(): any; + } + class InvalidParamsError {} + class InvalidRequestError {} + class MethodNotFoundError {} + class ParseError {} +} diff --git a/jsonrpc-serializer/jsonrpc-serializer-tests.ts b/jsonrpc-serializer/jsonrpc-serializer-tests.ts new file mode 100644 index 0000000000..83a6cc6f83 --- /dev/null +++ b/jsonrpc-serializer/jsonrpc-serializer-tests.ts @@ -0,0 +1,48 @@ +import * as jrs from 'jsonrpc-serializer'; + +// request tests +jrs.request('id', 'method'); +jrs.request('id', 'method', 'params'); +jrs.request('id', 'method', ['param1', 'param2', 'param3']); +jrs.request('id', 'method', { params: 'params' }); + +// request object tests +jrs.requestObject('id', 'method'); +jrs.requestObject('id', 'method', 'params'); +jrs.requestObject('id', 'method', ['param1', 'param2', 'param3']); +jrs.requestObject('id', 'method', { params: 'params' }); + +// notification tests +jrs.notification('method'); +jrs.notification('method', 'params'); +jrs.notification('method', ['param1', 'param2']); +jrs.notification('method', { param: 'param' }); + +// object notification tests +jrs.notificationObject('method'); +jrs.notificationObject('method', 'params'); +jrs.notificationObject('method', ['param1', 'param2']); +jrs.notificationObject('method', { param: 'param' }); + +// success tests +jrs.success('id', 'result'); +jrs.successObject('id', 'result'); + +// error tests; +jrs.error('id', new jrs.err.JsonRpcError('penta error')); +jrs.error('id', new jrs.err.InvalidParamsError()); +jrs.error('id', new jrs.err.ParseError()); +jrs.error('id', new jrs.err.InvalidRequestError()); +jrs.error('id', new jrs.err.MethodNotFoundError()); +jrs.error('id', new jrs.err.InvalidParamsError()); + +// deserialize tests +const request = { + jsonrpc : '2.0', + id : 'id', + method : 'method', + params : 'params' +}; + +jrs.deserialize(JSON.stringify(request)); +jrs.deserializeObject(request); diff --git a/jsonrpc-serializer/tsconfig.json b/jsonrpc-serializer/tsconfig.json new file mode 100644 index 0000000000..f17f1b210b --- /dev/null +++ b/jsonrpc-serializer/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", + "jsonrpc-serializer-tests.ts" + ] +} \ No newline at end of file diff --git a/jsonrpc-serializer/tslint.json b/jsonrpc-serializer/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jsonrpc-serializer/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jui-core/jui-core-tests.ts b/jui-core/jui-core-tests.ts index 6cf8a82c98..c0677926e6 100644 --- a/jui-core/jui-core-tests.ts +++ b/jui-core/jui-core-tests.ts @@ -1,15 +1,13 @@ -/// - import {jui, UtilColor, UtilBase} from "./index"; -jui.ready(["util.color"], function(color: UtilColor) { +jui.ready(["util.color"], (color: UtilColor) => { console.log(color.rgb("#ff0000")); }); -let _ : UtilBase = jui.include("util.base"); +const _: UtilBase = jui.include("util.base"); -let str: string = "10"; +const str: string = "10"; console.log(_.typeCheck("string", str)); -let i: number = 10; +const i: number = 10; console.log(_.typeCheck("string", i)); diff --git a/jui-grid/jui-grid-tests.ts b/jui-grid/jui-grid-tests.ts index 1d29dd059b..1fb65c4b97 100644 --- a/jui-grid/jui-grid-tests.ts +++ b/jui-grid/jui-grid-tests.ts @@ -4,8 +4,8 @@ import {jui} from 'jui-core'; import {GridTable, GridXTable, GridRow} from "./index"; -jui.ready([ "grid.table" ], function(table: GridTable) { - let table_1: GridTable = table("#table_1", { +jui.ready([ "grid.table" ], (table: GridTable) => { + const table_1: GridTable = table("#table_1", { data: [ { name: "Hong", age: "20", location: "Ilsan" }, { name: "Jung", age: "30", location: "Seoul" }, @@ -21,13 +21,13 @@ jui.ready([ "grid.table" ], function(table: GridTable) { table_1.scroll(100); }); -jui.ready([ "grid.table" ], function(table: GridTable) { - let table_3:GridTable = table("#table_3", { +jui.ready([ "grid.table" ], (table: GridTable) => { + const table_3: GridTable = table("#table_3", { event: { - expand: function(row: any, e: any): void { + expand(row: any, e: any): void { $(row.list[0]).html(""); }, - expandend: function(row: any, e: any): void { + expandend(row: any, e: any): void { $(row.list[0]).html(""); } }, @@ -40,21 +40,21 @@ jui.ready([ "grid.table" ], function(table: GridTable) { { name: "Park", age: "10", location: "Dangjin" } ]); - let table_3_submit: Function = function(index: number) { + const table_3_submit: Function = (index: number) => { var name = $(table_3.root).find(".name").val(), age = $(table_3.root).find(".age").val(), location = $(table_3.root).find(".location").val(); //noinspection TypeScriptValidateTypes - table_3.update(index, { name: name, age: age, location: location }); + table_3.update(index, { name, age, location }); table_3.hideExpand(); - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { var page = 1; - let xtable_2: GridXTable = xtable("#xtable_2", { + const xtable_2: GridXTable = xtable("#xtable_2", { fields: [ "name", "age", "location" ], resize: true, sort: true, @@ -62,28 +62,28 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { bufferCount: 20 }); - let xtable_2_submit: Function = function() { + const xtable_2_submit: Function = () => { var result: any[] = []; - for(var i = 0; i < 1000000; i++) { + for (var i = 0; i < 1000000; i++) { result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); } page = 1; xtable_2.update(result); xtable_2.resize(); - } + }; - let xtable_2_page: Function = function(no: number) { + const xtable_2_page: Function = (no: number) => { page += no; page = (page < 1) ? 1 : page; xtable_2.page(page); - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { - let xtable_4:GridXTable = xtable("#xtable_4", { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { + const xtable_4: GridXTable = xtable("#xtable_4", { fields: [ "name", "age", "location" ], data: [ { name: "Hong", age: "20", location: "Ilsan" }, @@ -96,25 +96,25 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { bufferCount: 20 }); - let xtable_4_submit: Function = function(isMulti: boolean) { - if(isMulti) { - xtable_4.filter(function(data: any) { - if(data.age >= 30 || data.name.indexOf("ng") != -1) { + const xtable_4_submit: Function = (isMulti: boolean) => { + if (isMulti) { + xtable_4.filter((data: any) => { + if (data.age >= 30 || data.name.indexOf("ng") !== -1) { return true; } }); } else { - xtable_4.filter(function(data: any) { - if(data.location.indexOf("eo") != -1) { + xtable_4.filter((data: any) => { + if (data.location.indexOf("eo") !== -1) { return true; } }); } - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { - let xtable_6: GridXTable = xtable("#xtable_6", { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { + const xtable_6: GridXTable = xtable("#xtable_6", { fields: [ "name", "age", "location" ], resize: true, sort: true, @@ -129,19 +129,19 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { } }); - let xtable_6_submit: Function = function() { + const xtable_6_submit: Function = () => { var result: any[] = []; - for(var i = 0; i < 1000000; i++) { + for (var i = 0; i < 1000000; i++) { result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); } xtable_6.update(result); - } + }; }); -jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { - let xtable_8: GridXTable = xtable("#xtable_8", { +jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { + const xtable_8: GridXTable = xtable("#xtable_8", { fields: [ "url", "count" ], resize: true, buffer: "vscroll", @@ -152,8 +152,8 @@ jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { none: $("#tpl_none").html() }, event: { - select: function(row: GridRow, e:any) { - if(row.type == "fold") { + select(row: GridRow, e: any) { + if (row.type === "fold") { xtable_8.open(row.index); } else { xtable_8.fold(row.index); diff --git a/jui-grid/tslint.json b/jui-grid/tslint.json index 377cc837d4..f05741c59b 100644 --- a/jui-grid/tslint.json +++ b/jui-grid/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/jui/jui-tests.ts b/jui/jui-tests.ts index 5bee2fdc2e..8a7a5d03f4 100644 --- a/jui/jui-tests.ts +++ b/jui/jui-tests.ts @@ -1,5 +1,3 @@ -/// - import {jui} from 'jui-core'; import { UIAccordion, UIAutoComplete, UIColorPicker, UICombo, UIDatePicker, UIDropdown, UIModal, UINotify, @@ -19,7 +17,7 @@ jui.ready([ 'ui.progress', 'ui.property', 'ui.select' -], function ( +], ( accordion: UIAccordion, autocomplete: UIAutoComplete, colorpicker: UIColorPicker, @@ -32,32 +30,32 @@ jui.ready([ progress: UIProgress, property: UIProperty, select: UISelect -) { - let a: UIAccordion = accordion("#test", { +) => { + const a: UIAccordion = accordion("#test", { multipanel: false }); console.log(a.activeIndex()); - let autoComplete: UIAutoComplete = autocomplete("#test", { + const autoComplete: UIAutoComplete = autocomplete("#test", { words : [] }); autoComplete.update([]); - let colorPicker: UIColorPicker = colorpicker("#test", { + const colorPicker: UIColorPicker = colorpicker("#test", { color: '#FFFF00' }); console.log(colorPicker.getColor('hex')); - let comboInstance: UICombo = combo("#test", { + const comboInstance: UICombo = combo("#test", { keydown: true - }) + }); console.log(comboInstance.getValue()); - let datePicker: UIDatePicker = datepicker("#test", { + const datePicker: UIDatePicker = datepicker("#test", { type: "daily" }); @@ -67,9 +65,9 @@ jui.ready([ datePicker.select(new Date()); - let dropdownInstance: UIDropdown = dropdown("#test", { + const dropdownInstance: UIDropdown = dropdown("#test", { width: 100 - }) + }); dropdownInstance.update([]); @@ -77,17 +75,17 @@ jui.ready([ dropdownInstance.reload(); - let m : UIModal = modal("#test", {autoHide: true}); + const m: UIModal = modal("#test", {autoHide: true}); m.show(); - let n: UINotify = notify("#test"); + const n: UINotify = notify("#test"); n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'warning' }, 1000); n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'success' }, 1000); n.reset(); - let p: UIPaging = paging("#test", { count :100, pageCount : 5 }); + const p: UIPaging = paging("#test", { count: 100, pageCount : 5 }); p.first(); p.last(); @@ -95,22 +93,22 @@ jui.ready([ p.prev(); p.page(10); - let prog: UIProgress = progress("#test", { striped: true }); + const prog: UIProgress = progress("#test", { striped: true }); console.log(prog.getValue()); prog.setValue(100); - let propertyView: UIProperty = property("#test", { + const propertyView: UIProperty = property("#test", { items : [ { type : 'group', title : 'Sample Category'}, { type : 'text', title : 'Category Name', key: 'sample-category-name', value : 'test'} ] - }) + }); console.log(propertyView.getValue()); - let selectInstance: UISelect = select("#test", { + const selectInstance: UISelect = select("#test", { items : [ { type : 'item', value : '0', text : 'first', html : '
test
', selected : true }, { type : 'divider' } diff --git a/jump.js/jump.js-tests.ts b/jump.js/jump.js-tests.ts index 4ae48074b2..bce5d68f21 100644 --- a/jump.js/jump.js-tests.ts +++ b/jump.js/jump.js-tests.ts @@ -1,6 +1,6 @@ import jump = require('jump.js'); -const node = document.querySelector('.target'); +const node = document.querySelector('.target')!; jump(node); jump('.target'); jump('.target', { @@ -12,5 +12,5 @@ jump('.target', { }); jump(100); jump(-100, { - callback: () => { console.log('Done!') } + callback: () => { console.log('Done!'); } }); diff --git a/jump.js/tsconfig.json b/jump.js/tsconfig.json index 0c6ab6d7c8..eb922b4eeb 100644 --- a/jump.js/tsconfig.json +++ b/jump.js/tsconfig.json @@ -1,7 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +20,4 @@ "index.d.ts", "jump.js-tests.ts" ] -} +} \ No newline at end of file diff --git a/kafka-node/index.d.ts b/kafka-node/index.d.ts index b3a67c4b9a..018b1a6f9e 100644 --- a/kafka-node/index.d.ts +++ b/kafka-node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for kafka-node 0.2.22 +// Type definitions for kafka-node 1.3.3 // Project: https://github.com/SOHU-Co/kafka-node/ // Definitions by: Daniel Imrie-Situnayake // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -13,24 +13,24 @@ export declare class Client { export declare class Producer { constructor(client: Client); - on(eventName: string, cb: () => any): Producer; - on(eventName: string, cb: (error: any) => any): Producer; + on(eventName: string, cb: () => any): void; + on(eventName: string, cb: (error: any) => any): void; send(payloads: Array, cb: (error: any, data: any) => any): void; createTopics(topics: Array, async: boolean, cb?: (error: any, data: any) => any): void; } export declare class HighLevelProducer { - constructor(client: Client); - on(eventName: string, cb: () => any): HighLevelProducer; - on(eventName: string, cb: (error: any) => any): HighLevelProducer; + constructor(client: Client, options?: any); + on(eventName: string, cb: () => any): void; + on(eventName: string, cb: (error: any) => any): void; send(payloads: Array, cb: (error: any, data: any) => any): void; createTopics(topics: Array, async: boolean, cb?: (error: any, data: any) => any): void; } export declare class Consumer { - constructor(client: Client, fetchRequests: Array, options: ConsumerOptions); - on(eventName: string, cb: (message: string) => any): Consumer; - on(eventName: string, cb: (error: any) => any): Consumer; + constructor(client: Client, fetchRequests: Array, options: ConsumerOptions); + on(eventName: string, cb: (message: string) => any): void; + on(eventName: string, cb: (error: any) => any): void; addTopics(topics: Array, cb: (error: any, added: boolean) => any): void; addTopics(topics: Array, cb: (error: any, added: boolean) => any, fromOffset: boolean): void; removeTopics(topics: Array, cb: (error: any, removed: boolean) => any): void; @@ -45,8 +45,8 @@ export declare class Consumer { export declare class HighLevelConsumer { constructor(client: Client, payloads: Array, options: ConsumerOptions); - on(eventName: string, cb: (message: string) => any): HighLevelConsumer; - on(eventName: string, cb: (error: any) => any): HighLevelConsumer; + on(eventName: string, cb: (message: string) => any): void; + on(eventName: string, cb: (error: any) => any): void; addTopics(topics: Array, cb: (error: any, added: boolean) => any): void; addTopics(topics: Array, cb: (error: any, added: boolean) => any, fromOffset: boolean): void; removeTopics(topics: Array, cb: (error: any, removed: boolean) => any): void; @@ -59,14 +59,22 @@ export declare class HighLevelConsumer { close(force: boolean, cb: () => any): void; } +export declare class ConsumerGroup { + constructor(options: ConsumerGroupOptions, topics: string[]); + on(eventName: string, cb: (message: string) => any): void; + on(eventName: string, cb: (error: any) => any): void; + close(force: boolean, cb: (error: any) => any): void; +} + export declare class Offset { constructor(client: Client); - on(eventName: string, cb: () => any): Offset; + on(eventName: string, cb: () => any): void; fetch(payloads: Array, cb: (error: any, data: any) => any): void; commit(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; fetchCommits(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; fetchLatestOffsets(topics: Array, cb: (error: any, data: any) => any): void; - on(eventName: string, cb: (error: any) => any): Offset; + fetchEarliestOffsets(topics: Array, cb: (error: any, data: any) => any): void; + on(eventName: string, cb: (error: any) => any): void; } export declare class KeyedMessage { @@ -74,6 +82,11 @@ export declare class KeyedMessage { } // # Interfaces +export interface AckBatchOptions { + noAckBatchSize: number | null, + noAckBatchAge: number | null +} + export interface ZKOptions { sessionTimeout?: number; spinDelay?: number; @@ -90,6 +103,7 @@ export interface ProduceRequest { export interface ConsumerOptions { groupId?: string; + id?: string; autoCommit?: boolean; autoCommitIntervalMs?: number; fetchMaxWaitMs?: number; @@ -99,6 +113,27 @@ export interface ConsumerOptions { encoding?: string; } +export interface CustomPartitionAssignmentProtocol { + name: string; + version: number; + userData: {}; + assign: (topicPattern: any, groupMembers: any, callback: (error: any, result: any) => void) => void; +} + +export interface ConsumerGroupOptions { + host: string; + zk?: ZKOptions; + batch?: AckBatchOptions; + ssl?: boolean; + id: string; + groupId: string; + sessionTimeout: number; + protocol: Array<"roundrobin" | "range" | CustomPartitionAssignmentProtocol>; + fromOffset: "earliest" | "latest" | "none"; + migrateHLC: false; + migrateRolling: true; +} + export interface Topic { topic: string; offset?: number; @@ -123,10 +158,5 @@ export interface OffsetCommitRequest { export interface OffsetFetchRequest { topic: string; partition?: number; -} - -export interface FetchRequest { - topic: string; offset?: number; } - diff --git a/kafka-node/kafka-node-tests.ts b/kafka-node/kafka-node-tests.ts index a5b9e9ca3e..557c40de8c 100644 --- a/kafka-node/kafka-node-tests.ts +++ b/kafka-node/kafka-node-tests.ts @@ -1,4 +1,3 @@ - import kafka = require('kafka-node'); var basicClient = new kafka.Client('localhost:2181/', 'sendMessage'); @@ -138,6 +137,24 @@ hlConsumer.resumeTopics([ hlConsumer.close(true, function () {}); +var ackBatchOptions = {'noAckBatchSize': 1024, 'noAckBatchAge': 10}; +var cgOptions: kafka.ConsumerGroupOptions = { + host: 'localhost:2181/', + batch: ackBatchOptions, + groupId: 'groupID', + id: 'consumerID', + sessionTimeout: 15000, + protocol: ["roundrobin"], + fromOffset: "latest", + migrateHLC: false, + migrateRolling: true +}; + +var consumerGroup = new kafka.ConsumerGroup( cgOptions, ['topic1']); +consumerGroup.on('error', (err) => {}); +consumerGroup.on('message', (msg) => {}); +consumerGroup.close(true, () => {}); + var offset = new kafka.Offset(basicClient); offset.on('ready', function(){}); @@ -154,3 +171,6 @@ offset.commit('groupId', [ offset.fetchCommits('groupId', [ { topic: 't', partition: 0 } ], function (err, data) {}); + +offset.fetchLatestOffsets(['t'], (err, offsets) => {}) +offset.fetchEarliestOffsets(['t'], (err, offsets) => {}) diff --git a/karma-jasmine/index.d.ts b/karma-jasmine/index.d.ts index a5f0a22f5b..46b7978251 100644 --- a/karma-jasmine/index.d.ts +++ b/karma-jasmine/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/karma-runner/karma-jasmine // Definitions by: Michel Salib // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/kendo-ui/index.d.ts b/kendo-ui/index.d.ts index 5d6e4ec0a8..ecdbffae66 100644 --- a/kendo-ui/index.d.ts +++ b/kendo-ui/index.d.ts @@ -18307,7 +18307,7 @@ declare namespace kendo.ooxml { cells?: WorkbookSheetRowCell[]; index?: number; height?: number; - type?: "header" | "footer" | "groupHeader" | "groupFooter" | "data"; + type?: "header" | "footer" | "group-header" | "group-footer" | "data"; } interface WorkbookSheet { diff --git a/keycloak-js/index.d.ts b/keycloak-js/index.d.ts index 2cd417da6b..540084d6fd 100644 --- a/keycloak-js/index.d.ts +++ b/keycloak-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for keycloak-js 2.4 +// Type definitions for keycloak-js 2.5 // Project: https://github.com/keycloak/keycloak // Definitions by: Brett Epps // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/keycloak-js/keycloak-authz.d.ts b/keycloak-js/keycloak-authz.d.ts new file mode 100644 index 0000000000..4db057ad97 --- /dev/null +++ b/keycloak-js/keycloak-authz.d.ts @@ -0,0 +1,39 @@ +import * as Keycloak from 'keycloak-js'; + +export as namespace KeycloakAuthorization; + +export = KeycloakAuthorization; + +/** + * Creates a new Keycloak client instance. + * @param config Path to a JSON config file or a plain config object. + */ +declare function KeycloakAuthorization(keycloak: Keycloak.KeycloakInstance): KeycloakAuthorization.KeycloakAuthorizationInstance; + +declare namespace KeycloakAuthorization { + export interface KeycloakAuthorizationPromise { + then(onGrant: (rpt: string) => void, onDeny: () => void, onError: () => void): void; + } + + export interface KeycloakAuthorizationInstance { + rpt: any; + config: { rpt_endpoint: string }; + + init(): void; + + /** + * This method enables client applications to better integrate with resource servers protected by a Keycloak + * policy enforcer. + * + * In this case, the resource server will respond with a 401 status code and a WWW-Authenticate header holding the + * necessary information to ask a Keycloak server for authorization data using both UMA and Entitlement protocol, + * depending on how the policy enforcer at the resource server was configured. + */ + authorize(wwwAuthenticateHeader: string): KeycloakAuthorizationPromise; + + /** + * Obtains all entitlements from a Keycloak server based on a given resourceServerId. + */ + entitlement(resourceServerId: string, entitlementRequest: {}): KeycloakAuthorizationPromise; + } +} diff --git a/keycloak-js/keycloak-js-tests.ts b/keycloak-js/keycloak-js-tests.ts index f0957d2114..f0c78392b7 100644 --- a/keycloak-js/keycloak-js-tests.ts +++ b/keycloak-js/keycloak-js-tests.ts @@ -11,4 +11,8 @@ import { KeycloakResponseType } from 'keycloak-js'; -let keycloak = Keycloak(); +import * as KeycloakAuthorization from 'keycloak-js/keycloak-authz'; +import { KeycloakAuthorizationPromise } from 'keycloak-js/keycloak-authz'; + +const keycloak = Keycloak(); +const keycloakAuthz = KeycloakAuthorization(keycloak); diff --git a/keycloak-js/tsconfig.json b/keycloak-js/tsconfig.json index 02d8f5053a..7ac994a5dc 100644 --- a/keycloak-js/tsconfig.json +++ b/keycloak-js/tsconfig.json @@ -17,6 +17,7 @@ }, "files": [ "index.d.ts", + "keycloak-authz.d.ts", "keycloak-js-tests.ts" ] -} \ No newline at end of file +} diff --git a/keygrip/keygrip-tests.ts b/keygrip/keygrip-tests.ts index afa66e04b1..d8447867b5 100644 --- a/keygrip/keygrip-tests.ts +++ b/keygrip/keygrip-tests.ts @@ -1,4 +1,4 @@ import * as Keygrip from 'keygrip'; -let keys = Keygrip(['123']); -let hash = keys.sign('abc'); +const keys = Keygrip(['123']); +const hash = keys.sign('abc'); diff --git a/knex/index.d.ts b/knex/index.d.ts index 55ef48a05e..3e7dc595f4 100644 --- a/knex/index.d.ts +++ b/knex/index.d.ts @@ -2,11 +2,13 @@ // Project: https://github.com/tgriesser/knex // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// -import * as events from "events"; +import events = require("events"); +import Promise = require("bluebird"); type Callback = Function; type Client = Function; @@ -382,6 +384,7 @@ declare namespace Knex { dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; dropUnique(columnNames: string[], indexName?: string): TableBuilder; dropPrimary(constraintName?: string): TableBuilder; + dropIndex(columnNames: string[], indexName?: string): TableBuilder; } interface CreateTableBuilder extends TableBuilder { diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index 8fd9cc971c..420aafd724 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -1,6 +1,7 @@ "use strict"; -import * as Knex from 'knex'; -import * as _ from 'lodash'; +import Knex = require('knex'); +import Promise = require('bluebird'); +import _ = require('lodash'); // Initializing the Library var knex = Knex({ diff --git a/koa-basic-auth/tslint.json b/koa-basic-auth/tslint.json index ec365f164b..377cc837d4 100644 --- a/koa-basic-auth/tslint.json +++ b/koa-basic-auth/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/koa-bodyparser/index.d.ts b/koa-bodyparser/index.d.ts index d3849cf9f9..932a53f7af 100644 --- a/koa-bodyparser/index.d.ts +++ b/koa-bodyparser/index.d.ts @@ -59,6 +59,7 @@ declare function bodyParser(opts?: { extendTypes?: { json?: string[]; form?: string[]; + text?: string[]; } /** diff --git a/koa-hbs/index.d.ts b/koa-hbs/index.d.ts index 8adfeaf20f..f38d2e9fdd 100644 --- a/koa-hbs/index.d.ts +++ b/koa-hbs/index.d.ts @@ -1,22 +1,21 @@ -// Type definitions for koa-favicon v2.x +// Type definitions for koa-hbs v1.x // Project: https://github.com/gilt/koa-hbs -// Definitions by: Jacob Malone +// Definitions by: Jacob Malone , Mudkip // Definitions: https://github.com/jcbmln/DefinitelyTyped /* =================== USAGE =================== - import * as Hbs from "koa-hbs"; import * as Koa from "koa"; +....import hbs = require("koa-hbs"); - var hbs = new Hbs(); var app = new Koa(); app.use(hbs.middleware({ viewPath: __dirname + '/views' })); - app.use(function *() { - yield this.render('main', { + app.use(async (ctx, next) => { + await ctx.render('main', { title: 'koa-hbs' }); }); @@ -25,31 +24,33 @@ /// -declare module "koa-hbs" { +import * as Koa from "koa"; - import * as Koa from "koa"; - - namespace Hbs { - export interface Middleware { - viewPath: Array | string, - handlebars?: Function, - templateOptions?: {}, - extname?: string, - partialsPath?: Array | string, - defaultLayout?: string, - layoutsPath?: string, - contentHelperName?: string, - blockHelperName?: string, - disableCache?: boolean - } +declare namespace Hbs { + export interface Middleware { + viewPath: Array | string, + handlebars?: Function, + templateOptions?: {}, + extname?: string, + partialsPath?: Array | string, + defaultLayout?: string, + layoutsPath?: string, + contentHelperName?: string, + blockHelperName?: string, + disableCache?: boolean } - - class Hbs { - constructor(); - - middleware(opts: Hbs.Middleware): any; - } - - namespace Hbs {} - export = Hbs; } + +declare class Hbs { + constructor(); + middleware(opts: Hbs.Middleware): any; +} + +declare const hbs: Hbs; +export = hbs; + +declare module "koa" { + export interface Context { + render(tpl: string, locals?: {[key: string]: any}): Promise; + } +} \ No newline at end of file diff --git a/koa-hbs/koa-hbs-tests.ts b/koa-hbs/koa-hbs-tests.ts index 647eee7f22..3c86a51cad 100644 --- a/koa-hbs/koa-hbs-tests.ts +++ b/koa-hbs/koa-hbs-tests.ts @@ -1,16 +1,15 @@ -import * as Hbs from 'koa-hbs'; import * as Koa from 'koa'; +import hbs = require("koa-hbs"); import * as Path from 'path'; const app = new Koa(); -const hbs = new Hbs(); app.use(hbs.middleware({ viewPath: Path.join(__dirname, './views') })); -app.use(function *(next: any) { - yield this.render('index', { +app.use(async (ctx, next) => { + await ctx.render('index', { title: 'Hello World!' }); }); diff --git a/koa-json-error/index.d.ts b/koa-json-error/index.d.ts index 9f02cce994..dfe23c26b0 100644 --- a/koa-json-error/index.d.ts +++ b/koa-json-error/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for koa-json-error v3.x +// Type definitions for koa-json-error 3.1 // Project: https://github.com/koajs/json-error // Definitions by: Mudkip // Definitions: https://github.com/mudkipme/DefinitelyTyped +// TypeScript Version: 2.1 import * as Koa from "koa"; @@ -9,23 +10,23 @@ interface JSONErrorOptions { /** * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. */ - preFormat?: { (err: Error): any }; + preFormat?: (err: Error) => any; /** * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. */ - format?: { (err: Error, obj: any): any }; + format?: (err: Error, obj: any) => any; /** * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. */ - postFormat?: { (err: Error, obj: any): any }; + postFormat?: (err: Error, obj: any) => any; } /** * Error handler for pure Koa 2.0.0+ JSON apps */ -declare function jsonError(options?: JSONErrorOptions) : Koa.Middleware; +declare function jsonError(options?: JSONErrorOptions): Koa.Middleware; declare namespace jsonError {} export = jsonError; diff --git a/koa-json-error/koa-json-error-tests.ts b/koa-json-error/koa-json-error-tests.ts index 07ac0fd129..77a13a1f64 100644 --- a/koa-json-error/koa-json-error-tests.ts +++ b/koa-json-error/koa-json-error-tests.ts @@ -1,9 +1,8 @@ import * as Koa from "koa"; import * as error from "koa-json-error"; -import { assign } from "lodash"; const app = new Koa(); app.use(error({ - preFormat: err => assign({}, err) + preFormat: err => Object.assign({}, err) })); \ No newline at end of file diff --git a/koa-json-error/tslint.json b/koa-json-error/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/koa-json-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/koa-jwt/tslint.json b/koa-jwt/tslint.json index f9e30021f4..377cc837d4 100644 --- a/koa-jwt/tslint.json +++ b/koa-jwt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/koa-passport/index.d.ts b/koa-passport/index.d.ts index 2bdf4bcfac..e3a318004a 100644 --- a/koa-passport/index.d.ts +++ b/koa-passport/index.d.ts @@ -13,7 +13,7 @@ import * as Koa from "koa"; declare module "koa" { - interface Request { + interface Context { authInfo?: any; user?: any; diff --git a/koa-session-minimal/index.d.ts b/koa-session-minimal/index.d.ts index 3fe9da3a52..02d3a68004 100644 --- a/koa-session-minimal/index.d.ts +++ b/koa-session-minimal/index.d.ts @@ -17,7 +17,7 @@ import * as Koa from "koa"; import * as cookies from "cookies"; declare module "koa" { - interface Request { + interface Context { session: any; sessionHandler: { regenerateId: () => void }; } diff --git a/koa/index.d.ts b/koa/index.d.ts index 09b2a64426..99e2c04498 100644 --- a/koa/index.d.ts +++ b/koa/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Koa 2.x // Project: http://koajs.com -// Definitions by: DavidCai1993 +// Definitions by: DavidCai1993 , jKey Lu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* =================== USAGE =================== @@ -14,172 +14,645 @@ =============================================== */ /// -import { EventEmitter } from "events"; -import * as cookies from "cookies"; -import * as http from "http"; -import * as net from "net"; +import { EventEmitter } from 'events'; +import { IncomingMessage, ServerResponse, Server } from 'http'; +import { Socket, ListenOptions } from 'net'; +import * as compose from 'koa-compose'; +import * as Keygrip from 'keygrip'; +import * as httpAssert from 'http-assert'; +import * as Cookies from 'cookies'; +import * as accepts from 'accepts'; + +declare interface ContextDelegatedRequest { + /** + * Return request header. + */ + header: any; + /** + * Return request header, alias as request.header + */ + headers: any; + + /** + * Get/Set request URL. + */ + url: string; + + /** + * Get origin of URL. + */ + origin: string; + + /** + * Get full request URL. + */ + href: string; + + /** + * Get/Set request method. + */ + method: string; + + /** + * Get request pathname. + * Set pathname, retaining the query-string when present. + */ + path: string; + + /** + * Get parsed query-string. + * Set query-string as an object. + */ + query: any; + + /** + * Get/Set query string. + */ + querystring: string; + + /** + * Get the search string. Same as the querystring + * except it includes the leading ?. + * + * Set the search string. Same as + * response.querystring= but included for ubiquity. + */ + search: string; -export = Koa; + /** + * Parse the "Host" header field host + * and support X-Forwarded-Host when a + * proxy is enabled. + */ + host: string; -declare namespace Koa { - export interface Context extends Request, Response { - app: Koa; - req: http.IncomingMessage; - res: http.ServerResponse; - request: Request; - response: Response; + /** + * Parse the "Host" header field hostname + * and support X-Forwarded-Host when a + * proxy is enabled. + */ + hostname: string; - cookies: cookies.ICookies; - originalUrl: string; - state: any; + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; - name?: string; - respond?: boolean; + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; - assert(test: any, ...args: any[]): void; - onerror(err?: any): void; - throw(...args: any[]): void; + /** + * Check if the request is idempotent. + */ + idempotent: boolean; - toJSON(): any; - inspect(): any; + /** + * Return the request socket. + */ + socket: Socket; - [key: string]: any; - } + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the proxy setting + * is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; - export interface Request { - app: Koa; - req: http.IncomingMessage; - res: http.ServerResponse; - ctx: Context; - response: Response; + /** + * Short-hand for: + * + * this.protocol == 'https' + */ + secure: boolean; - fresh: boolean; - header: any; - headers: any; - host: string; - hostname: string; - href: string; - idempotent: boolean; - ip: string; - ips: string[]; - method: string; - origin: string; - originalUrl: string; - path: string; - protocol: string; - query: any; - querystring: string; - search: string; - secure: boolean; - socket: net.Socket; - stale: boolean; - subdomains: string[]; - type: string; - url: string; + /** + * When `app.proxy` is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; - charset?: string; - length?: number; + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain + * of the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting `app.subdomainOffset`. + * + * For example, if the domain is "tobi.ferrets.example.com": + * If `app.subdomainOffset` is not set, this.subdomains is + * `["ferrets", "tobi"]`. + * If `app.subdomainOffset` is 3, this.subdomains is `["tobi"]`. + */ + subdomains: string[]; - accepts(): string[]; - accepts(arg: string): void | string; - accepts(arg: string[]): void | string; - accepts(...args: string[]): void | string; - acceptsCharsets(): string[]; - acceptsCharsets(arg: string): void | string; - acceptsCharsets(arg: string[]): void | string; - acceptsCharsets(...args: string[]): void | string; - acceptsEncodings(): string[]; - acceptsEncodings(arg: string): void | string; - acceptsEncodings(arg: string[]): void | string; - acceptsEncodings(...args: string[]): void | string; - acceptsLanguages(): string[]; - acceptsLanguages(arg: string): void | string; - acceptsLanguages(arg: string[]): void | string; - acceptsLanguages(...args: string[]): void | string; - get(field: string): string; - is(): string[]; - is(arg: string): void | string; - is(arg: string[]): void | string; - is(...args: string[]): void | string; + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.accepts('html'); + * // => "html" + * this.accepts('text/html'); + * // => "text/html" + * this.accepts('json', 'text'); + * // => "json" + * this.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.accepts('image/png'); + * this.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.accepts(['html', 'json']); + * this.accepts('html', 'json'); + * // => "json" + */ + accepts(): string[] | boolean; + accepts(...types: string[]): string | boolean; + accepts(types: string[]): string | boolean; - toJSON(): any; - inspect(): any; - } + /** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + */ + acceptsEncodings(): string[] | boolean; + acceptsEncodings(...encodings: string[]): string | boolean; + acceptsEncodings(encodings: string[]): string | boolean; - export interface Response { - app: Koa; - req: http.IncomingMessage; - res: http.ServerResponse; - ctx: Context; - request: Request; + /** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + */ + acceptsCharsets(): string[] | boolean; + acceptsCharsets(...charsets: string[]): string | boolean; + acceptsCharsets(charsets: string[]): string | boolean; - body: any; - etag: string; - header: any; - headers: any; - headerSent: boolean; - lastModified: Date; - message: string; - socket: net.Socket; - status: number; - type: string; - writable: boolean; + /** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + */ + acceptsLanguages(): string[] | boolean; + acceptsLanguages(...langs: string[]): string | boolean; + acceptsLanguages(langs: string[]): string | boolean; - charset?: string; - length?: number; + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + */ + // is(): string | boolean; + is(...types: string[]): string | boolean; + is(types: string[]): string | boolean; - append(field: string, val: string | string[]): void; - attachment(filename?: string): void; - get(field: string): string; - is(): string[]; - is(arg: string): void | string; - is(arg: string[]): void | string; - is(...args: string[]): void | string; - redirect(url: string, alt?: string): void; - remove(field: string): void; - set(field: string, val: string | string[]): void; - set(field: any): void; - vary(field: string): void; - - toJSON(): any; - inspect(): any; - } - - export type Middleware = (ctx: Koa.Context, next: () => Promise) => any; + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * this.get('Content-Type'); + * // => "text/plain" + * + * this.get('content-type'); + * // => "text/plain" + * + * this.get('Something'); + * // => undefined + */ + get(field: string): string; } -declare class Koa extends EventEmitter { - subdomainOffset: number; - server: http.Server; - env: string; - context: Koa.Context; - keys: string[]; +declare interface BaseRequest extends ContextDelegatedRequest { + /** + * Get the charset when present or undefined. + */ + charset: string; + + /** + * Return parsed Content-Length when present. + */ + length: number; + + /** + * Return the request mime type void of + * parameters such as "charset". + */ + type: string; + + /** + * Inspect implementation. + */ + inspect(): any; + + /** + * Return JSON representation. + */ + toJSON(): any; +} + +declare interface ContextDelegatedResponse { + /** + * Get/Set response status code. + */ + status: number; + + /** + * Get response status message + */ + message: string; + + /** + * Get/Set response body. + */ + body: any; + + /** + * Return parsed response Content-Length when present. + * Set Content-Length field to `n`. + */ + length: number; + + /** + * Check if a header has been written to the socket. + */ + headerSent: boolean; + + /** + * Vary on `field`. + */ + vary(field: string): void; + + /** + * Perform a 302 redirect to `url`. + * + * The string "back" is special-cased + * to provide Referrer support, when Referrer + * is not present `alt` or "/" is used. + * + * Examples: + * + * this.redirect('back'); + * this.redirect('back', '/index.html'); + * this.redirect('/login'); + * this.redirect('http://google.com'); + */ + redirect(url: string, alt?: string): void; + + /** + * Set Content-Disposition header to "attachment" with optional `filename`. + */ + attachment(filename: string): void; + + /** + * Return the response mime type void of + * parameters such as "charset". + * + * Set Content-Type response header with `type` through `mime.lookup()` + * when it does not contain a charset. + * + * Examples: + * + * this.type = '.html'; + * this.type = 'html'; + * this.type = 'json'; + * this.type = 'application/json'; + * this.type = 'png'; + */ + type: string; + + /** + * Get the Last-Modified date in Date form, if it exists. + * Set the Last-Modified date using a string or a Date. + * + * this.response.lastModified = new Date(); + * this.response.lastModified = '2013-09-13'; + */ + lastModified: Date; + + /** + * Get/Set the ETag of a response. + * This will normalize the quotes if necessary. + * + * this.response.etag = 'md5hashsum'; + * this.response.etag = '"md5hashsum"'; + * this.response.etag = 'W/"123456789"'; + * + * @param {String} etag + * @api public + */ + etag: string; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * this.set('Foo', ['bar', 'baz']); + * this.set('Accept', 'application/json'); + * this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + */ + set(field: { [key: string]: string; }): void; + set(field: string, val: string | string[]): void; + + /** + * Append additional header `field` with value `val`. + * + * Examples: + * + * ``` + * this.append('Link', ['', '']); + * this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * this.append('Warning', '199 Miscellaneous warning'); + * ``` + */ + append(field: string, val: string | string[]): void; + + /** + * Remove header `field`. + */ + remove(field: string): void; + + /** + * Checks if the request is writable. + * Tests for the existence of the socket + * as node sometimes does not set it. + */ + writable: boolean; + + /** + * Flush any set headers, and begin the body + */ + flushHeaders(): void; +} + +declare interface BaseResponse extends ContextDelegatedResponse { + /** + * Return the request socket. + * + * @return {Connection} + * @api public + */ + socket: Socket; + + /** + * Return response header. + */ + header: any; + + /** + * Return response header, alias as response.header + */ + headers: any; + + /** + * Check whether the response is one of the listed types. + * Pretty much the same as `this.request.is()`. + * + * @param {String|Array} types... + * @return {String|false} + * @api public + */ + // is(): string; + is(...types: string[]): string; + is(types: string[]): string; + + /** + * Return response header. + * + * Examples: + * + * this.get('Content-Type'); + * // => "text/plain" + * + * this.get('content-type'); + * // => "text/plain" + */ + get(field: string): string; + + /** + * Inspect implementation. + */ + inspect(): any; + + /** + * Return JSON representation. + */ + toJSON(): any; +} + + +declare interface BaseContext extends ContextDelegatedRequest, ContextDelegatedResponse { + /** + * util.inspect() implementation, which + * just returns the JSON output. + */ + inspect(): any; + + /** + * Return JSON representation. + * + * Here we explicitly invoke .toJSON() on each + * object, as iteration will otherwise fail due + * to the getters and cause utilities such as + * clone() to fail. + */ + toJSON(): any; + + /** + * Similar to .throw(), adds assertion. + * + * this.assert(this.user, 401, 'Please login!'); + * + * See: https://github.com/jshttp/http-assert + */ + assert: typeof httpAssert; + + /** + * Throw an error with `msg` and optional `status` + * defaulting to 500. Note that these are user-level + * errors, and the message may be exposed to the client. + * + * this.throw(403) + * this.throw('name required', 400) + * this.throw(400, 'name required') + * this.throw('something exploded') + * this.throw(new Error('invalid'), 400); + * this.throw(400, new Error('invalid')); + * + * See: https://github.com/jshttp/http-errors + */ + throw(message: string, code?: number, properties?: {}): never; + throw(status: number): never; + throw(...properties: Array): never; + + /** + * Default error handling. + */ + onerror(err: Error): void; +} + +declare class Application extends EventEmitter { proxy: boolean; - request: Koa.Request; - response: Koa.Response; + middleware: Application.Middleware[]; + subdomainOffset: number; + env: string; + context: BaseContext; + request: BaseRequest; + response: BaseResponse; silent: boolean; + keys: Keygrip | string[]; constructor(); - // From node.d.ts - listen(): http.Server; - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): http.Server; - listen(port: number, hostname?: string, listeningListener?: Function): http.Server; - listen(port: number, backlog?: number, listeningListener?: Function): http.Server; - listen(port: number, listeningListener?: Function): http.Server; - listen(path: string, backlog?: number, listeningListener?: Function): http.Server; - listen(path: string, listeningListener?: Function): http.Server; - listen(handle: any, backlog?: number, listeningListener?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - listen(options: net.ListenOptions, listeningListener?: Function): http.Server; + /** + * Shorthand for: + * + * http.createServer(app.callback()).listen(...) + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): Server; + listen(port: number, hostname?: string, listeningListener?: () => void): Server; + /* tslint:disable:unified-signatures */ + listen(port: number, backlog?: number, listeningListener?: () => void): Server; + listen(port: number, listeningListener?: () => void): Server; + listen(path: string, backlog?: number, listeningListener?: () => void): Server; + listen(path: string, listeningListener?: () => void): Server; + listen(options: ListenOptions, listeningListener?: () => void): Server; + listen(handle: any, backlog?: number, listeningListener?: () => void): Server; + listen(handle: any, listeningListener?: () => void): Server; + /* tslint:enable:unified-signatures*/ - callback(): (req: http.IncomingMessage, res: http.ServerResponse) => void; - onerror(err: any): void; - use(middleware: Koa.Middleware): Koa; - - toJSON(): any; + /** + * Return JSON representation. + * We only bother showing settings. + */ inspect(): any; - onerror(err: any): void; + + /** + * Return JSON representation. + * We only bother showing settings. + */ + toJSON(): any; + + /** + * Use the given middleware `fn`. + * + * Old-style middleware will be converted. + */ + use(middleware: Application.Middleware): this; + + /** + * Return a request handler callback + * for node's native http server. + */ + callback(): (req: IncomingMessage, res: ServerResponse) => void; + + /** + * Initialize a new context. + * + * @api private + */ + createContext(req: IncomingMessage, res: ServerResponse): Application.Context; + + /** + * Default error handler. + * + * @api private + */ + onerror(err: Error): void; } +declare namespace Application { + type Middleware = compose.Middleware; + + interface Request extends BaseRequest { + app: Application; + req: IncomingMessage; + res: ServerResponse; + ctx: Context; + response: Response; + originalUrl: string; + ip: string; + accept: accepts.Accepts; + } + + interface Response extends BaseResponse { + app: Application; + req: IncomingMessage; + res: ServerResponse; + ctx: Context; + request: Request; + } + + interface Context extends BaseContext { + app: Application; + request: Request; + response: Response; + req: IncomingMessage; + res: ServerResponse; + originalUrl: string; + cookies: Cookies; + accept: accepts.Accepts; + state: any; + } +} + +export = Application; diff --git a/later/index.d.ts b/later/index.d.ts index c5c2449a00..5dd68ec90a 100644 --- a/later/index.d.ts +++ b/later/index.d.ts @@ -142,7 +142,7 @@ declare namespace later { * For acces to custom time periods created as extension to the later static type * and modifiers created on the later modifier static type. */ - [ timeperiodAndModifierName: string ]: number[]; + [ timeperiodAndModifierName: string ]: number[] | undefined; } interface ParseStatic { diff --git a/later/later-tests.ts b/later/later-tests.ts index 1d8c272f1b..1ecd1d6d0e 100644 --- a/later/later-tests.ts +++ b/later/later-tests.ts @@ -6,7 +6,7 @@ namespace LaterTest_DefineSchedule { var textSched = later.parse.text('at 10:15am every weekday'); var cronSched = later.parse.cron('0 0/5 14,18 * * ?'); var recurSched = later.parse.recur().last().dayOfMonth(); - var manualSched = { schedules: [ { M: [ 3 ], D: [ 21 ] } ] }; + var manualSched = { schedules: [ { M: [ 3 ], D: [ 21 ] } ] }; // this schedule will fire on the closest weekday to the 15th // every month at 2:00 am except in March @@ -406,13 +406,13 @@ namespace LaterTest_TimePeriods { // 'Mon, 31 Dec 2012 23:59:59 GMT' } - export interface IPartOfDayLater extends later.Static { + export interface PartOfDayLater extends later.Static { partOfDay: later.TimePeriod; } export function custom() { - var customLater = later; + var customLater = later; customLater.partOfDay = { @@ -420,7 +420,7 @@ namespace LaterTest_TimePeriods { range: later.hour.range * 6, - val: function(d: Date): number { + val(d: Date): number { return later.hour.val(d) < 12 ? 0 : later.hour.val(d) < 18 @@ -428,15 +428,15 @@ namespace LaterTest_TimePeriods { : 2; }, - isValid: function(d: Date, val: any) { + isValid(d: Date, val: any) { return customLater.partOfDay.val(d) === val; }, - extent: function(date?: Date) { + extent(date?: Date) { return [0, 2]; }, - start: function(date: Date) { + start(date: Date) { var hour = customLater.partOfDay.val(date) === 0 ? 0 : customLater.partOfDay.val(date) === 1 @@ -451,7 +451,7 @@ namespace LaterTest_TimePeriods { ); }, - end: function(date: Date) { + end(date: Date) { var hour = customLater.partOfDay.val(date) === 0 ? 11 : customLater.partOfDay.val(date) === 1 @@ -466,7 +466,7 @@ namespace LaterTest_TimePeriods { ); }, - next: function(date: Date, val: any) { + next(date: Date, val: any) { var hour = val === 0 ? 0 : val === 1 @@ -482,7 +482,7 @@ namespace LaterTest_TimePeriods { ); }, - prev: function(date: Date, val: any) { + prev(date: Date, val: any) { var hour = val === 0 ? 11 : val === 1 @@ -578,7 +578,7 @@ namespace LaterTest_GenerateRecurences { var sched = later.parse.recur() .every(2).hour().first().dayOfMonth() .and() - .on(8, 20).hour().last().dayOfMonth() + .on(8, 20).hour().last().dayOfMonth(); } export function except_method() { diff --git a/later/tsconfig.json b/later/tsconfig.json index 78a6cefd34..add4a07667 100644 --- a/later/tsconfig.json +++ b/later/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/later/tslint.json b/later/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/later/tslint.json +++ b/later/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/leaflet-draw/leaflet-draw-tests.ts b/leaflet-draw/leaflet-draw-tests.ts index 98d3681789..4260eac263 100644 --- a/leaflet-draw/leaflet-draw-tests.ts +++ b/leaflet-draw/leaflet-draw-tests.ts @@ -37,7 +37,7 @@ var drawControl = new L.Control.Draw({ }); map.addControl(drawControl); -map.on('draw:created', function (e: any) { +map.on('draw:created', (e: any) => { var drawEvent = (e as L.DrawEvents.Created); var type = drawEvent.layerType, layer = drawEvent.layer; diff --git a/leaflet-draw/tslint.json b/leaflet-draw/tslint.json index 9bc375c06b..105f5736e6 100644 --- a/leaflet-draw/tslint.json +++ b/leaflet-draw/tslint.json @@ -3,4 +3,4 @@ "rules": { "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/leaflet-imageoverlay-rotated/index.d.ts b/leaflet-imageoverlay-rotated/index.d.ts new file mode 100644 index 0000000000..acb4d7f172 --- /dev/null +++ b/leaflet-imageoverlay-rotated/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for leaflet-imageoverlay-rotated 0.1 +// Project: https://github.com/IvanSanchez/Leaflet.ImageOverlay.Rotated +// Definitions by: Thomas Kleinke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + + namespace ImageOverlay { + + export interface Rotated extends L.ImageOverlay { + reposition(topleft: L.LatLngExpression, + topright: L.LatLngExpression, + bottomleft: L.LatLngExpression): void; + } + } + + namespace imageOverlay { + + export function rotated(imgSrc: string | HTMLImageElement | HTMLCanvasElement, + topleft: L.LatLngExpression, + topright: L.LatLngExpression, + bottomleft: L.LatLngExpression, + options?: L.ImageOverlayOptions): L.ImageOverlay.Rotated; + } +} diff --git a/leaflet-imageoverlay-rotated/leaflet-imageoverlay-rotated-tests.ts b/leaflet-imageoverlay-rotated/leaflet-imageoverlay-rotated-tests.ts new file mode 100644 index 0000000000..1b2ffd6c20 --- /dev/null +++ b/leaflet-imageoverlay-rotated/leaflet-imageoverlay-rotated-tests.ts @@ -0,0 +1,10 @@ +var topleft = L.latLng(40.52256691873593, -3.7743186950683594); +var topright = L.latLng(40.5210255066156, -3.7734764814376835); +var bottomleft = L.latLng(40.52180437272552, -3.7768453359603886); + +var overlay = L.imageOverlay.rotated("image.jpg", topleft, topright, bottomleft, { + opacity: 0.5, + interactive: true +}); + +overlay.reposition(topleft, topright, bottomleft); diff --git a/leaflet-imageoverlay-rotated/tsconfig.json b/leaflet-imageoverlay-rotated/tsconfig.json new file mode 100644 index 0000000000..c6f8181b86 --- /dev/null +++ b/leaflet-imageoverlay-rotated/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", + "leaflet-imageoverlay-rotated-tests.ts" + ] +} \ No newline at end of file diff --git a/leaflet-imageoverlay-rotated/tslint.json b/leaflet-imageoverlay-rotated/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/leaflet-imageoverlay-rotated/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/leaflet-label/leaflet-label-tests.ts b/leaflet-label/leaflet-label-tests.ts index bdfee67e62..eba8c5907b 100644 --- a/leaflet-label/leaflet-label-tests.ts +++ b/leaflet-label/leaflet-label-tests.ts @@ -23,7 +23,7 @@ circleMarker.showLabel(); circleMarker.hideLabel(); circleMarker.setLabelNoHide(true); circleMarker.updateLabelContent('test2'); -label = circleMarker.getLabel() +label = circleMarker.getLabel(); circleMarker = circleMarker.unbindLabel(); // Marker @@ -43,7 +43,7 @@ marker.showLabel(); marker.hideLabel(); marker.setLabelNoHide(true); marker.updateLabelContent('test2'); -label = marker.getLabel() +label = marker.getLabel(); marker = marker.unbindLabel(); marker.setOpacity(0.5); marker.setOpacity(0.5, true); diff --git a/leaflet-label/tslint.json b/leaflet-label/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/leaflet-label/tslint.json +++ b/leaflet-label/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/leaflet-markercluster/leaflet-markercluster-tests.ts b/leaflet-markercluster/leaflet-markercluster-tests.ts index 346239f836..7488a4e132 100644 --- a/leaflet-markercluster/leaflet-markercluster-tests.ts +++ b/leaflet-markercluster/leaflet-markercluster-tests.ts @@ -26,7 +26,7 @@ markerClusterGroupOptions = { }, chunkedLoading: false, chunkDelay: 100 -} +}; let markerClusterGroup: L.MarkerClusterGroup; markerClusterGroup = L.markerClusterGroup(); diff --git a/leaflet-markercluster/tslint.json b/leaflet-markercluster/tslint.json index 192203ab54..377cc837d4 100644 --- a/leaflet-markercluster/tslint.json +++ b/leaflet-markercluster/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/leaflet.gridlayer.googlemutant/index.d.ts b/leaflet.gridlayer.googlemutant/index.d.ts new file mode 100644 index 0000000000..a5fa96ae80 --- /dev/null +++ b/leaflet.gridlayer.googlemutant/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for leaflet.gridlayer.googlemutant 0.4 +// Project: https://gitlab.com/IvanSanchez/Leaflet.GridLayer.GoogleMutant#README +// Definitions by: Ernest Rhinozeros +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L.gridLayer { + export interface GoogleMutant extends L.GridLayer { + setElementSize(e: HTMLElement, size: L.Point): void ; + } + + export type GoogleMutantType = 'roadmap' | 'satellite' | 'terrain' | 'hybrid'; + + export interface GoogleMutantStyler { + hue?: string; + lightness?: number; + saturation?: number; + gamma?: number; + invert_lightness?: boolean; + visibility?: string; + color?: string; + weight?: number; + } + + /** + * Google's map style. + * + * https://developers.google.com/maps/documentation/javascript/style-reference + */ + export interface GoogleMutantStyle { + + /** + * https://developers.google.com/maps/documentation/javascript/style-reference#style-features + */ + featureType?: string; + + /** + * https://developers.google.com/maps/documentation/javascript/style-reference#style-elements + */ + elementType?: string; + + /** + * https://developers.google.com/maps/documentation/javascript/style-reference#stylers + */ + stylers?: GoogleMutantStyler[]; + } + + export interface GoogleMutantOptions extends L.TileLayerOptions { + minZoom?: number; + maxZoom?: number; + maxNativeZoom?: number; + tileSize?: number | Point; + subdomains?: string | string[]; + errorTileUrl?: string; + + /** + * The mutant container will add its own attribution anyways. + */ + attribution?: string; + + opacity?: number; + continuousWorld?: boolean; + noWrap?: boolean; + + /** + * Google's map type. 'hybrid' is not really supported. + */ + type?: GoogleMutantType; + + /** + * Google's map styles. + */ + styles?: GoogleMutantStyle[]; + } + + export function googleMutant(options?: GoogleMutantOptions): GoogleMutant; +} diff --git a/leaflet.gridlayer.googlemutant/leaflet.gridlayer.googlemutant-tests.ts b/leaflet.gridlayer.googlemutant/leaflet.gridlayer.googlemutant-tests.ts new file mode 100644 index 0000000000..797947f9c7 --- /dev/null +++ b/leaflet.gridlayer.googlemutant/leaflet.gridlayer.googlemutant-tests.ts @@ -0,0 +1,13 @@ +let map = L.map('foo'); + +let roads = L.gridLayer.googleMutant({ + type: 'roadmap' +}).addTo(map); + +let styled = L.gridLayer.googleMutant({ + type: 'satellite', + styles: [ + { elementType: 'labels', stylers: [ { visibility: 'off' } ] }, + { featureType: 'water' , stylers: [ { color: '#444444' } ] } + ] +}).addTo(map); diff --git a/leaflet.gridlayer.googlemutant/tsconfig.json b/leaflet.gridlayer.googlemutant/tsconfig.json new file mode 100644 index 0000000000..7001206f48 --- /dev/null +++ b/leaflet.gridlayer.googlemutant/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", + "leaflet.gridlayer.googlemutant-tests.ts" + ] +} \ No newline at end of file diff --git a/leaflet.gridlayer.googlemutant/tslint.json b/leaflet.gridlayer.googlemutant/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/leaflet.gridlayer.googlemutant/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/leaflet.pm/index.d.ts b/leaflet.pm/index.d.ts new file mode 100644 index 0000000000..7e9e2a1c14 --- /dev/null +++ b/leaflet.pm/index.d.ts @@ -0,0 +1,96 @@ +// Type definitions for leaflet.pm 0.13 +// Project: https://github.com/codeofsumit/leaflet.pm +// Definitions by: Thomas Kleinke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + + export interface Map { + pm: PM.Map; + } + + export interface Polygon { + pm: PM.Edit.Line; + } + + export interface Polyline { + pm: PM.Edit.Line; + } + + export interface Marker { + pm: PM.Edit.Marker; + } + + export interface LayerGroup { + pm: PM.Edit.LayerGroup; + } + + export namespace PM { + + export interface Map { + addControls(options?: PM.ToolbarOptions): void; + enableDraw(shape: string, options?: PM.DrawOptions): void; + disableDraw(shape: string): void; + setPathOptions(options: L.PathOptions): void; + toggleRemoval(enabled: boolean): void; + globalEditEnabled(): boolean; + toggleGlobalEditMode(options?: PM.EditOptions): void; + + Draw: PM.Draw; + } + + export interface Draw { + getShapes(): string[]; + } + + export interface ToolbarOptions { + position?: string; // topleft | topright | bottomleft | bottomright + drawMarker?: boolean; + drawPolygon?: boolean; + drawPolyline?: boolean; + editPolygon?: boolean; + deleteLayer?: boolean; + } + + export interface DrawOptions { + templineStyle?: L.PathOptions; + hintlineStyle?: L.PathOptions; + pathOptions?: L.PathOptions; + } + + export interface EditOptions { + draggable?: boolean; + snappable?: boolean; + snapDistance?: number; + } + + export namespace Edit { + + export interface Line { + enable(options?: EditOptions): void; + disable(poly?: L.Layer): void; + toggleEdit(options?: EditOptions): void; + enabled(): boolean; + } + + export interface Marker { + enable(options?: EditOptions): void; + disable(): void; + toggleEdit(options?: EditOptions): void; + enabled(): boolean; + } + + export interface LayerGroup { + enable(options?: EditOptions): void; + disable(): void; + toggleEdit(options?: EditOptions): void; + enabled(): boolean; + findLayers(): L.Layer[]; + dragging(): boolean; + getOptions(): EditOptions; + } + } + } +} diff --git a/leaflet.pm/leaflet.pm-tests.ts b/leaflet.pm/leaflet.pm-tests.ts new file mode 100644 index 0000000000..88c804acff --- /dev/null +++ b/leaflet.pm/leaflet.pm-tests.ts @@ -0,0 +1,68 @@ +var toolbarOptions: L.PM.ToolbarOptions = { + position: 'topleft', + drawMarker: true, + drawPolygon: true, + drawPolyline: true, + editPolygon: true, + deleteLayer: true +}; + +var drawOptions: L.PM.DrawOptions = { + templineStyle: { + color: 'red' + }, + hintlineStyle: { + color: 'red', + dashArray: '5, 5' + } +}; + +var editOptions: L.PM.EditOptions = { + draggable: true, + snappable: true, + snapDistance: 30 +}; + +var pathOptions: L.PathOptions = { + color: 'orange', + fillColor: 'green', + fillOpacity: 0.5 +}; + +var map: L.Map = L.map('map-element'); +map.pm.addControls(toolbarOptions); +map.pm.enableDraw('Poly', drawOptions); +map.pm.disableDraw('Poly'); +map.pm.setPathOptions(pathOptions); +map.pm.toggleRemoval(true); +var enabled: boolean = map.pm.globalEditEnabled(); +map.pm.toggleGlobalEditMode(editOptions); + +var shapes: string[] = map.pm.Draw.getShapes(); + +var polygon: L.Polygon = L.polygon([ [ 1.0, 1.0], [ 2.0, 1.0], [ 1.0, 2.0] ]); +polygon.pm.enable(editOptions); +polygon.pm.disable(); +polygon.pm.toggleEdit(editOptions); +enabled = polygon.pm.enabled(); + +var polyline: L.Polyline = L.polyline([ [ 1.0, 1.0], [ 2.0, 1.0], [ 1.0, 2.0] ]); +polyline.pm.enable(editOptions); +polyline.pm.disable(); +polyline.pm.toggleEdit(editOptions); +enabled = polyline.pm.enabled(); + +var marker: L.Marker = L.marker([ 3.0, 3.0 ]); +marker.pm.enable(editOptions); +marker.pm.disable(); +marker.pm.toggleEdit(editOptions); +enabled = marker.pm.enabled(); + +var layerGroup: L.LayerGroup = L.layerGroup([ polygon, polyline, marker ]); +layerGroup.pm.enable(editOptions); +layerGroup.pm.disable(); +layerGroup.pm.toggleEdit(editOptions); +enabled = layerGroup.pm.enabled(); +var layers: L.Layer[] = layerGroup.pm.findLayers(); +var dragging: boolean = layerGroup.pm.dragging(); +var options: L.PM.EditOptions = layerGroup.pm.getOptions(); diff --git a/leaflet.pm/tsconfig.json b/leaflet.pm/tsconfig.json new file mode 100644 index 0000000000..f106913bbd --- /dev/null +++ b/leaflet.pm/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", + "leaflet.pm-tests.ts" + ] +} \ No newline at end of file diff --git a/leaflet.pm/tslint.json b/leaflet.pm/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/leaflet.pm/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index c031df81bc..de463ae997 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Leaflet.js 1.0.2 +// Type definitions for Leaflet.js 1.0 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,6 +8,19 @@ type NativeMouseEvent = MouseEvent; type NativeKeyboardEvent = KeyboardEvent; +// Import to avoid conflicts with the GeoJSON class of leaflet +import GeoJSONFeature = GeoJSON.Feature; +import GeoJSONLineString = GeoJSON.LineString; +import GeoJSONMultiLineString = GeoJSON.MultiLineString; +import GeoJSONPolygon = GeoJSON.Polygon; +import GeoJSONMultiPolygon = GeoJSON.MultiPolygon; +import GeoJSONFeatureCollection = GeoJSON.FeatureCollection; +import GeoJSONGeometryObject = GeoJSON.GeometryObject; +import GeoJSONGeometryCollection = GeoJSON.GeometryCollection; +import GeoJSONPoint = GeoJSON.Point; +import GeoJSONMultiPoint = GeoJSON.MultiPoint; +import GeoJSONGeoJsonObject = GeoJSON.GeoJsonObject; + declare namespace L { export class Class { static extend(props: any): any/* how to return constructor of self extended type ? */; @@ -25,43 +38,37 @@ declare namespace L { } export namespace LineUtil { - export function simplify(points: Array, tolerance: number): Array; + export function simplify(points: PointExpression[], tolerance: number): Point[]; - export function simplify(points: Array, tolerance: number): Array; + export function pointToSegmentDistance(p: PointExpression, p1: PointExpression, p2: PointExpression): number; - export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; - - export function pointToSegmentDistance(p: PointTuple, p1: PointTuple, p2: PointTuple): number; - - export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; - - export function closestPointOnSegment(p: PointTuple, p1: PointTuple, p2: PointTuple): Point; + export function closestPointOnSegment(p: PointExpression, p1: PointExpression, p2: PointExpression): Point; } export namespace PolyUtil { - export function clipPolygon(points: Array, bounds: Bounds, round?: boolean): Array; - - export function clipPolygon(points: Array, bounds: BoundsLiteral, round?: boolean): Array; + export function clipPolygon(points: PointExpression[], bounds: BoundsExpression, round?: boolean): Point[]; } export class DomUtil { - static get(id: string): HTMLElement; - static get(id: HTMLElement): HTMLElement; + /** + * Get Element by its ID or with the given HTML-Element + */ + static get(element: string | HTMLElement): HTMLElement; static getStyle(el: HTMLElement, styleAttrib: string): string; - static create(tagName: String, className?: String, container?: HTMLElement): HTMLElement; - static remove(el: HTMLElement):void; - static empty(el: HTMLElement):void; - static toFront(el: HTMLElement):void; - static toBack(el: HTMLElement):void; - static hasClass(el: HTMLElement, name: String): Boolean; - static addClass(el: HTMLElement, name: String):void; - static removeClass(el: HTMLElement, name: String):void; - static setClass(el: HTMLElement, name: String):void; - static getClass(el: HTMLElement): String; - static setOpacity(el: HTMLElement, opacity: Number):void; - static testProp(props: String[]): String|boolean/*=false*/; - static setTransform(el: HTMLElement, offset: Point, scale?: Number):void; - static setPosition(el: HTMLElement, position: Point):void; + static create(tagName: string, className?: string, container?: HTMLElement): HTMLElement; + static remove(el: HTMLElement): void; + static empty(el: HTMLElement): void; + static toFront(el: HTMLElement): void; + static toBack(el: HTMLElement): void; + static hasClass(el: HTMLElement, name: string): boolean; + static addClass(el: HTMLElement, name: string): void; + static removeClass(el: HTMLElement, name: string): void; + static setClass(el: HTMLElement, name: string): void; + static getClass(el: HTMLElement): string; + static setOpacity(el: HTMLElement, opacity: number): void; + static testProp(props: string[]): string | boolean/*=false*/; + static setTransform(el: HTMLElement, offset: Point, scale?: number): void; + static setPosition(el: HTMLElement, position: Point): void; static getPosition(el: HTMLElement): Point; static disableTextSelection(): void; static enableTextSelection(): void; @@ -71,7 +78,7 @@ declare namespace L { static restoreOutline(): void; } - export interface CRS { + export abstract class CRS { latLngToPoint(latlng: LatLngExpression, zoom: number): Point; pointToLatLng(point: PointExpression, zoom: number): LatLng; project(latlng: LatLngExpression): Point; @@ -109,7 +116,9 @@ declare namespace L { export const SphericalMercator: Projection; } - export interface LatLng { + export class LatLng { + constructor(latitude: number, longitude: number, altitude?: number); + constructor(coords: LatLngTuple | [number, number, number] | LatLngLiteral | {lat: number, lng: number, alt?: number}); equals(otherLatLng: LatLngExpression, maxMargin?: number): boolean; toString(): string; distanceTo(otherLatLng: LatLngExpression): number; @@ -132,17 +141,12 @@ declare namespace L { export function latLng(latitude: number, longitude: number, altitude?: number): LatLng; - export function latLng(coords: LatLngTuple): LatLng; + export function latLng(coords: LatLngTuple | [number, number, number] | LatLngLiteral | {lat: number, lng: number, alt?: number}): LatLng; - export function latLng(coords: [number, number, number]): LatLng; - - export function latLng(coords: LatLngLiteral): LatLng; - - export function latLng(coords: {lat: number, lng: number, alt: number}): LatLng; - - export interface LatLngBounds { - extend(latlng: LatLngExpression): this; - extend(otherBounds: LatLngBoundsExpression): this; + export class LatLngBounds { + constructor(southWest: LatLngExpression, northEast: LatLngExpression); + constructor(latlngs: LatLngBoundsLiteral); + extend(latlngOrBounds: LatLngExpression | LatLngBoundsExpression): this; pad(bufferRatio: number): LatLngBounds; // does this modify the current instance or does it return a new one? getCenter(): LatLng; getSouthWest(): LatLng; @@ -153,8 +157,7 @@ declare namespace L { getSouth(): number; getEast(): number; getNorth(): number; - contains(otherBounds: LatLngBoundsExpression): boolean; - contains(latlng: LatLngExpression): boolean; + contains(otherBoundsOrLatLng: LatLngBoundsExpression | LatLngExpression): boolean; intersects(otherBounds: LatLngBoundsExpression): boolean; overlaps(otherBounds: BoundsExpression): boolean; // investigate if this is really bounds and not latlngbounds toBBoxString(): string; @@ -162,7 +165,7 @@ declare namespace L { isValid(): boolean; } - export type LatLngBoundsLiteral = Array; + export type LatLngBoundsLiteral = LatLngTuple[]; // Must be [LatLngTuple, LatLngTuple], cant't change because Map.setMaxBounds type LatLngBoundsExpression = LatLngBounds | LatLngBoundsLiteral; @@ -172,7 +175,9 @@ declare namespace L { export type PointTuple = [number, number]; - export interface Point { + export class Point { + constructor(x: number, y: number, round?: boolean); + constructor(coords: PointTuple | {x: number, y: number}); clone(): Point; add(otherPoint: PointExpression): Point; // investigate if this mutates or returns a new instance subtract(otherPoint: PointExpression): Point; @@ -195,20 +200,19 @@ declare namespace L { export function point(x: number, y: number, round?: boolean): Point; - export function point(coords: PointTuple): Point; + export function point(coords: PointTuple | {x: number, y: number}): Point; - export function point(coords: {x: number, y: number}): Point; + export type BoundsLiteral = [PointTuple, PointTuple]; - export type BoundsLiteral = Array; - - export interface Bounds { + export class Bounds { + constructor(topLeft: PointExpression, bottomRight: PointExpression); + constructor(points: Point[] | BoundsLiteral); extend(point: PointExpression): this; getCenter(round?: boolean): Point; getBottomLeft(): Point; getTopRight(): Point; getSize(): Point; - contains(otherBounds: BoundsExpression): boolean; - contains(point: PointExpression): boolean; + contains(pointOrBounds: BoundsExpression | PointExpression): boolean; intersects(otherBounds: BoundsExpression): boolean; overlaps(otherBounds: BoundsExpression): boolean; @@ -220,13 +224,13 @@ declare namespace L { export function bounds(topLeft: PointExpression, bottomRight: PointExpression): Bounds; - export function bounds(points: Array): Bounds; - - export function bounds(points: BoundsLiteral): Bounds; + export function bounds(points: Point[] | BoundsLiteral): Bounds; export type EventHandlerFn = (event: Event) => void; - export type EventHandlerFnMap = {[type: string]: EventHandlerFn}; + export interface EventHandlerFnMap { + [type: string]: EventHandlerFn; + } /** * A set of methods shared between event-powered classes (like Map and Marker). @@ -248,6 +252,7 @@ declare namespace L { */ on(eventMap: EventHandlerFnMap): this; + /* tslint:disable:unified-signatures */ // With an eventMap there are no additional arguments allowed /** * Removes a previously added listener function. If no function is specified, * it will remove all the listeners of that particular event from the object. @@ -260,7 +265,7 @@ declare namespace L { * Removes a set of type/listener pairs. */ off(eventMap: EventHandlerFnMap): this; - + /* tslint:enable */ /** * Removes all listeners to all events on the object. */ @@ -401,35 +406,23 @@ declare namespace L { getPane(name?: string): HTMLElement; // Popup methods - bindPopup(content: string, options?: PopupOptions): this; - bindPopup(content: HTMLElement, options?: PopupOptions): this; - bindPopup(content: (layer: Layer) => Content, options?: PopupOptions): this; - bindPopup(content: Popup): this; + bindPopup(content: ((layer: Layer) => Content) | Content | Popup, options?: PopupOptions): this; unbindPopup(): this; - openPopup(): this; - openPopup(latlng: LatLngExpression): this; + openPopup(latlng?: LatLngExpression): this; closePopup(): this; togglePopup(): this; isPopupOpen(): boolean; - setPopupContent(content: string): this; - setPopupContent(content: HTMLElement): this; - setPopupContent(content: Popup): this; + setPopupContent(content: Content | Popup): this; getPopup(): Popup; // Tooltip methods - bindTooltip(content: string, options?: TooltipOptions): this; - bindTooltip(content: HTMLElement, options?: TooltipOptions): this; - bindTooltip(content: (layer: Layer) => Content, options?: TooltipOptions): this; - bindTooltip(content: Tooltip, options?: TooltipOptions): this; + bindTooltip(content: ((layer: Layer) => Content) | Tooltip | Content, options?: TooltipOptions): this; unbindTooltip(): this; - openTooltip(): this; - openTooltip(latlng: LatLngExpression): this; + openTooltip(latlng?: LatLngExpression): this; closeTooltip(): this; toggleTooltip(): this; isTooltipOpen(): boolean; - setTooltipContent(content: string): this; - setTooltipContent(content: HTMLElement): this; - setTooltipContent(content: Tooltip): this; + setTooltipContent(content: Content | Tooltip): this; getTooltip(): Tooltip; // Extension methods @@ -457,7 +450,8 @@ declare namespace L { keepBuffer?: number; } - export interface GridLayer extends Layer { + export class GridLayer extends Layer { + constructor(options?: GridLayerOptions); bringToFront(): this; bringToBack(): this; getAttribution(): string; @@ -475,7 +469,8 @@ declare namespace L { minZoom?: number; maxZoom?: number; maxNativeZoom?: number; - subdomains?: string | Array; + minNativeZoom?: number; + subdomains?: string | string[]; errorTileUrl?: string; zoomOffset?: number; tms?: boolean; @@ -485,12 +480,25 @@ declare namespace L { [name: string]: any; } - export interface TileLayer extends GridLayer { + export class TileLayer extends GridLayer { + constructor(urlTemplate: string, options?: TileLayerOptions); setUrl(url: string, noRedraw?: boolean): this; + + options: TileLayerOptions; } export function tileLayer(urlTemplate: string, options?: TileLayerOptions): TileLayer; + export namespace TileLayer { + export class WMS extends TileLayer { + constructor(baseUrl: string, options: WMSOptions); + setParams(params: WMSParams, noRedraw?: boolean): this; + + wmsParams: WMSParams; + options: WMSOptions; + } + } + export interface WMSOptions extends TileLayerOptions { layers: string; styles?: string; @@ -501,12 +509,20 @@ declare namespace L { uppercase?: boolean; } - export interface WMS extends TileLayer { - setParams(params: any, noRedraw?: boolean): this; + export interface WMSParams { + format?: string; + layers: string; + request?: string; + service?: string; + styles?: string; + version?: string; + transparent?: boolean; + width?: number; + height?: number; } export namespace tileLayer { - export function wms(baseUrl: string, options?: WMSOptions): WMS; + export function wms(baseUrl: string, options?: WMSOptions): TileLayer.WMS; } export interface ImageOverlayOptions extends LayerOptions { @@ -517,7 +533,8 @@ declare namespace L { crossOrigin?: boolean; } - export interface ImageOverlay extends Layer { + export class ImageOverlay extends Layer { + constructor(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions); setOpacity(opacity: number): this; bringToFront(): this; bringToBack(): this; @@ -531,6 +548,8 @@ declare namespace L { /** Get the img element that represents the ImageOverlay on the map */ getElement(): HTMLImageElement; + + options: ImageOverlayOptions; } export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; @@ -558,11 +577,14 @@ declare namespace L { className?: string; } - export interface Path extends Layer { + export abstract class Path extends Layer { redraw(): this; setStyle(style: PathOptions): this; bringToFront(): this; bringToBack(): this; + getElement(): HTMLElement; + + options: PathOptions; } export interface PolylineOptions extends PathOptions { @@ -570,32 +592,37 @@ declare namespace L { noClip?: boolean; } - interface InternalPolyline extends Path { - getLatLngs(): Array; - setLatLngs(latlngs: Array): this; + class InternalPolyline extends Path { + getLatLngs(): LatLng[]; + setLatLngs(latlngs: LatLngExpression[]): this; isEmpty(): boolean; getCenter(): LatLng; getBounds(): LatLngBounds; - addLatLng(latlng: LatLngExpression): this; - addLatLng(latlng: Array): this; // these three overloads aren't explicitly noted in the docs + addLatLng(latlng: LatLngExpression | LatLngExpression[]): this; + + options: PolylineOptions; } - export interface Polyline extends InternalPolyline { - toGeoJSON(): GeoJSON.LineString | GeoJSON.MultiLineString; + export class Polyline extends InternalPolyline { + constructor(latlngs: LatLngExpression[], options?: PolylineOptions); + toGeoJSON(): GeoJSONFeature; + + feature: GeoJSONFeature; } - export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; - export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + export function polyline(latlngs: LatLngExpression[], options?: PolylineOptions): Polyline; - export interface Polygon extends InternalPolyline { - toGeoJSON(): GeoJSON.Polygon | GeoJSON.MultiPolygon; + export class Polygon extends InternalPolyline { + constructor(latlngs: LatLngExpression[], options?: PolylineOptions); + toGeoJSON(): GeoJSONFeature; + + feature: GeoJSONFeature; } - export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + export function polygon(latlngs: LatLngExpression[], options?: PolylineOptions): Polygon; - export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; - - export interface Rectangle extends Polygon { + export class Rectangle extends Polygon { + constructor(latLngBounds: LatLngBoundsExpression, options?: PolylineOptions); setBounds(latLngBounds: LatLngBoundsExpression): this; } @@ -605,48 +632,50 @@ declare namespace L { radius?: number; } - export interface CircleMarker extends Path { - toGeoJSON(): GeoJSON.Point; + export class CircleMarker extends Path { + constructor(latlng: LatLngExpression, options?: CircleMarkerOptions); + toGeoJSON(): GeoJSONFeature; setLatLng(latLng: LatLngExpression): this; getLatLng(): LatLng; setRadius(radius: number): this; getRadius(): number; + + options: CircleMarkerOptions; + feature: GeoJSONFeature; } export function circleMarker(latlng: LatLngExpression, options?: CircleMarkerOptions): CircleMarker; - export interface CircleOptions extends PathOptions { - radius?: number; - } - - export interface Circle extends CircleMarker { - setRadius(radius: number): this; - getRadius(): number; + export class Circle extends CircleMarker { + constructor(latlng: LatLngExpression, options?: CircleMarkerOptions); + constructor(latlng: LatLngExpression, radius: number, options?: CircleMarkerOptions); // deprecated! getBounds(): LatLngBounds; } - export function circle(latlng: LatLngExpression, options?: CircleOptions): Circle; - export function circle(latlng: LatLngExpression, radius: number, options?: CircleOptions): Circle; + export function circle(latlng: LatLngExpression, options?: CircleMarkerOptions): Circle; + export function circle(latlng: LatLngExpression, radius: number, options?: CircleMarkerOptions): Circle; // deprecated! export interface RendererOptions extends LayerOptions { padding?: number; } - export interface Renderer extends Layer {} + export class Renderer extends Layer { + constructor(options?: RendererOptions); - export interface SVG extends Renderer {} + options: RendererOptions; + } + + export class SVG extends Renderer {} export namespace SVG { export function create(name: string): SVGElement; - export function pointsToPath(rings: Array, close: boolean): string; - - export function pointsToPath(rings: Array, close: boolean): string; + export function pointsToPath(rings: PointExpression[], close: boolean): string; } export function svg(options?: RendererOptions): SVG; - export interface Canvas extends Renderer {} + export class Canvas extends Renderer {} export function canvas(options?: RendererOptions): Canvas; @@ -655,11 +684,12 @@ declare namespace L { * If you add it to the map, any layers added or removed from the group will be * added/removed on the map as well. Extends Layer. */ - export interface LayerGroup extends Layer { + export class LayerGroup extends Layer { + constructor(layers: Layer[]); /** - * Returns a GeoJSON representation of the layer group (as a GeoJSON GeometryCollection). + * Returns a GeoJSON representation of the layer group (as a GeoJSON GeometryCollection, GeoJSONFeatureCollection or Multipoint). */ - toGeoJSON(): GeoJSON.GeometryCollection; + toGeoJSON(): GeoJSONFeatureCollection | GeoJSONFeature | GeoJSONGeometryCollection; /** * Adds the given layer to the group. @@ -667,14 +697,9 @@ declare namespace L { addLayer(layer: Layer): this; /** - * Removes the given layer from the group. + * Removes the layer with the given internal ID or the given layer from the group. */ - removeLayer(layer: Layer): this; - - /** - * Removes the layer with the given internal ID from the group. - */ - removeLayer(id: number): this; + removeLayer(layer: number | Layer): this; /** * Returns true if the given layer is currently added to the group. @@ -690,7 +715,7 @@ declare namespace L { * Calls methodName on every layer contained in this group, passing any additional parameters. * Has no effect if the layers contained do not implement methodName. */ - invoke(methodName: string, ...params: Array): this; + invoke(methodName: string, ...params: any[]): this; /** * Iterates over the layers of the group, @@ -706,7 +731,7 @@ declare namespace L { /** * Returns an array of all the layers added to the group. */ - getLayers(): Array; + getLayers(): Layer[]; /** * Calls setZIndex on every layer contained in this group, passing the z-index. @@ -717,18 +742,20 @@ declare namespace L { * Returns the internal ID for a layer */ getLayerId(layer: Layer): number; + + feature: GeoJSONFeatureCollection | GeoJSONFeature | GeoJSONGeometryCollection; } /** * Create a layer group, optionally given an initial set of layers. */ - export function layerGroup(layers: Array): LayerGroup; + export function layerGroup(layers: Layer[]): LayerGroup; /** * Extended LayerGroup that also has mouse events (propagated from * members of the group) and a shared bindPopup method. */ - export interface FeatureGroup extends LayerGroup { + export class FeatureGroup extends LayerGroup { /** * Sets the given path options to each layer of the group that has a setStyle method. */ @@ -754,9 +781,9 @@ declare namespace L { /** * Create a feature group, optionally given an initial set of layers. */ - export function featureGroup(layers?: Array): FeatureGroup; + export function featureGroup(layers?: Layer[]): FeatureGroup; - type StyleFunction = (feature: GeoJSON.Feature) => PathOptions; + type StyleFunction = (feature: GeoJSONFeature) => PathOptions; export interface GeoJSONOptions extends LayerOptions { /** @@ -772,7 +799,7 @@ declare namespace L { * } * ``` */ - pointToLayer?: (geoJsonPoint: GeoJSON.Feature, latlng: LatLng) => Layer; // should import GeoJSON typings + pointToLayer?: (geoJsonPoint: GeoJSONFeature, latlng: LatLng) => Layer; // should import GeoJSON typings /** * A Function defining the Path options for styling GeoJSON lines and polygons, @@ -798,7 +825,7 @@ declare namespace L { * function (feature, layer) {} * ``` */ - onEachFeature?: (feature: GeoJSON.Feature, layer: Layer) => void; + onEachFeature?: (feature: GeoJSONFeature, layer: Layer) => void; /** * A Function that will be used to decide whether to show a feature or not. @@ -811,7 +838,7 @@ declare namespace L { * } * ``` */ - filter?: (geoJsonFeature: GeoJSON.Feature) => boolean; + filter?: (geoJsonFeature: GeoJSONFeature) => boolean; /** * A Function that will be used for converting GeoJSON coordinates to LatLngs. @@ -820,12 +847,16 @@ declare namespace L { coordsToLatLng?: (coords: [number, number] | [number, number, number]) => LatLng; // check if LatLng has an altitude property } - export class GeoJSON { + /** + * Represents a GeoJSON object or an array of GeoJSON objects. + * Allows you to parse GeoJSON data and display it on the map. Extends FeatureGroup. + */ + export class GeoJSON extends FeatureGroup { /** * Creates a Layer from a given GeoJSON feature. Can use a custom pointToLayer * and/or coordsToLatLng functions if provided as options. */ - static geometryToLayer(featureData: GeoJSON.Feature, options?: GeoJSONOptions): Layer; + static geometryToLayer(featureData: GeoJSONFeature, options?: GeoJSONOptions): Layer; /** * Creates a LatLng object from an array of 2 numbers (longitude, latitude) or @@ -849,7 +880,6 @@ declare namespace L { */ static latLngToCoords(latlng: LatLng): [number, number, number]; // A three tuple can be assigned to a two or three tuple - /** * Reverse of coordsToLatLngs closed determines whether the first point should be * appended to the end of the array to close the feature, only used when levelsDeep is 0. @@ -860,21 +890,13 @@ declare namespace L { /** * Normalize GeoJSON geometries/features into GeoJSON features. */ - static asFeature(geojson: GeoJSON.GeometryObject): GeoJSON.Feature; + static asFeature(geojson: GeoJSONFeature | GeoJSONGeometryObject): GeoJSONFeature; - static asFeature(geojson: GeoJSON.Feature): GeoJSON.Feature; - - } - - /** - * Represents a GeoJSON object or an array of GeoJSON objects. - * Allows you to parse GeoJSON data and display it on the map. Extends FeatureGroup. - */ - export interface GeoJSON extends FeatureGroup { + constructor(geojson?: GeoJSONGeoJsonObject, options?: GeoJSONOptions) /** * Adds a GeoJSON object to the layer. */ - addData(data: GeoJSON.GeoJsonObject): Layer; + addData(data: GeoJSONGeoJsonObject): Layer; /** * Resets the given vector layer's style to the original GeoJSON style, @@ -887,6 +909,8 @@ declare namespace L { */ setStyle(style: StyleFunction): this; + options: GeoJSONOptions; + } /** @@ -896,7 +920,7 @@ declare namespace L { * map (you can alternatively add it later with addData method) and * an options object. */ - export function geoJSON(geojson?: GeoJSON.GeoJsonObject, options?: GeoJSONOptions): GeoJSON; + export function geoJSON(geojson?: GeoJSONGeoJsonObject, options?: GeoJSONOptions): GeoJSON; type Zoom = boolean | 'center'; @@ -922,7 +946,7 @@ declare namespace L { zoom?: number; minZoom?: number; maxZoom?: number; - layers?: Array; + layers?: Layer[]; maxBounds?: LatLngBoundsExpression; renderer?: Renderer; @@ -964,7 +988,7 @@ declare namespace L { } export class Control extends Class { - constructor (options?: ControlOptions); + constructor(options?: ControlOptions); getPosition(): ControlPosition; setPosition(position: ControlPosition): this; getContainer(): HTMLElement; @@ -974,6 +998,8 @@ declare namespace L { // Extension methods onAdd(map: Map): HTMLElement; onRemove(map: Map): void; + + options: ControlOptions; } export namespace Control { @@ -984,16 +1010,21 @@ declare namespace L { zoomOutTitle?: string; } - export interface Zoom extends Control {} + export class Zoom extends Control { + constructor(options?: ZoomOptions); + options: ZoomOptions; + } export interface AttributionOptions extends ControlOptions { prefix?: string | boolean; } - export interface Attribution extends Control { + export class Attribution extends Control { + constructor(options?: AttributionOptions); setPrefix(prefix: string): this; addAttribution(text: string): this; removeAttribution(text: string): this; + options: AttributionOptions; } export interface LayersOptions extends ControlOptions { @@ -1002,12 +1033,18 @@ declare namespace L { hideSingleBase?: boolean; } - export interface Layers extends Control { + interface LayersObject { + [name: string]: Layer; + } + + export class Layers extends Control { + constructor(baseLayers?: LayersObject, overlays?: LayersObject, options?: Control.LayersOptions); addBaseLayer(layer: Layer, name: string): this; addOverlay(layer: Layer, name: string): this; removeLayer(layer: Layer): this; expand(): this; collapse(): this; + options: LayersOptions; } export interface ScaleOptions extends ControlOptions { @@ -1017,17 +1054,18 @@ declare namespace L { updateWhenIdle?: boolean; } - export interface Scale extends Control {} + export class Scale extends Control { + constructor(options?: Control.ScaleOptions); + options: ScaleOptions; + } } export namespace control { - export function zoom(options: Control.ZoomOptions): Control.Zoom; + export function zoom(options?: Control.ZoomOptions): Control.Zoom; - export function attribution(options: Control.AttributionOptions): Control.Attribution; + export function attribution(options?: Control.AttributionOptions): Control.Attribution; - type LayersObject = {[name: string]: Layer}; - - export function layers(baseLayers?: LayersObject, overlays?: LayersObject, options?: Control.LayersOptions): Control.Layers; + export function layers(baseLayers?: Control.LayersObject, overlays?: Control.LayersObject, options?: Control.LayersOptions): Control.Layers; export function scale(options?: Control.ScaleOptions): Control.Scale; } @@ -1055,19 +1093,20 @@ declare namespace L { type Content = string | HTMLElement; - export interface Popup extends Layer { + export class Popup extends Layer { + constructor(options?: PopupOptions, source?: Layer); getLatLng(): LatLng; setLatLng(latlng: LatLngExpression): this; getContent(): Content; - setContent(htmlContent: string): this; - setContent(htmlContent: HTMLElement): this; - setContent(htmlContent: (source: Layer) => Content): this; - getElement(): Content; + setContent(htmlContent: ((source: Layer) => Content) | Content): this; + getElement(): HTMLElement; update(): void; isOpen(): boolean; bringToFront(): this; bringToBack(): this; openOn(map: Map): this; + + options: PopupOptions; } export function popup(options?: PopupOptions, source?: Layer): Popup; @@ -1084,7 +1123,21 @@ declare namespace L { opacity?: number; } - export interface Tooltip extends Layer {} + export class Tooltip extends Layer { + constructor(options?: TooltipOptions, source?: Layer); + setOpacity(val: number): void; + getLatLng(): LatLng; + setLatLng(latlng: LatLngExpression): this; + getContent(): Content; + setContent(htmlContent: ((source: Layer) => Content) | Content): this; + getElement(): HTMLElement; + update(): void; + isOpen(): boolean; + bringToFront(): this; + bringToBack(): this; + + options: TooltipOptions; + } export function tooltip(options?: TooltipOptions, source?: Layer): Tooltip; @@ -1099,7 +1152,9 @@ declare namespace L { noMoveStart?: boolean; } + /* tslint:disable:no-empty-interface */ // This is not empty, it extends two interfaces into one... export interface ZoomPanOptions extends ZoomOptions, PanOptions {} + /* tslint:enable */ export interface FitBoundsOptions extends ZoomOptions, PanOptions { paddingTopLeft?: PointExpression; @@ -1117,7 +1172,8 @@ declare namespace L { enableHighAccuracy?: boolean; } - export interface Handler { + export class Handler extends Class { + constructor(map: Map); enable(): this; disable(): this; enabled(): boolean; @@ -1207,13 +1263,13 @@ declare namespace L { } export namespace DomEvent { - export function on(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; + export function on(el: HTMLElement, types: string, fn: EventHandlerFn, context?: any): typeof DomEvent; - export function on(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; + export function on(el: HTMLElement, eventMap: {[eventName: string]: EventHandlerFn}, context?: any): typeof DomEvent; - export function off(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; + export function off(el: HTMLElement, types: string, fn: EventHandlerFn, context?: any): typeof DomEvent; - export function off(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; + export function off(el: HTMLElement, eventMap: {[eventName: string]: EventHandlerFn}, context?: any): typeof DomEvent; export function stopPropagation(ev: Event): typeof DomEvent; @@ -1229,13 +1285,13 @@ declare namespace L { export function getWheelDelta(ev: Event): number; - export function addListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; + export function addListener(el: HTMLElement, types: string, fn: EventHandlerFn, context?: any): typeof DomEvent; - export function addListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; + export function addListener(el: HTMLElement, eventMap: {[eventName: string]: EventHandlerFn}, context?: any): typeof DomEvent; - export function removeListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: any): typeof DomEvent; + export function removeListener(el: HTMLElement, types: string, fn: EventHandlerFn, context?: any): typeof DomEvent; - export function removeListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: any): typeof DomEvent; + export function removeListener(el: HTMLElement, eventMap: {[eventName: string]: EventHandlerFn}, context?: any): typeof DomEvent; } interface DefaultMapPanes { @@ -1248,7 +1304,8 @@ declare namespace L { popupPane: HTMLElement; } - export interface Map extends Evented { + export class Map extends Evented { + constructor(element: string | HTMLElement, options?: MapOptions); getRenderer(layer: Path): Renderer; // Methods for layers and controls @@ -1259,12 +1316,10 @@ declare namespace L { hasLayer(layer: Layer): boolean; eachLayer(fn: (layer: Layer) => void, context?: any): this; openPopup(popup: Popup): this; - openPopup(content: string, latlng: LatLngExpression, options?: PopupOptions): this; - openPopup(content: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): this; + openPopup(content: Content, latlng: LatLngExpression, options?: PopupOptions): this; closePopup(popup?: Popup): this; openTooltip(tooltip: Tooltip): this; - openTooltip(content: string, latlng: LatLngExpression, options?: TooltipOptions): this; - openTooltip(content: HTMLElement, latlng: LatLngExpression, options?: TooltipOptions): this; + openTooltip(content: Content, latlng: LatLngExpression, options?: TooltipOptions): this; closeTooltip(tooltip?: Tooltip): this; // Methods for modifying map state @@ -1272,8 +1327,7 @@ declare namespace L { setZoom(zoom: number, options?: ZoomPanOptions): this; zoomIn(delta?: number, options?: ZoomOptions): this; zoomOut(delta?: number, options?: ZoomOptions): this; - setZoomAround(latlng: LatLngExpression, zoom: number, options?: ZoomOptions): this; - setZoomAround(offset: Point, zoom: number, options?: ZoomOptions): this; + setZoomAround(position: Point | LatLngExpression, zoom: number, options?: ZoomOptions): this; fitBounds(bounds: LatLngBoundsExpression, options?: FitBoundsOptions): this; fitWorld(options?: FitBoundsOptions): this; panTo(latlng: LatLngExpression, options?: PanOptions): this; @@ -1282,8 +1336,10 @@ declare namespace L { setMinZoom(zoom: number): this; setMaxZoom(zoom: number): this; panInsideBounds(bounds: LatLngBoundsExpression, options?: PanOptions): this; - invalidateSize(options: ZoomPanOptions): this; - invalidateSize(animate: boolean): this; + /** + * Boolean for animate or advanced ZoomPanOptions + */ + invalidateSize(options?: boolean | ZoomPanOptions): this; stop(): this; flyTo(latlng: LatLngExpression, zoom?: number, options?: ZoomPanOptions): this; flyToBounds(bounds: LatLngBoundsExpression, options?: FitBoundsOptions): this; @@ -1292,8 +1348,10 @@ declare namespace L { addHandler(name: string, HandlerClass: () => Handler): this; // HandlerClass is actually a constructor function, is this the right way? remove(): this; createPane(name: string, container?: HTMLElement): HTMLElement; - getPane(pane: string): HTMLElement; - getPane(pane: HTMLElement): HTMLElement; + /** + * Name of the pane or the pane as HTML-Element + */ + getPane(pane: string | HTMLElement): HTMLElement; getPanes(): {[name: string]: HTMLElement} & DefaultMapPanes; getContainer(): HTMLElement; whenReady(fn: () => void, context?: any): this; @@ -1321,7 +1379,6 @@ declare namespace L { distance(latlng1: LatLngExpression, latlng2: LatLngExpression): number; containerPointToLayerPoint(point: PointExpression): Point; layerPointToContainerPoint(point: PointExpression): Point; - layerPointToContainerPoint(point: PointTuple): Point; latLngToContainerPoint(latlng: LatLngExpression): Point; mouseEventToContainerPoint(ev: MouseEvent): Point; mouseEventToLayerPoint(ev: MouseEvent): Point; @@ -1339,14 +1396,17 @@ declare namespace L { scrollWheelZoom: Handler; tap: Handler; touchZoom: Handler; + + options: MapOptions; } - export function map(id: string, options?: MapOptions): Map; + /** + * ID of a HTML-Element as string or the HTML-ELement itself + */ + export function map(element: string | HTMLElement, options?: MapOptions): Map; - export function map(el: HTMLElement, options?: MapOptions): Map; - - export interface IconOptions extends LayerOptions { - iconUrl: string; + interface BaseIconOptions extends LayerOptions { + iconUrl?: string; iconRetinaUrl?: string; iconSize?: PointExpression; iconAnchor?: PointExpression; @@ -1358,29 +1418,38 @@ declare namespace L { className?: string; } - export interface Icon extends Layer { + export interface IconOptions extends BaseIconOptions { + iconUrl: string; + } + + // This class does not exist in reality, it's just a way to provide + // options of more specific types in the sub classes + class BaseIcon extends Layer { createIcon(oldIcon?: HTMLElement): HTMLElement; createShadow(oldIcon?: HTMLElement): HTMLElement; + options: BaseIconOptions; } - export interface IconDefault extends Icon { - imagePath: string; - } - - export class Icon { + export class Icon extends BaseIcon { constructor(options: IconOptions); + options: IconOptions; } export namespace Icon { - export class Default extends Icon { - constructor(options?: IconOptions); - imagePath: string; + export interface DefaultIconOptions extends BaseIconOptions { + imagePath?: string; + } + + export class Default extends BaseIcon { + static imagePath?: string; + constructor(options?: DefaultIconOptions); + options: DefaultIconOptions; } } export function icon(options: IconOptions): Icon; - export interface DivIconOptions extends LayerOptions { + export interface DivIconOptions extends BaseIconOptions { html?: string; bgPos?: PointExpression; iconSize?: PointExpression; @@ -1389,14 +1458,16 @@ declare namespace L { className?: string; } - export class DivIcon extends Icon { + export class DivIcon extends BaseIcon { constructor(options?: DivIconOptions); + options: DivIconOptions; } export function divIcon(options?: DivIconOptions): DivIcon; export interface MarkerOptions extends InteractiveLayerOptions { icon?: Icon; + clickable?: boolean; draggable?: boolean; keyboard?: boolean; title?: string; @@ -1414,9 +1485,10 @@ declare namespace L { setZIndexOffset(offset: number): this; setIcon(icon: Icon): this; setOpacity(opacity: number): this; - getElement(): Element; + getElement(): HTMLElement; // Properties + options: MarkerOptions; dragging: Handler; } @@ -1451,6 +1523,28 @@ declare namespace L { export const vml: boolean; export const svg: boolean; } + + export namespace Util { + export function extend(dest: any, src?: any): any; + export function create(proto: any, properties?: any): any; + export function bind(fn: () => void, ...obj: any[]): () => void; + export function stamp(obj: any): number; + export function throttle(fn: () => void, time: number, context: any): () => void; + export function wrapNum(num: number, range: number[], includeMax?: boolean): number; + export function falseFn(): () => false; + export function formatNum(num: number, digits?: number): number; + export function trim(str: string): string; + export function splitWords(str: string): string[]; + export function setOptions(obj: any, options: any): any; + export function getParamString(obj: any, existingUrl?: string, uppercase?: boolean): string; + export function template(str: string, data: any): string; + export function isArray(obj: any): boolean; + export function indexOf(array: any[], el: any): number; + export function requestAnimFrame(fn: () => void, context?: any, immediate?: boolean): number; + export function cancelAnimFrame(id: number): void; + export let lastId: string; + export let emptyImageUrl: string; + } } declare module 'leaflet' { diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index c6dca97f5d..cce5565851 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -11,6 +11,13 @@ latLng = L.latLng({lat: 12, lng: 13, alt: 0}); latLng = L.latLng(latLngTuple); latLng = L.latLng([12, 13, 0]); +latLng = new L.LatLng(12, 13); +latLng = new L.LatLng(12, 13, 0); +latLng = new L.LatLng(latLngLiteral); +latLng = new L.LatLng({lat: 12, lng: 13, alt: 0}); +latLng = new L.LatLng(latLngTuple); +latLng = new L.LatLng([12, 13, 0]); + const latLngBoundsLiteral: L.LatLngBoundsLiteral = [[12, 13], latLngTuple]; let latLngBounds: L.LatLngBounds; @@ -18,6 +25,10 @@ latLngBounds = L.latLngBounds(latLng, latLng); latLngBounds = L.latLngBounds(latLngLiteral, latLngLiteral); latLngBounds = L.latLngBounds(latLngTuple, latLngTuple); +latLngBounds = new L.LatLngBounds(latLng, latLng); +latLngBounds = new L.LatLngBounds(latLngLiteral, latLngLiteral); +latLngBounds = new L.LatLngBounds(latLngTuple, latLngTuple); + const pointTuple: L.PointTuple = [0, 0]; let point: L.Point; @@ -26,6 +37,11 @@ point = L.point(12, 13, true); point = L.point(pointTuple); point = L.point({x: 12, y: 13}); +point = new L.Point(12, 13); +point = new L.Point(12, 13, true); +point = new L.Point(pointTuple); +point = new L.Point({x: 12, y: 13}); + let distance: number; point.distanceTo(point); point.distanceTo(pointTuple); @@ -44,7 +60,12 @@ bounds = L.bounds(pointTuple, pointTuple); bounds = L.bounds([point, point]); bounds = L.bounds(boundsLiteral); -let points: Array; +bounds = new L.Bounds(point, point); +bounds = new L.Bounds(pointTuple, pointTuple); +bounds = new L.Bounds([point, point]); +bounds = new L.Bounds(boundsLiteral); + +let points: L.Point[]; points = L.LineUtil.simplify([point, point], 1); points = L.LineUtil.simplify([pointTuple, pointTuple], 2); @@ -120,9 +141,9 @@ let layer: L.Layer; const htmlElement = document.getElementById('foo'); -let popupOptions: L.PopupOptions = {}; +const popupOptions: L.PopupOptions = {}; -let tooltipOptions: L.TooltipOptions = {}; +const tooltipOptions: L.TooltipOptions = {}; let zoomPanOptions: L.ZoomPanOptions = {}; zoomPanOptions = { @@ -132,17 +153,21 @@ zoomPanOptions = { noMoveStart: true }; -let zoomOptions: L.ZoomOptions = {}; +const zoomOptions: L.ZoomOptions = {}; -let panOptions: L.PanOptions = {}; +const panOptions: L.PanOptions = {}; -let fitBoundsOptions: L.FitBoundsOptions = {}; +const fitBoundsOptions: L.FitBoundsOptions = {}; let map = L.map('foo'); map = L.map('foo', mapOptions); map = L.map(htmlElement); map = L.map(htmlElement, mapOptions); +map = new L.Map('foo', mapOptions); +map = new L.Map(htmlElement); +map = new L.Map(htmlElement, mapOptions); + let doesItHaveLayer: boolean; doesItHaveLayer = map.hasLayer(L.tileLayer('')); @@ -150,7 +175,7 @@ doesItHaveLayer = map.hasLayer(L.tileLayer('')); let html: HTMLElement; html = map.createPane('foo'); -html = map.createPane('foo', htmlElement) +html = map.createPane('foo', htmlElement); html = map.getPane('foo'); html = map.getPane(htmlElement); html = map.getContainer(); @@ -220,7 +245,7 @@ tileLayerOptions.subdomains = ['a', 'b']; tileLayerOptions.tileSize = 256; tileLayerOptions.tileSize = point; -//tileLayerOptions.tileSize = pointTuple; investigate if this is valid +// tileLayerOptions.tileSize = pointTuple; investigate if this is valid tileLayerOptions.bounds = latLngBounds; tileLayerOptions.bounds = latLngBoundsLiteral; @@ -230,17 +255,21 @@ tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'); tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayerOptions); tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}&{bar}&{abc}', {foo: 'bar', bar: (data: any) => 'foo', abc: () => ''}); -let eventHandler = () => {}; -let domEvent: Event = {} as Event; +tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'); +tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayerOptions); +tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}&{bar}&{abc}', {foo: 'bar', bar: (data: any) => 'foo', abc: () => ''}); + +const eventHandler = () => {}; +const domEvent: Event = {} as Event; L.DomEvent .on(htmlElement, 'click', eventHandler) .addListener(htmlElement, 'click', eventHandler) .off(htmlElement, 'click', eventHandler) .removeListener(htmlElement, 'click', eventHandler) - .on(htmlElement, {'click': eventHandler}) - .addListener(htmlElement, {'click': eventHandler}) - .off(htmlElement, {'click': eventHandler}, eventHandler) - .removeListener(htmlElement, {'click': eventHandler}, eventHandler) + .on(htmlElement, {click: eventHandler}) + .addListener(htmlElement, {click: eventHandler}) + .off(htmlElement, {click: eventHandler}, eventHandler) + .removeListener(htmlElement, {click: eventHandler}, eventHandler) .stopPropagation(domEvent) .disableScrollPropagation(htmlElement) .disableClickPropagation(htmlElement) @@ -352,8 +381,8 @@ map = map .whenReady(() => {}) .whenReady(() => {}, {}); -let elementToDrag = document.createElement('div'); -let draggable = new L.Draggable(elementToDrag); +const elementToDrag = document.createElement('div'); +const draggable = new L.Draggable(elementToDrag); draggable.enable(); draggable.disable(); draggable.on('drag', () => {}); @@ -367,7 +396,7 @@ latLng = L.GeoJSON.coordsToLatLng(threeCoords); threeCoords = L.GeoJSON.latLngToCoords(latLng); let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; -let nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); +const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); nestedTwoCoords = L.GeoJSON.latLngsToCoords(nestedLatLngs, 1); class MyMarker extends L.Marker { @@ -375,24 +404,31 @@ class MyMarker extends L.Marker { super([12, 13]); } } + class MyLayer extends L.Layer { constructor() { super(); } } + class MyIcon extends L.Icon { constructor() { super({iconUrl: 'icon.png'}); } } + class MyDivIcon extends L.DivIcon { constructor() { super(); } } -let myControlClass = L.Control.extend({}); -let myControl = new myControlClass(); +const divIcon = L.divIcon({html: ''}); +let defaultIcon = new L.Icon.Default(); +defaultIcon = new L.Icon.Default({imagePath: 'apath'}); + +const myControlClass = L.Control.extend({}); +const myControl = new myControlClass(); L.Control.include({}); L.Control.mergeOptions({}); @@ -405,3 +441,28 @@ export class MyNewControl extends L.Control { }); } } + +L.marker([1, 2], { + icon: L.icon({ + iconUrl: 'my-icon.png' + }) +}).bindPopup('

Hi

'); + +L.Util.extend({}); +L.Util.create({}); +L.Util.bind(() => {}, {}); +L.Util.stamp({}); +L.Util.throttle(() => {}, 123, {}); +L.Util.wrapNum(123, []); +L.Util.falseFn(); +L.Util.formatNum(123); +L.Util.trim('word '); +L.Util.splitWords('word word'); +L.Util.setOptions({}, {}); +L.Util.getParamString({}); +L.Util.template('template', {}); +L.Util.isArray({}); +L.Util.indexOf([], {}); +L.Util.requestAnimFrame(() => {}); +L.Util.cancelAnimFrame(1); +L.Util.emptyImageUrl; diff --git a/leaflet/tslint.json b/leaflet/tslint.json new file mode 100644 index 0000000000..0b14fdec0d --- /dev/null +++ b/leaflet/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/libpq/index.d.ts b/libpq/index.d.ts index df2135046a..1e9e38dd5c 100644 --- a/libpq/index.d.ts +++ b/libpq/index.d.ts @@ -307,11 +307,11 @@ declare class Libpq extends EventEmitter { * (sync) Sends a named statement to the server to be prepared for later execution. blocks * until a result from the prepare operation is received. * - * @param {string} [statementName=""] a required string of name of the statement to prepare. - * @param {string} [commandText=""] a required string of the query. - * @param {number} [nParams=0] a count of the number of parameters in the commandText. + * @param {string} statementName a required string of name of the statement to prepare. + * @param {string} commandText a required string of the query. + * @param {number} nParams a count of the number of parameters in the commandText. */ - prepare(statementName?: string, commandText?: string, nParams?: number): void; + prepare(statementName: string, commandText: string, nParams: number): void; /** * Retrieves detailed error information from the current result object. Very similar to @@ -363,12 +363,12 @@ declare class Libpq extends EventEmitter { /** * (async) Sends a request to the backend to prepare a named statement with the given name. * - * @param {string} [statementName=""] a required string of name of the statement to prepare. - * @param {string} [commandText=""] a required string of the query. - * @param {number} [nParams=0] a count of the number of parameters in the commandText. + * @param {string} statementName a required string of name of the statement to prepare. + * @param {string} commandText a required string of the query. + * @param {number} nParams a count of the number of parameters in the commandText. * @returns {boolean} true if the command was sent succesfully or false if it failed to send. */ - sendPrepare(statementName?: string, commandText?: string, nParams?: number): boolean; + sendPrepare(statementName: string, commandText: string, nParams: number): boolean; /** * (async) Sends a request to execute a previously prepared statement. @@ -421,8 +421,10 @@ declare class Libpq extends EventEmitter { * and PQflush for async writing. * * @param {Function} callback + * + * @returns {Libpq} */ - writable(callback: () => void): void; + writable(callback: () => void): this; } export = Libpq; diff --git a/libpq/libpq-tests.ts b/libpq/libpq-tests.ts index dda341a4bb..8a9aced3c3 100644 --- a/libpq/libpq-tests.ts +++ b/libpq/libpq-tests.ts @@ -5,20 +5,21 @@ import {Buffer} from 'buffer'; import * as assert from 'assert'; import * as async from 'async'; import * as PQ from 'libpq'; -import * as _ from 'lodash'; + +declare const _: { times(n: number, f: () => T): T[] }; declare const ok: Function; const createTable = (pq: PQ) => { pq.exec('CREATE TEMP TABLE test_data(name text, age int)'); console.log(pq.resultErrorMessage()); - pq.exec("INSERT INTO test_data(name, age) VALUES ('brian', 32), ('aaron', 30), ('', null);") + pq.exec("INSERT INTO test_data(name, age) VALUES ('brian', 32), ('aaron', 30), ('', null);"); }; const blink = (n: number, cb: Function) => { const connections: PQ[] = []; for (let i = 0; i < 30; i++) { - connections.push(new PQ()) + connections.push(new PQ()); } const connect = (con: PQ, cb: (err?: Error) => void) => { con.connect(cb); @@ -28,7 +29,7 @@ const blink = (n: number, cb: Function) => { con.finish(); }); cb(); - })) + })); }; const queryText = "SELECT * FROM generate_series(1, 1000)"; @@ -54,7 +55,7 @@ const query = (pq: PQ, cb: Function) => { return readError('Only one result at a time is accepted'); } cleanup(); - return cb(null, []) + return cb(null, []); }; const sent = pq.sendQuery(queryText); @@ -126,7 +127,7 @@ const consume = (pq: PQ, cb: Function) => { }; describe('async simple query', () => { - let pq: PQ; + const pq: PQ = null as any; it('dispatches simple query', (done: Function) => { assert(pq.setNonBlocking(true)); @@ -156,7 +157,7 @@ describe('async simple query', () => { assert.strictEqual(pq.ntuples(), 1); assert.equal(pq.getvalue(0, 0), 'Brian'); done(); - }) + }); }); it('dispatches named query', (done: Function) => { @@ -167,30 +168,30 @@ describe('async simple query', () => { consume(pq, () => { assert.ifError(pq.errorMessage()); - //first time there should be a result + // first time there should be a result assert(pq.getResult()); - //call 'getResult' until it returns false indicating - //there is no more input to consume + // call 'getResult' until it returns false indicating + // there is no more input to consume assert.strictEqual(pq.getResult(), false); - //since we only prepared a statement there should be - //0 tuples in the result + // since we only prepared a statement there should be + // 0 tuples in the result assert.equal(pq.ntuples(), 0); - //now execute the previously prepared statement + // now execute the previously prepared statement const success = pq.sendQueryPrepared(statementName, ['Brian']); assert(success, pq.errorMessage()); assert.strictEqual(pq.flush(), 0, 'Should have flushed parameters'); consume(pq, () => { assert.ifError(pq.errorMessage()); - //consume the result of the query execution + // consume the result of the query execution assert(pq.getResult()); assert.equal(pq.ntuples(), 1); assert.equal(pq.getvalue(0, 0), 'Brian'); - //call 'getResult' again to ensure we're finished + // call 'getResult' again to ensure we're finished assert.strictEqual(pq.getResult(), false); done(); }); @@ -395,7 +396,7 @@ describe('error info', () => { assert.equal(err.dataTypeName, undefined); assert.equal(err.constraintName, undefined); assert.equal(err.sourceFile, "parse_target.c"); - assert(parseInt(err.sourceLine)); + assert(parseInt(err.sourceLine, 10)); assert.equal(err.sourceFunction, "transformAssignedExpr"); }); }); @@ -449,8 +450,8 @@ describe('connecting', () => { describe('many connections', () => { it('works', (done) => { - async.timesSeries(10, blink, done) - }) + async.timesSeries(10, blink, done); + }); }); describe('connectSync', () => { @@ -477,7 +478,7 @@ describe('connect async', () => { assert.ifError(err); count++; pq.startReader(); - if (count == total) { + if (count === total) { cb(); } }); @@ -497,7 +498,7 @@ describe('multiple queries', () => { const pq = new PQ(); before((done) => { - pq.connect(done) + pq.connect(done); }); it('first query works', (done) => { diff --git a/libpq/tslint.json b/libpq/tslint.json index 377cc837d4..f05741c59b 100644 --- a/libpq/tslint.json +++ b/libpq/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts index 37f7820888..0efb62c9ce 100644 --- a/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts +++ b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts @@ -26,30 +26,30 @@ declare var cordovaSQLiteDriver: LocalForageDriver; var newValue: string = value; }); - cordovaSQLiteDriver.keys((err: any, keys: Array) => { + cordovaSQLiteDriver.keys((err: any, keys: string[]) => { var newError: any = err; - var newArray: Array = keys; + var newArray: string[] = keys; }); - cordovaSQLiteDriver.getItem("key",(err: any, str: string) => { + cordovaSQLiteDriver.getItem("key", (err: any, str: string) => { var newError: any = err; - var newStr: string = str + var newStr: string = str; }); cordovaSQLiteDriver.setItem("key", "value", (err: any, str: string) => { var newError: any = err; - var newStr: string = str + var newStr: string = str; }); cordovaSQLiteDriver.setItem("key", "value", (str: string) => { var newStr: string = str; }); - cordovaSQLiteDriver.removeItem("key",(err: any) => { + cordovaSQLiteDriver.removeItem("key", (err: any) => { var newError: any = err; }); cordovaSQLiteDriver.removeItem("key", (err: any) => { var newError: any = err; }); -} \ No newline at end of file +}; \ No newline at end of file diff --git a/localforage-cordovasqlitedriver/tslint.json b/localforage-cordovasqlitedriver/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/localforage-cordovasqlitedriver/tslint.json +++ b/localforage-cordovasqlitedriver/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash-decorators/index.d.ts b/lodash-decorators/index.d.ts index 0e0b8d9e3c..eb05886150 100644 --- a/lodash-decorators/index.d.ts +++ b/lodash-decorators/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/steelsojka/lodash-decorators // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/lodash-es/index.d.ts b/lodash-es/index.d.ts index 71f98587ff..e344736795 100644 --- a/lodash-es/index.d.ts +++ b/lodash-es/index.d.ts @@ -2,3 +2,288 @@ // Project: http://lodash.com/ // Definitions by: Stephen Lautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export { default as add } from './add'; +export { default as after } from './after'; +export { default as ary } from './ary'; +export { default as assign } from './assign'; +export { default as assignIn } from './assignIn'; +export { default as assignInWith } from './assignInWith'; +export { default as assignWith } from './assignWith'; +export { default as at } from './at'; +export { default as attempt } from './attempt'; +export { default as before } from './before'; +export { default as bind } from './bind'; +export { default as bindAll } from './bindAll'; +export { default as bindKey } from './bindKey'; +export { default as camelCase } from './camelCase'; +export { default as capitalize } from './capitalize'; +export { default as castArray } from './castArray'; +export { default as ceil } from './ceil'; +export { default as chain } from './chain'; +export { default as chunk } from './chunk'; +export { default as clamp } from './clamp'; +export { default as clone } from './clone'; +export { default as cloneDeep } from './cloneDeep'; +export { default as cloneDeepWith } from './cloneDeepWith'; +export { default as cloneWith } from './cloneWith'; +export { default as compact } from './compact'; +export { default as concat } from './concat'; +export { default as constant } from './constant'; +export { default as countBy } from './countBy'; +export { default as create } from './create'; +export { default as curry } from './curry'; +export { default as curryRight } from './curryRight'; +export { default as debounce } from './debounce'; +export { default as deburr } from './deburr'; +export { default as defaults } from './defaults'; +export { default as defaultsDeep } from './defaultsDeep'; +export { default as defer } from './defer'; +export { default as delay } from './delay'; +export { default as difference } from './difference'; +export { default as differenceBy } from './differenceBy'; +export { default as differenceWith } from './differenceWith'; +export { default as drop } from './drop'; +export { default as dropRight } from './dropRight'; +export { default as dropRightWhile } from './dropRightWhile'; +export { default as dropWhile } from './dropWhile'; +export { default as each } from './each'; +export { default as eachRight } from './eachRight'; +export { default as endsWith } from './endsWith'; +export { default as eq } from './eq'; +export { default as escape } from './escape'; +export { default as escapeRegExp } from './escapeRegExp'; +export { default as every } from './every'; +export { default as extend } from './extend'; +export { default as extendWith } from './extendWith'; +export { default as fill } from './fill'; +export { default as filter } from './filter'; +export { default as find } from './find'; +export { default as findIndex } from './findIndex'; +export { default as findKey } from './findKey'; +export { default as findLast } from './findLast'; +export { default as findLastIndex } from './findLastIndex'; +export { default as findLastKey } from './findLastKey'; +export { default as first } from './first'; +export { default as flatMap } from './flatMap'; +export { default as flatten } from './flatten'; +export { default as flattenDeep } from './flattenDeep'; +export { default as flattenDepth } from './flattenDepth'; +export { default as flip } from './flip'; +export { default as floor } from './floor'; +export { default as flow } from './flow'; +export { default as flowRight } from './flowRight'; +export { default as forEach } from './forEach'; +export { default as forEachRight } from './forEachRight'; +export { default as forIn } from './forIn'; +export { default as forInRight } from './forInRight'; +export { default as forOwn } from './forOwn'; +export { default as forOwnRight } from './forOwnRight'; +export { default as fromPairs } from './fromPairs'; +export { default as functions } from './functions'; +export { default as functionsIn } from './functionsIn'; +export { default as get } from './get'; +export { default as groupBy } from './groupBy'; +export { default as gt } from './gt'; +export { default as gte } from './gte'; +export { default as has } from './has'; +export { default as hasIn } from './hasIn'; +export { default as head } from './head'; +export { default as identity } from './identity'; +export { default as inRange } from './inRange'; +export { default as includes } from './includes'; +export { default as indexOf } from './indexOf'; +export { default as initial } from './initial'; +export { default as intersection } from './intersection'; +export { default as intersectionBy } from './intersectionBy'; +export { default as intersectionWith } from './intersectionWith'; +export { default as invert } from './invert'; +export { default as invertBy } from './invertBy'; +export { default as invoke } from './invoke'; +export { default as invokeMap } from './invokeMap'; +export { default as isArguments } from './isArguments'; +export { default as isArray } from './isArray'; +export { default as isArrayBuffer } from './isArrayBuffer'; +export { default as isArrayLike } from './isArrayLike'; +export { default as isArrayLikeObject } from './isArrayLikeObject'; +export { default as isBoolean } from './isBoolean'; +export { default as isBuffer } from './isBuffer'; +export { default as isDate } from './isDate'; +export { default as isElement } from './isElement'; +export { default as isEmpty } from './isEmpty'; +export { default as isEqual } from './isEqual'; +export { default as isEqualWith } from './isEqualWith'; +export { default as isError } from './isError'; +export { default as isFinite } from './isFinite'; +export { default as isFunction } from './isFunction'; +export { default as isInteger } from './isInteger'; +export { default as isLength } from './isLength'; +export { default as isMap } from './isMap'; +export { default as isMatch } from './isMatch'; +export { default as isMatchWith } from './isMatchWith'; +export { default as isNaN } from './isNaN'; +export { default as isNative } from './isNative'; +export { default as isNil } from './isNil'; +export { default as isNull } from './isNull'; +export { default as isNumber } from './isNumber'; +export { default as isObject } from './isObject'; +export { default as isObjectLike } from './isObjectLike'; +export { default as isPlainObject } from './isPlainObject'; +export { default as isRegExp } from './isRegExp'; +export { default as isSafeInteger } from './isSafeInteger'; +export { default as isSet } from './isSet'; +export { default as isString } from './isString'; +export { default as isSymbol } from './isSymbol'; +export { default as isTypedArray } from './isTypedArray'; +export { default as isUndefined } from './isUndefined'; +export { default as isWeakMap } from './isWeakMap'; +export { default as isWeakSet } from './isWeakSet'; +export { default as iteratee } from './iteratee'; +export { default as join } from './join'; +export { default as kebabCase } from './kebabCase'; +export { default as keyBy } from './keyBy'; +export { default as keys } from './keys'; +export { default as keysIn } from './keysIn'; +export { default as last } from './last'; +export { default as lastIndexOf } from './lastIndexOf'; +export { default as lowerCase } from './lowerCase'; +export { default as lowerFirst } from './lowerFirst'; +export { default as lt } from './lt'; +export { default as lte } from './lte'; +export { default as map } from './map'; +export { default as mapKeys } from './mapKeys'; +export { default as mapValues } from './mapValues'; +export { default as matches } from './matches'; +export { default as matchesProperty } from './matchesProperty'; +export { default as max } from './max'; +export { default as maxBy } from './maxBy'; +export { default as mean } from './mean'; +export { default as meanBy } from './meanBy'; +export { default as memoize } from './memoize'; +export { default as merge } from './merge'; +export { default as mergeWith } from './mergeWith'; +export { default as method } from './method'; +export { default as methodOf } from './methodOf'; +export { default as min } from './min'; +export { default as minBy } from './minBy'; +export { default as mixin } from './mixin'; +export { default as negate } from './negate'; +export { default as noop } from './noop'; +export { default as now } from './now'; +export { default as nthArg } from './nthArg'; +export { default as omit } from './omit'; +export { default as omitBy } from './omitBy'; +export { default as once } from './once'; +export { default as orderBy } from './orderBy'; +export { default as over } from './over'; +export { default as overArgs } from './overArgs'; +export { default as overEvery } from './overEvery'; +export { default as overSome } from './overSome'; +export { default as pad } from './pad'; +export { default as padEnd } from './padEnd'; +export { default as padStart } from './padStart'; +export { default as parseInt } from './parseInt'; +export { default as partial } from './partial'; +export { default as partialRight } from './partialRight'; +export { default as partition } from './partition'; +export { default as pick } from './pick'; +export { default as pickBy } from './pickBy'; +export { default as property } from './property'; +export { default as propertyOf } from './propertyOf'; +export { default as pull } from './pull'; +export { default as pullAll } from './pullAll'; +export { default as pullAllBy } from './pullAllBy'; +export { default as pullAt } from './pullAt'; +export { default as random } from './random'; +export { default as range } from './range'; +export { default as rangeRight } from './rangeRight'; +export { default as rearg } from './rearg'; +export { default as reduce } from './reduce'; +export { default as reduceRight } from './reduceRight'; +export { default as reject } from './reject'; +export { default as remove } from './remove'; +export { default as repeat } from './repeat'; +export { default as replace } from './replace'; +export { default as rest } from './rest'; +export { default as result } from './result'; +export { default as reverse } from './reverse'; +export { default as round } from './round'; +export { default as sample } from './sample'; +export { default as sampleSize } from './sampleSize'; +export { default as set } from './set'; +export { default as setWith } from './setWith'; +export { default as shuffle } from './shuffle'; +export { default as size } from './size'; +export { default as slice } from './slice'; +export { default as snakeCase } from './snakeCase'; +export { default as some } from './some'; +export { default as sortBy } from './sortBy'; +export { default as sortedIndex } from './sortedIndex'; +export { default as sortedIndexBy } from './sortedIndexBy'; +export { default as sortedIndexOf } from './sortedIndexOf'; +export { default as sortedLastIndex } from './sortedLastIndex'; +export { default as sortedLastIndexBy } from './sortedLastIndexBy'; +export { default as sortedLastIndexOf } from './sortedLastIndexOf'; +export { default as sortedUniq } from './sortedUniq'; +export { default as sortedUniqBy } from './sortedUniqBy'; +export { default as split } from './split'; +export { default as spread } from './spread'; +export { default as startCase } from './startCase'; +export { default as startsWith } from './startsWith'; +export { default as subtract } from './subtract'; +export { default as sum } from './sum'; +export { default as sumBy } from './sumBy'; +export { default as tail } from './tail'; +export { default as take } from './take'; +export { default as takeRight } from './takeRight'; +export { default as takeRightWhile } from './takeRightWhile'; +export { default as takeWhile } from './takeWhile'; +export { default as tap } from './tap'; +export { default as template } from './template'; +export { default as throttle } from './throttle'; +export { default as thru } from './thru'; +export { default as times } from './times'; +export { default as toArray } from './toArray'; +export { default as toInteger } from './toInteger'; +export { default as toLength } from './toLength'; +export { default as toLower } from './toLower'; +export { default as toNumber } from './toNumber'; +export { default as toPairs } from './toPairs'; +export { default as toPairsIn } from './toPairsIn'; +export { default as toPath } from './toPath'; +export { default as toPlainObject } from './toPlainObject'; +export { default as toSafeInteger } from './toSafeInteger'; +export { default as toString } from './toString'; +export { default as toUpper } from './toUpper'; +export { default as transform } from './transform'; +export { default as trim } from './trim'; +export { default as trimEnd } from './trimEnd'; +export { default as trimStart } from './trimStart'; +export { default as truncate } from './truncate'; +export { default as unary } from './unary'; +export { default as unescape } from './unescape'; +export { default as union } from './union'; +export { default as unionBy } from './unionBy'; +export { default as unionWith } from './unionWith'; +export { default as uniq } from './uniq'; +export { default as uniqBy } from './uniqBy'; +export { default as uniqWith } from './uniqWith'; +export { default as uniqueId } from './uniqueId'; +export { default as unset } from './unset'; +export { default as unzip } from './unzip'; +export { default as unzipWith } from './unzipWith'; +export { default as update } from './update'; +export { default as upperCase } from './upperCase'; +export { default as upperFirst } from './upperFirst'; +export { default as values } from './values'; +export { default as valuesIn } from './valuesIn'; +export { default as without } from './without'; +export { default as words } from './words'; +export { default as wrap } from './wrap'; +export { default as xor } from './xor'; +export { default as xorBy } from './xorBy'; +export { default as xorWith } from './xorWith'; +export { default as zip } from './zip'; +export { default as zipObject } from './zipObject'; +export { default as zipWith } from './zipWith'; diff --git a/lodash-es/tslint.json b/lodash-es/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/lodash-es/tslint.json +++ b/lodash-es/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash-webpack-plugin/index.d.ts b/lodash-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..7b2c3ebe67 --- /dev/null +++ b/lodash-webpack-plugin/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for lodash-webpack-plugin 0.11 +// Project: https://github.com/lodash/lodash-webpack-plugin#readme +// Definitions by: Benjamin Lim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack'; + +export = LodashModuleReplacementPlugin; + +declare class LodashModuleReplacementPlugin extends Plugin { + constructor(options?: LodashModuleReplacementPlugin.Options); +} + +declare namespace LodashModuleReplacementPlugin { + interface Options { + caching?: boolean; + chaining?: boolean; + cloning?: boolean; + coercions?: boolean; + collections?: boolean; + currying?: boolean; + deburring?: boolean; + exotics?: boolean; + flattening?: boolean; + guards?: boolean; + memoizing?: boolean; + metadata?: boolean; + paths?: boolean; + placeholders?: boolean; + shorthands?: boolean; + unicode?: boolean; + } +} diff --git a/lodash-webpack-plugin/lodash-webpack-plugin-tests.ts b/lodash-webpack-plugin/lodash-webpack-plugin-tests.ts new file mode 100644 index 0000000000..d6483e3d03 --- /dev/null +++ b/lodash-webpack-plugin/lodash-webpack-plugin-tests.ts @@ -0,0 +1,31 @@ +import * as LodashModuleReplacementPlugin from 'lodash-webpack-plugin'; + +new LodashModuleReplacementPlugin(); + +const optionsArray: LodashModuleReplacementPlugin.Options[] = [ + { + collections: true, + paths: true, + }, + { + caching: true, + chaining: true, + cloning: true, + coercions: true, + collections: true, + currying: true, + deburring: true, + exotics: true, + flattening: true, + guards: true, + memoizing: true, + metadata: true, + paths: true, + placeholders: true, + shorthands: true, + unicode: true, + }, +]; + +const plugins: LodashModuleReplacementPlugin[] = optionsArray + .map(options => new LodashModuleReplacementPlugin(options)); diff --git a/lodash-webpack-plugin/tsconfig.json b/lodash-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..34ca502764 --- /dev/null +++ b/lodash-webpack-plugin/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", + "lodash-webpack-plugin-tests.ts" + ] +} diff --git a/lodash-webpack-plugin/tslint.json b/lodash-webpack-plugin/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/lodash-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/lodash.add/index.d.ts b/lodash.add/index.d.ts index 0a9aecd185..76c74086e3 100644 --- a/lodash.add/index.d.ts +++ b/lodash.add/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { add } from "lodash"; export = add; diff --git a/lodash.add/tslint.json b/lodash.add/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.add/tslint.json +++ b/lodash.add/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.after/index.d.ts b/lodash.after/index.d.ts index 52f5efd8e1..7ba8e38a1a 100644 --- a/lodash.after/index.d.ts +++ b/lodash.after/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { after } from "lodash"; export = after; diff --git a/lodash.after/tslint.json b/lodash.after/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.after/tslint.json +++ b/lodash.after/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ary/index.d.ts b/lodash.ary/index.d.ts index d78cd0c60e..fe902df0d0 100644 --- a/lodash.ary/index.d.ts +++ b/lodash.ary/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { ary } from "lodash"; export = ary; diff --git a/lodash.ary/tslint.json b/lodash.ary/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ary/tslint.json +++ b/lodash.ary/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assign/index.d.ts b/lodash.assign/index.d.ts index 0558933c3f..8da5d220bf 100644 --- a/lodash.assign/index.d.ts +++ b/lodash.assign/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { assign } from "lodash"; export = assign; diff --git a/lodash.assign/tslint.json b/lodash.assign/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assign/tslint.json +++ b/lodash.assign/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assignin/index.d.ts b/lodash.assignin/index.d.ts index 7e8740aea3..50551ff9d7 100644 --- a/lodash.assignin/index.d.ts +++ b/lodash.assignin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { assignIn } from "lodash"; export = assignIn; diff --git a/lodash.assignin/tslint.json b/lodash.assignin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assignin/tslint.json +++ b/lodash.assignin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assigninwith/index.d.ts b/lodash.assigninwith/index.d.ts index 1e1e3189c1..76f3d2dede 100644 --- a/lodash.assigninwith/index.d.ts +++ b/lodash.assigninwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { assignInWith } from "lodash"; export = assignInWith; diff --git a/lodash.assigninwith/tslint.json b/lodash.assigninwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assigninwith/tslint.json +++ b/lodash.assigninwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.assignwith/index.d.ts b/lodash.assignwith/index.d.ts index 02e395824d..a01c36eb29 100644 --- a/lodash.assignwith/index.d.ts +++ b/lodash.assignwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { assignWith } from "lodash"; export = assignWith; diff --git a/lodash.assignwith/tslint.json b/lodash.assignwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.assignwith/tslint.json +++ b/lodash.assignwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.at/index.d.ts b/lodash.at/index.d.ts index 7b237c170b..061d6040b8 100644 --- a/lodash.at/index.d.ts +++ b/lodash.at/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { at } from "lodash"; export = at; diff --git a/lodash.at/tslint.json b/lodash.at/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.at/tslint.json +++ b/lodash.at/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.attempt/index.d.ts b/lodash.attempt/index.d.ts index a93d1efb06..52874b4372 100644 --- a/lodash.attempt/index.d.ts +++ b/lodash.attempt/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { attempt } from "lodash"; export = attempt; diff --git a/lodash.attempt/tslint.json b/lodash.attempt/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.attempt/tslint.json +++ b/lodash.attempt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.before/index.d.ts b/lodash.before/index.d.ts index 50456ca93b..3c211206c0 100644 --- a/lodash.before/index.d.ts +++ b/lodash.before/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { before } from "lodash"; export = before; diff --git a/lodash.before/tslint.json b/lodash.before/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.before/tslint.json +++ b/lodash.before/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.bind/index.d.ts b/lodash.bind/index.d.ts index 2ace06a403..eda3868cae 100644 --- a/lodash.bind/index.d.ts +++ b/lodash.bind/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { bind } from "lodash"; export = bind; diff --git a/lodash.bind/tslint.json b/lodash.bind/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.bind/tslint.json +++ b/lodash.bind/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.bindall/index.d.ts b/lodash.bindall/index.d.ts index 7d5b08e79e..9a80f928cc 100644 --- a/lodash.bindall/index.d.ts +++ b/lodash.bindall/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { bindAll } from "lodash"; export = bindAll; diff --git a/lodash.bindall/tslint.json b/lodash.bindall/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.bindall/tslint.json +++ b/lodash.bindall/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.bindkey/index.d.ts b/lodash.bindkey/index.d.ts index 581f950cc1..a7ecab5dd1 100644 --- a/lodash.bindkey/index.d.ts +++ b/lodash.bindkey/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { bindKey } from "lodash"; export = bindKey; diff --git a/lodash.bindkey/tslint.json b/lodash.bindkey/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.bindkey/tslint.json +++ b/lodash.bindkey/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.camelcase/index.d.ts b/lodash.camelcase/index.d.ts index 7e330178df..b489f3f7a5 100644 --- a/lodash.camelcase/index.d.ts +++ b/lodash.camelcase/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { camelCase } from "lodash"; export = camelCase; diff --git a/lodash.camelcase/tslint.json b/lodash.camelcase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.camelcase/tslint.json +++ b/lodash.camelcase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.capitalize/index.d.ts b/lodash.capitalize/index.d.ts index 5cdfce9f64..06a3f72fd4 100644 --- a/lodash.capitalize/index.d.ts +++ b/lodash.capitalize/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { capitalize } from "lodash"; export = capitalize; diff --git a/lodash.capitalize/tslint.json b/lodash.capitalize/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.capitalize/tslint.json +++ b/lodash.capitalize/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.castarray/index.d.ts b/lodash.castarray/index.d.ts index 468ae08464..2d77145a0c 100644 --- a/lodash.castarray/index.d.ts +++ b/lodash.castarray/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { castArray } from "lodash"; export = castArray; diff --git a/lodash.castarray/tslint.json b/lodash.castarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.castarray/tslint.json +++ b/lodash.castarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ceil/index.d.ts b/lodash.ceil/index.d.ts index 382e7c6452..4d91e60e65 100644 --- a/lodash.ceil/index.d.ts +++ b/lodash.ceil/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { ceil } from "lodash"; export = ceil; diff --git a/lodash.ceil/tslint.json b/lodash.ceil/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ceil/tslint.json +++ b/lodash.ceil/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.chunk/index.d.ts b/lodash.chunk/index.d.ts index 9fd9a55c59..ffd11b71b2 100644 --- a/lodash.chunk/index.d.ts +++ b/lodash.chunk/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { chunk } from "lodash"; export = chunk; diff --git a/lodash.chunk/tslint.json b/lodash.chunk/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.chunk/tslint.json +++ b/lodash.chunk/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clamp/index.d.ts b/lodash.clamp/index.d.ts index 58372494cd..0a28f04829 100644 --- a/lodash.clamp/index.d.ts +++ b/lodash.clamp/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { clamp } from "lodash"; export = clamp; diff --git a/lodash.clamp/tslint.json b/lodash.clamp/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clamp/tslint.json +++ b/lodash.clamp/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clone/index.d.ts b/lodash.clone/index.d.ts index b9fa987104..a2d6e34490 100644 --- a/lodash.clone/index.d.ts +++ b/lodash.clone/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { clone } from "lodash"; export = clone; diff --git a/lodash.clone/tslint.json b/lodash.clone/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clone/tslint.json +++ b/lodash.clone/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clonedeep/index.d.ts b/lodash.clonedeep/index.d.ts index 4bd178bff0..5e9382e296 100644 --- a/lodash.clonedeep/index.d.ts +++ b/lodash.clonedeep/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { cloneDeep } from "lodash"; export = cloneDeep; diff --git a/lodash.clonedeep/tslint.json b/lodash.clonedeep/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clonedeep/tslint.json +++ b/lodash.clonedeep/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clonedeepwith/index.d.ts b/lodash.clonedeepwith/index.d.ts index e014c80686..80439cef54 100644 --- a/lodash.clonedeepwith/index.d.ts +++ b/lodash.clonedeepwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { cloneDeepWith } from "lodash"; export = cloneDeepWith; diff --git a/lodash.clonedeepwith/tslint.json b/lodash.clonedeepwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clonedeepwith/tslint.json +++ b/lodash.clonedeepwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.clonewith/index.d.ts b/lodash.clonewith/index.d.ts index cb29709538..bdaa109a3a 100644 --- a/lodash.clonewith/index.d.ts +++ b/lodash.clonewith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { cloneWith } from "lodash"; export = cloneWith; diff --git a/lodash.clonewith/tslint.json b/lodash.clonewith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.clonewith/tslint.json +++ b/lodash.clonewith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.compact/index.d.ts b/lodash.compact/index.d.ts index d6dc0b2fb8..9af681aeb4 100644 --- a/lodash.compact/index.d.ts +++ b/lodash.compact/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { compact } from "lodash"; export = compact; diff --git a/lodash.compact/tslint.json b/lodash.compact/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.compact/tslint.json +++ b/lodash.compact/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.concat/index.d.ts b/lodash.concat/index.d.ts index dd6f9bb6e2..692dfa5aab 100644 --- a/lodash.concat/index.d.ts +++ b/lodash.concat/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { concat } from "lodash"; export = concat; diff --git a/lodash.concat/tslint.json b/lodash.concat/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.concat/tslint.json +++ b/lodash.concat/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.constant/index.d.ts b/lodash.constant/index.d.ts index 92fc209518..1b941af3ad 100644 --- a/lodash.constant/index.d.ts +++ b/lodash.constant/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { constant } from "lodash"; export = constant; diff --git a/lodash.constant/tslint.json b/lodash.constant/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.constant/tslint.json +++ b/lodash.constant/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.countby/index.d.ts b/lodash.countby/index.d.ts index a3c6d24d93..03940a5e7d 100644 --- a/lodash.countby/index.d.ts +++ b/lodash.countby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { countBy } from "lodash"; export = countBy; diff --git a/lodash.countby/tslint.json b/lodash.countby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.countby/tslint.json +++ b/lodash.countby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.create/index.d.ts b/lodash.create/index.d.ts index 5ca15075eb..e9d553be1c 100644 --- a/lodash.create/index.d.ts +++ b/lodash.create/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { create } from "lodash"; export = create; diff --git a/lodash.create/tslint.json b/lodash.create/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.create/tslint.json +++ b/lodash.create/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.curry/index.d.ts b/lodash.curry/index.d.ts index 61f26316fd..a613fce91a 100644 --- a/lodash.curry/index.d.ts +++ b/lodash.curry/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { curry } from "lodash"; export = curry; diff --git a/lodash.curry/tslint.json b/lodash.curry/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.curry/tslint.json +++ b/lodash.curry/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.curryright/index.d.ts b/lodash.curryright/index.d.ts index caf7dfcfe3..b16fdd5147 100644 --- a/lodash.curryright/index.d.ts +++ b/lodash.curryright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { curryRight } from "lodash"; export = curryRight; diff --git a/lodash.curryright/tslint.json b/lodash.curryright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.curryright/tslint.json +++ b/lodash.curryright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.debounce/index.d.ts b/lodash.debounce/index.d.ts index 2bef22974b..4e4e3aec55 100644 --- a/lodash.debounce/index.d.ts +++ b/lodash.debounce/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { debounce } from "lodash"; export = debounce; diff --git a/lodash.debounce/tslint.json b/lodash.debounce/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.debounce/tslint.json +++ b/lodash.debounce/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.deburr/index.d.ts b/lodash.deburr/index.d.ts index 6f92fcbbd4..0caa30be24 100644 --- a/lodash.deburr/index.d.ts +++ b/lodash.deburr/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { deburr } from "lodash"; export = deburr; diff --git a/lodash.deburr/tslint.json b/lodash.deburr/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.deburr/tslint.json +++ b/lodash.deburr/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.defaults/index.d.ts b/lodash.defaults/index.d.ts index 15c8e57184..6c0bb1b47b 100644 --- a/lodash.defaults/index.d.ts +++ b/lodash.defaults/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { defaults } from "lodash"; export = defaults; diff --git a/lodash.defaults/tslint.json b/lodash.defaults/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.defaults/tslint.json +++ b/lodash.defaults/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.defaultsdeep/index.d.ts b/lodash.defaultsdeep/index.d.ts index 22cb0667a3..c552b805ff 100644 --- a/lodash.defaultsdeep/index.d.ts +++ b/lodash.defaultsdeep/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { defaultsDeep } from "lodash"; export = defaultsDeep; diff --git a/lodash.defaultsdeep/tslint.json b/lodash.defaultsdeep/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.defaultsdeep/tslint.json +++ b/lodash.defaultsdeep/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.defer/index.d.ts b/lodash.defer/index.d.ts index ad67ed0c82..6c35dd7513 100644 --- a/lodash.defer/index.d.ts +++ b/lodash.defer/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { defer } from "lodash"; export = defer; diff --git a/lodash.defer/tslint.json b/lodash.defer/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.defer/tslint.json +++ b/lodash.defer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.delay/index.d.ts b/lodash.delay/index.d.ts index b65bd46abe..bb4922c81c 100644 --- a/lodash.delay/index.d.ts +++ b/lodash.delay/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { delay } from "lodash"; export = delay; diff --git a/lodash.delay/tslint.json b/lodash.delay/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.delay/tslint.json +++ b/lodash.delay/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.difference/index.d.ts b/lodash.difference/index.d.ts index 38aa798be1..7ad8c6c414 100644 --- a/lodash.difference/index.d.ts +++ b/lodash.difference/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { difference } from "lodash"; export = difference; diff --git a/lodash.difference/tslint.json b/lodash.difference/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.difference/tslint.json +++ b/lodash.difference/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.differenceby/index.d.ts b/lodash.differenceby/index.d.ts index 2d0c4859f0..50dfcd6a9c 100644 --- a/lodash.differenceby/index.d.ts +++ b/lodash.differenceby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { differenceBy } from "lodash"; export = differenceBy; diff --git a/lodash.differenceby/tslint.json b/lodash.differenceby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.differenceby/tslint.json +++ b/lodash.differenceby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.differencewith/index.d.ts b/lodash.differencewith/index.d.ts index fff454ca64..9870768137 100644 --- a/lodash.differencewith/index.d.ts +++ b/lodash.differencewith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { differenceWith } from "lodash"; export = differenceWith; diff --git a/lodash.differencewith/tslint.json b/lodash.differencewith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.differencewith/tslint.json +++ b/lodash.differencewith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.drop/index.d.ts b/lodash.drop/index.d.ts index 0605e176ec..f702675717 100644 --- a/lodash.drop/index.d.ts +++ b/lodash.drop/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { drop } from "lodash"; export = drop; diff --git a/lodash.drop/tslint.json b/lodash.drop/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.drop/tslint.json +++ b/lodash.drop/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.dropright/index.d.ts b/lodash.dropright/index.d.ts index 1322022901..1385005315 100644 --- a/lodash.dropright/index.d.ts +++ b/lodash.dropright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { dropRight } from "lodash"; export = dropRight; diff --git a/lodash.dropright/tslint.json b/lodash.dropright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.dropright/tslint.json +++ b/lodash.dropright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.droprightwhile/index.d.ts b/lodash.droprightwhile/index.d.ts index b5fd1a75d2..02f5d13ac8 100644 --- a/lodash.droprightwhile/index.d.ts +++ b/lodash.droprightwhile/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { dropRightWhile } from "lodash"; export = dropRightWhile; diff --git a/lodash.droprightwhile/tslint.json b/lodash.droprightwhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.droprightwhile/tslint.json +++ b/lodash.droprightwhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.dropwhile/index.d.ts b/lodash.dropwhile/index.d.ts index e24e46bccc..270e0d0189 100644 --- a/lodash.dropwhile/index.d.ts +++ b/lodash.dropwhile/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { dropWhile } from "lodash"; export = dropWhile; diff --git a/lodash.dropwhile/tslint.json b/lodash.dropwhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.dropwhile/tslint.json +++ b/lodash.dropwhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.endswith/index.d.ts b/lodash.endswith/index.d.ts index 191301b21e..3a1c9b314e 100644 --- a/lodash.endswith/index.d.ts +++ b/lodash.endswith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { endsWith } from "lodash"; export = endsWith; diff --git a/lodash.endswith/tslint.json b/lodash.endswith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.endswith/tslint.json +++ b/lodash.endswith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.eq/index.d.ts b/lodash.eq/index.d.ts index 87e927aa6d..8af8729bb4 100644 --- a/lodash.eq/index.d.ts +++ b/lodash.eq/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { eq } from "lodash"; export = eq; diff --git a/lodash.eq/tslint.json b/lodash.eq/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.eq/tslint.json +++ b/lodash.eq/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.escape/index.d.ts b/lodash.escape/index.d.ts index 8e72963f22..a74f554830 100644 --- a/lodash.escape/index.d.ts +++ b/lodash.escape/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { escape } from "lodash"; export = escape; diff --git a/lodash.escape/tslint.json b/lodash.escape/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.escape/tslint.json +++ b/lodash.escape/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.escaperegexp/index.d.ts b/lodash.escaperegexp/index.d.ts index 19eb0c6807..b80f492f70 100644 --- a/lodash.escaperegexp/index.d.ts +++ b/lodash.escaperegexp/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { escapeRegExp } from "lodash"; export = escapeRegExp; diff --git a/lodash.escaperegexp/tslint.json b/lodash.escaperegexp/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.escaperegexp/tslint.json +++ b/lodash.escaperegexp/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.every/index.d.ts b/lodash.every/index.d.ts index a7ce29ad7a..84fd71115a 100644 --- a/lodash.every/index.d.ts +++ b/lodash.every/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { every } from "lodash"; export = every; diff --git a/lodash.every/tslint.json b/lodash.every/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.every/tslint.json +++ b/lodash.every/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.fill/index.d.ts b/lodash.fill/index.d.ts index 1c8c619422..c2b785fbe5 100644 --- a/lodash.fill/index.d.ts +++ b/lodash.fill/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { fill } from "lodash"; export = fill; diff --git a/lodash.fill/tslint.json b/lodash.fill/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.fill/tslint.json +++ b/lodash.fill/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.filter/index.d.ts b/lodash.filter/index.d.ts index 83dd5a1ddb..4960ebde70 100644 --- a/lodash.filter/index.d.ts +++ b/lodash.filter/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { filter } from "lodash"; export = filter; diff --git a/lodash.filter/tslint.json b/lodash.filter/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.filter/tslint.json +++ b/lodash.filter/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.find/index.d.ts b/lodash.find/index.d.ts index eda8769f54..f1d736f0c0 100644 --- a/lodash.find/index.d.ts +++ b/lodash.find/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { find } from "lodash"; export = find; diff --git a/lodash.find/tslint.json b/lodash.find/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.find/tslint.json +++ b/lodash.find/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findindex/index.d.ts b/lodash.findindex/index.d.ts index bfb5034785..bc2fee9d18 100644 --- a/lodash.findindex/index.d.ts +++ b/lodash.findindex/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { findIndex } from "lodash"; export = findIndex; diff --git a/lodash.findindex/tslint.json b/lodash.findindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findindex/tslint.json +++ b/lodash.findindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findkey/index.d.ts b/lodash.findkey/index.d.ts index bf5c2a357c..4bca193179 100644 --- a/lodash.findkey/index.d.ts +++ b/lodash.findkey/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { findKey } from "lodash"; export = findKey; diff --git a/lodash.findkey/tslint.json b/lodash.findkey/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findkey/tslint.json +++ b/lodash.findkey/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findlast/index.d.ts b/lodash.findlast/index.d.ts index ad5f1d00f9..7ec89440be 100644 --- a/lodash.findlast/index.d.ts +++ b/lodash.findlast/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { findLast } from "lodash"; export = findLast; diff --git a/lodash.findlast/tslint.json b/lodash.findlast/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findlast/tslint.json +++ b/lodash.findlast/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findlastindex/index.d.ts b/lodash.findlastindex/index.d.ts index 6e771c3842..37c0ba4567 100644 --- a/lodash.findlastindex/index.d.ts +++ b/lodash.findlastindex/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { findLastIndex } from "lodash"; export = findLastIndex; diff --git a/lodash.findlastindex/tslint.json b/lodash.findlastindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findlastindex/tslint.json +++ b/lodash.findlastindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.findlastkey/index.d.ts b/lodash.findlastkey/index.d.ts index ea09517b83..6e53f08733 100644 --- a/lodash.findlastkey/index.d.ts +++ b/lodash.findlastkey/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { findLastKey } from "lodash"; export = findLastKey; diff --git a/lodash.findlastkey/tslint.json b/lodash.findlastkey/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.findlastkey/tslint.json +++ b/lodash.findlastkey/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.first/index.d.ts b/lodash.first/index.d.ts index b1e1b84a54..21b7337178 100644 --- a/lodash.first/index.d.ts +++ b/lodash.first/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { first } from "lodash"; export = first; diff --git a/lodash.first/tslint.json b/lodash.first/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.first/tslint.json +++ b/lodash.first/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flatmap/index.d.ts b/lodash.flatmap/index.d.ts index 26d291b7bc..075c3eba57 100644 --- a/lodash.flatmap/index.d.ts +++ b/lodash.flatmap/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { flatMap } from "lodash"; export = flatMap; diff --git a/lodash.flatmap/tslint.json b/lodash.flatmap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flatmap/tslint.json +++ b/lodash.flatmap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flatten/index.d.ts b/lodash.flatten/index.d.ts index 4c3d68eb5e..b0247fd668 100644 --- a/lodash.flatten/index.d.ts +++ b/lodash.flatten/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { flatten } from "lodash"; export = flatten; diff --git a/lodash.flatten/tslint.json b/lodash.flatten/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flatten/tslint.json +++ b/lodash.flatten/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flattendeep/index.d.ts b/lodash.flattendeep/index.d.ts index 4e6b573eae..b596ff5fad 100644 --- a/lodash.flattendeep/index.d.ts +++ b/lodash.flattendeep/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { flattenDeep } from "lodash"; export = flattenDeep; diff --git a/lodash.flattendeep/tslint.json b/lodash.flattendeep/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flattendeep/tslint.json +++ b/lodash.flattendeep/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flattendepth/index.d.ts b/lodash.flattendepth/index.d.ts index 186641d1bc..d8df8b242b 100644 --- a/lodash.flattendepth/index.d.ts +++ b/lodash.flattendepth/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { flattenDepth } from "lodash"; export = flattenDepth; diff --git a/lodash.flattendepth/tslint.json b/lodash.flattendepth/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flattendepth/tslint.json +++ b/lodash.flattendepth/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flip/index.d.ts b/lodash.flip/index.d.ts index d4a69991ab..a87354fe7d 100644 --- a/lodash.flip/index.d.ts +++ b/lodash.flip/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { flip } from "lodash"; export = flip; diff --git a/lodash.flip/tslint.json b/lodash.flip/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flip/tslint.json +++ b/lodash.flip/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.floor/index.d.ts b/lodash.floor/index.d.ts index 7e43e4335b..ca831b6e0f 100644 --- a/lodash.floor/index.d.ts +++ b/lodash.floor/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { floor } from "lodash"; export = floor; diff --git a/lodash.floor/tslint.json b/lodash.floor/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.floor/tslint.json +++ b/lodash.floor/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flow/index.d.ts b/lodash.flow/index.d.ts index 36be0e704f..d2bc98d1ab 100644 --- a/lodash.flow/index.d.ts +++ b/lodash.flow/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { flow } from "lodash"; export = flow; diff --git a/lodash.flow/tslint.json b/lodash.flow/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flow/tslint.json +++ b/lodash.flow/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.flowright/index.d.ts b/lodash.flowright/index.d.ts index 95189e5684..e1275db957 100644 --- a/lodash.flowright/index.d.ts +++ b/lodash.flowright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { flowRight } from "lodash"; export = flowRight; diff --git a/lodash.flowright/tslint.json b/lodash.flowright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.flowright/tslint.json +++ b/lodash.flowright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.foreach/index.d.ts b/lodash.foreach/index.d.ts index d2fd5757b4..9aec8eaf2b 100644 --- a/lodash.foreach/index.d.ts +++ b/lodash.foreach/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { forEach } from "lodash"; export = forEach; diff --git a/lodash.foreach/tslint.json b/lodash.foreach/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.foreach/tslint.json +++ b/lodash.foreach/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.foreachright/index.d.ts b/lodash.foreachright/index.d.ts index cdd20d5fec..147f43d771 100644 --- a/lodash.foreachright/index.d.ts +++ b/lodash.foreachright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { forEachRight } from "lodash"; export = forEachRight; diff --git a/lodash.foreachright/tslint.json b/lodash.foreachright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.foreachright/tslint.json +++ b/lodash.foreachright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forin/index.d.ts b/lodash.forin/index.d.ts index e95e69f8b4..af03a8a4e1 100644 --- a/lodash.forin/index.d.ts +++ b/lodash.forin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { forIn } from "lodash"; export = forIn; diff --git a/lodash.forin/tslint.json b/lodash.forin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forin/tslint.json +++ b/lodash.forin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forinright/index.d.ts b/lodash.forinright/index.d.ts index 160f182cf9..c79a18f746 100644 --- a/lodash.forinright/index.d.ts +++ b/lodash.forinright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { forInRight } from "lodash"; export = forInRight; diff --git a/lodash.forinright/tslint.json b/lodash.forinright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forinright/tslint.json +++ b/lodash.forinright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forown/index.d.ts b/lodash.forown/index.d.ts index 20ae037f37..32d2ac758d 100644 --- a/lodash.forown/index.d.ts +++ b/lodash.forown/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { forOwn } from "lodash"; export = forOwn; diff --git a/lodash.forown/tslint.json b/lodash.forown/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forown/tslint.json +++ b/lodash.forown/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.forownright/index.d.ts b/lodash.forownright/index.d.ts index 0736346722..1a2ff70788 100644 --- a/lodash.forownright/index.d.ts +++ b/lodash.forownright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { forOwnRight } from "lodash"; export = forOwnRight; diff --git a/lodash.forownright/tslint.json b/lodash.forownright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.forownright/tslint.json +++ b/lodash.forownright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.frompairs/index.d.ts b/lodash.frompairs/index.d.ts index db158444d5..b74020f99f 100644 --- a/lodash.frompairs/index.d.ts +++ b/lodash.frompairs/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { fromPairs } from "lodash"; export = fromPairs; diff --git a/lodash.frompairs/tslint.json b/lodash.frompairs/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.frompairs/tslint.json +++ b/lodash.frompairs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.functions/index.d.ts b/lodash.functions/index.d.ts index 03ca7febbb..865f3c0c1e 100644 --- a/lodash.functions/index.d.ts +++ b/lodash.functions/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { functions } from "lodash"; export = functions; diff --git a/lodash.functions/tslint.json b/lodash.functions/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.functions/tslint.json +++ b/lodash.functions/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.functionsin/index.d.ts b/lodash.functionsin/index.d.ts index 93168e67a3..5bfc7a5ca2 100644 --- a/lodash.functionsin/index.d.ts +++ b/lodash.functionsin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { functionsIn } from "lodash"; export = functionsIn; diff --git a/lodash.functionsin/tslint.json b/lodash.functionsin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.functionsin/tslint.json +++ b/lodash.functionsin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.get/index.d.ts b/lodash.get/index.d.ts index 91e6b74e66..fd7d336a70 100644 --- a/lodash.get/index.d.ts +++ b/lodash.get/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { get } from "lodash"; export = get; diff --git a/lodash.get/tslint.json b/lodash.get/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.get/tslint.json +++ b/lodash.get/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.groupby/index.d.ts b/lodash.groupby/index.d.ts index 06156f9b00..c55d2e3db7 100644 --- a/lodash.groupby/index.d.ts +++ b/lodash.groupby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { groupBy } from "lodash"; export = groupBy; diff --git a/lodash.groupby/tslint.json b/lodash.groupby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.groupby/tslint.json +++ b/lodash.groupby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.gt/index.d.ts b/lodash.gt/index.d.ts index f541f408a8..cd5aa96019 100644 --- a/lodash.gt/index.d.ts +++ b/lodash.gt/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { gt } from "lodash"; export = gt; diff --git a/lodash.gt/tslint.json b/lodash.gt/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.gt/tslint.json +++ b/lodash.gt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.gte/index.d.ts b/lodash.gte/index.d.ts index 4041863b22..0e9eb62a7c 100644 --- a/lodash.gte/index.d.ts +++ b/lodash.gte/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { gte } from "lodash"; export = gte; diff --git a/lodash.gte/tslint.json b/lodash.gte/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.gte/tslint.json +++ b/lodash.gte/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.has/index.d.ts b/lodash.has/index.d.ts index aaf4c27353..28ee7cd4e9 100644 --- a/lodash.has/index.d.ts +++ b/lodash.has/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { has } from "lodash"; export = has; diff --git a/lodash.has/tslint.json b/lodash.has/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.has/tslint.json +++ b/lodash.has/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.hasin/index.d.ts b/lodash.hasin/index.d.ts index 53052f5cc3..09be59f7da 100644 --- a/lodash.hasin/index.d.ts +++ b/lodash.hasin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { hasIn } from "lodash"; export = hasIn; diff --git a/lodash.hasin/tslint.json b/lodash.hasin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.hasin/tslint.json +++ b/lodash.hasin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.head/index.d.ts b/lodash.head/index.d.ts index d2e3e06eac..0b3b6da94f 100644 --- a/lodash.head/index.d.ts +++ b/lodash.head/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { head } from "lodash"; export = head; diff --git a/lodash.head/tslint.json b/lodash.head/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.head/tslint.json +++ b/lodash.head/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.identity/index.d.ts b/lodash.identity/index.d.ts index 810313857d..0e683ed1c4 100644 --- a/lodash.identity/index.d.ts +++ b/lodash.identity/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { identity } from "lodash"; export = identity; diff --git a/lodash.identity/tslint.json b/lodash.identity/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.identity/tslint.json +++ b/lodash.identity/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.includes/index.d.ts b/lodash.includes/index.d.ts index dccbc5e3ee..ddb703d38d 100644 --- a/lodash.includes/index.d.ts +++ b/lodash.includes/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { includes } from "lodash"; export = includes; diff --git a/lodash.includes/tslint.json b/lodash.includes/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.includes/tslint.json +++ b/lodash.includes/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.indexof/index.d.ts b/lodash.indexof/index.d.ts index 0551b9acc6..180fde9e2f 100644 --- a/lodash.indexof/index.d.ts +++ b/lodash.indexof/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { indexOf } from "lodash"; export = indexOf; diff --git a/lodash.indexof/tslint.json b/lodash.indexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.indexof/tslint.json +++ b/lodash.indexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.initial/index.d.ts b/lodash.initial/index.d.ts index 303d425de1..40fec082f7 100644 --- a/lodash.initial/index.d.ts +++ b/lodash.initial/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { initial } from "lodash"; export = initial; diff --git a/lodash.initial/tslint.json b/lodash.initial/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.initial/tslint.json +++ b/lodash.initial/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.inrange/index.d.ts b/lodash.inrange/index.d.ts index b65ff730db..8140966ac2 100644 --- a/lodash.inrange/index.d.ts +++ b/lodash.inrange/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { inRange } from "lodash"; export = inRange; diff --git a/lodash.inrange/tslint.json b/lodash.inrange/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.inrange/tslint.json +++ b/lodash.inrange/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.intersection/index.d.ts b/lodash.intersection/index.d.ts index 8bc7dbde4f..149a324277 100644 --- a/lodash.intersection/index.d.ts +++ b/lodash.intersection/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { intersection } from "lodash"; export = intersection; diff --git a/lodash.intersection/tslint.json b/lodash.intersection/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.intersection/tslint.json +++ b/lodash.intersection/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.intersectionby/index.d.ts b/lodash.intersectionby/index.d.ts index 74ae5d4dfc..81c206df48 100644 --- a/lodash.intersectionby/index.d.ts +++ b/lodash.intersectionby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { intersectionBy } from "lodash"; export = intersectionBy; diff --git a/lodash.intersectionby/tslint.json b/lodash.intersectionby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.intersectionby/tslint.json +++ b/lodash.intersectionby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.intersectionwith/index.d.ts b/lodash.intersectionwith/index.d.ts index 73b816b192..e18b9d41ff 100644 --- a/lodash.intersectionwith/index.d.ts +++ b/lodash.intersectionwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { intersectionWith } from "lodash"; export = intersectionWith; diff --git a/lodash.intersectionwith/tslint.json b/lodash.intersectionwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.intersectionwith/tslint.json +++ b/lodash.intersectionwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invert/index.d.ts b/lodash.invert/index.d.ts index 99fdb04c76..25fe9ce360 100644 --- a/lodash.invert/index.d.ts +++ b/lodash.invert/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { invert } from "lodash"; export = invert; diff --git a/lodash.invert/tslint.json b/lodash.invert/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invert/tslint.json +++ b/lodash.invert/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invertby/index.d.ts b/lodash.invertby/index.d.ts index c3959934a2..63e5c70405 100644 --- a/lodash.invertby/index.d.ts +++ b/lodash.invertby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { invertBy } from "lodash"; export = invertBy; diff --git a/lodash.invertby/tslint.json b/lodash.invertby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invertby/tslint.json +++ b/lodash.invertby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invoke/index.d.ts b/lodash.invoke/index.d.ts index 7af1475a29..e16b07d462 100644 --- a/lodash.invoke/index.d.ts +++ b/lodash.invoke/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { invoke } from "lodash"; export = invoke; diff --git a/lodash.invoke/tslint.json b/lodash.invoke/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invoke/tslint.json +++ b/lodash.invoke/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.invokemap/index.d.ts b/lodash.invokemap/index.d.ts index 4995018391..1365a4f752 100644 --- a/lodash.invokemap/index.d.ts +++ b/lodash.invokemap/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { invokeMap } from "lodash"; export = invokeMap; diff --git a/lodash.invokemap/tslint.json b/lodash.invokemap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.invokemap/tslint.json +++ b/lodash.invokemap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarguments/index.d.ts b/lodash.isarguments/index.d.ts index f46218acd9..7eb30e26dd 100644 --- a/lodash.isarguments/index.d.ts +++ b/lodash.isarguments/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isArguments } from "lodash"; export = isArguments; diff --git a/lodash.isarguments/tslint.json b/lodash.isarguments/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarguments/tslint.json +++ b/lodash.isarguments/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarray/index.d.ts b/lodash.isarray/index.d.ts index a777294028..d4df88d8d7 100644 --- a/lodash.isarray/index.d.ts +++ b/lodash.isarray/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isArray } from "lodash"; export = isArray; diff --git a/lodash.isarray/tslint.json b/lodash.isarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarray/tslint.json +++ b/lodash.isarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarraybuffer/index.d.ts b/lodash.isarraybuffer/index.d.ts index 827727c372..bb65311721 100644 --- a/lodash.isarraybuffer/index.d.ts +++ b/lodash.isarraybuffer/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isArrayBuffer } from "lodash"; export = isArrayBuffer; diff --git a/lodash.isarraybuffer/tslint.json b/lodash.isarraybuffer/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarraybuffer/tslint.json +++ b/lodash.isarraybuffer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarraylike/index.d.ts b/lodash.isarraylike/index.d.ts index 44e0da10d2..e722669eb4 100644 --- a/lodash.isarraylike/index.d.ts +++ b/lodash.isarraylike/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isArrayLike } from "lodash"; export = isArrayLike; diff --git a/lodash.isarraylike/tslint.json b/lodash.isarraylike/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarraylike/tslint.json +++ b/lodash.isarraylike/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isarraylikeobject/index.d.ts b/lodash.isarraylikeobject/index.d.ts index e5a2a5d847..8d094d8261 100644 --- a/lodash.isarraylikeobject/index.d.ts +++ b/lodash.isarraylikeobject/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isArrayLikeObject } from "lodash"; export = isArrayLikeObject; diff --git a/lodash.isarraylikeobject/tslint.json b/lodash.isarraylikeobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isarraylikeobject/tslint.json +++ b/lodash.isarraylikeobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isboolean/index.d.ts b/lodash.isboolean/index.d.ts index 39ae1338ee..38bcb53406 100644 --- a/lodash.isboolean/index.d.ts +++ b/lodash.isboolean/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isBoolean } from "lodash"; export = isBoolean; diff --git a/lodash.isboolean/tslint.json b/lodash.isboolean/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isboolean/tslint.json +++ b/lodash.isboolean/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isbuffer/index.d.ts b/lodash.isbuffer/index.d.ts index 985ce28952..0c9d922967 100644 --- a/lodash.isbuffer/index.d.ts +++ b/lodash.isbuffer/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isBuffer } from "lodash"; export = isBuffer; diff --git a/lodash.isbuffer/tslint.json b/lodash.isbuffer/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isbuffer/tslint.json +++ b/lodash.isbuffer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isdate/index.d.ts b/lodash.isdate/index.d.ts index 0c59a7a05f..bc61921489 100644 --- a/lodash.isdate/index.d.ts +++ b/lodash.isdate/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isDate } from "lodash"; export = isDate; diff --git a/lodash.isdate/tslint.json b/lodash.isdate/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isdate/tslint.json +++ b/lodash.isdate/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.iselement/index.d.ts b/lodash.iselement/index.d.ts index d4538e9e40..e059b8b1f5 100644 --- a/lodash.iselement/index.d.ts +++ b/lodash.iselement/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isElement } from "lodash"; export = isElement; diff --git a/lodash.iselement/tslint.json b/lodash.iselement/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.iselement/tslint.json +++ b/lodash.iselement/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isempty/index.d.ts b/lodash.isempty/index.d.ts index dc550a45a3..bff4c499aa 100644 --- a/lodash.isempty/index.d.ts +++ b/lodash.isempty/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isEmpty } from "lodash"; export = isEmpty; diff --git a/lodash.isempty/tslint.json b/lodash.isempty/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isempty/tslint.json +++ b/lodash.isempty/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isequal/index.d.ts b/lodash.isequal/index.d.ts index b19d0c04d5..d06f5a2a2a 100644 --- a/lodash.isequal/index.d.ts +++ b/lodash.isequal/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for lodash.isEqual 4.4 +// Type definitions for lodash.isEqual 4.5 // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isEqual } from "lodash"; export = isEqual; diff --git a/lodash.isequal/tslint.json b/lodash.isequal/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isequal/tslint.json +++ b/lodash.isequal/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isequalwith/index.d.ts b/lodash.isequalwith/index.d.ts index 1298491bd4..250895312b 100644 --- a/lodash.isequalwith/index.d.ts +++ b/lodash.isequalwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isEqualWith } from "lodash"; export = isEqualWith; diff --git a/lodash.isequalwith/tslint.json b/lodash.isequalwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isequalwith/tslint.json +++ b/lodash.isequalwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.iserror/index.d.ts b/lodash.iserror/index.d.ts index d12d1b7cce..42a2bc0923 100644 --- a/lodash.iserror/index.d.ts +++ b/lodash.iserror/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isError } from "lodash"; export = isError; diff --git a/lodash.iserror/tslint.json b/lodash.iserror/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.iserror/tslint.json +++ b/lodash.iserror/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isfinite/index.d.ts b/lodash.isfinite/index.d.ts index 8cd096692c..02a28fa204 100644 --- a/lodash.isfinite/index.d.ts +++ b/lodash.isfinite/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isFinite } from "lodash"; export = isFinite; diff --git a/lodash.isfinite/tslint.json b/lodash.isfinite/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isfinite/tslint.json +++ b/lodash.isfinite/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isfunction/index.d.ts b/lodash.isfunction/index.d.ts index a2276e5633..3253939f6b 100644 --- a/lodash.isfunction/index.d.ts +++ b/lodash.isfunction/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isFunction } from "lodash"; export = isFunction; diff --git a/lodash.isfunction/tslint.json b/lodash.isfunction/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isfunction/tslint.json +++ b/lodash.isfunction/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isinteger/index.d.ts b/lodash.isinteger/index.d.ts index f2d78c2b1f..7d604a19b6 100644 --- a/lodash.isinteger/index.d.ts +++ b/lodash.isinteger/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isInteger } from "lodash"; export = isInteger; diff --git a/lodash.isinteger/tslint.json b/lodash.isinteger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isinteger/tslint.json +++ b/lodash.isinteger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.islength/index.d.ts b/lodash.islength/index.d.ts index abcc89acda..6ed54652e5 100644 --- a/lodash.islength/index.d.ts +++ b/lodash.islength/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isLength } from "lodash"; export = isLength; diff --git a/lodash.islength/tslint.json b/lodash.islength/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.islength/tslint.json +++ b/lodash.islength/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ismap/index.d.ts b/lodash.ismap/index.d.ts index 62bde83057..1fc93f3462 100644 --- a/lodash.ismap/index.d.ts +++ b/lodash.ismap/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isMap } from "lodash"; export = isMap; diff --git a/lodash.ismap/tslint.json b/lodash.ismap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ismap/tslint.json +++ b/lodash.ismap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ismatch/index.d.ts b/lodash.ismatch/index.d.ts index 617f6c9bda..3c8de854e8 100644 --- a/lodash.ismatch/index.d.ts +++ b/lodash.ismatch/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isMatch } from "lodash"; export = isMatch; diff --git a/lodash.ismatch/tslint.json b/lodash.ismatch/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ismatch/tslint.json +++ b/lodash.ismatch/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ismatchwith/index.d.ts b/lodash.ismatchwith/index.d.ts index ed8ff1b11b..c69ae83ea6 100644 --- a/lodash.ismatchwith/index.d.ts +++ b/lodash.ismatchwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isMatchWith } from "lodash"; export = isMatchWith; diff --git a/lodash.ismatchwith/tslint.json b/lodash.ismatchwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ismatchwith/tslint.json +++ b/lodash.ismatchwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnan/index.d.ts b/lodash.isnan/index.d.ts index 029f8c6e9b..1d95ffe160 100644 --- a/lodash.isnan/index.d.ts +++ b/lodash.isnan/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isNaN } from "lodash"; export = isNaN; diff --git a/lodash.isnan/tslint.json b/lodash.isnan/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnan/tslint.json +++ b/lodash.isnan/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnative/index.d.ts b/lodash.isnative/index.d.ts index 133f9cea47..29050811ef 100644 --- a/lodash.isnative/index.d.ts +++ b/lodash.isnative/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isNative } from "lodash"; export = isNative; diff --git a/lodash.isnative/tslint.json b/lodash.isnative/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnative/tslint.json +++ b/lodash.isnative/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnil/index.d.ts b/lodash.isnil/index.d.ts index d3aaa388ee..5199f1657a 100644 --- a/lodash.isnil/index.d.ts +++ b/lodash.isnil/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isNil } from "lodash"; export = isNil; diff --git a/lodash.isnil/tslint.json b/lodash.isnil/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnil/tslint.json +++ b/lodash.isnil/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnull/index.d.ts b/lodash.isnull/index.d.ts index 87a041d532..117b41f2e5 100644 --- a/lodash.isnull/index.d.ts +++ b/lodash.isnull/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isNull } from "lodash"; export = isNull; diff --git a/lodash.isnull/tslint.json b/lodash.isnull/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnull/tslint.json +++ b/lodash.isnull/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isnumber/index.d.ts b/lodash.isnumber/index.d.ts index 1f88c13582..70e51e9842 100644 --- a/lodash.isnumber/index.d.ts +++ b/lodash.isnumber/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isNumber } from "lodash"; export = isNumber; diff --git a/lodash.isnumber/tslint.json b/lodash.isnumber/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isnumber/tslint.json +++ b/lodash.isnumber/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isobject/index.d.ts b/lodash.isobject/index.d.ts index 229357175a..6f79f888df 100644 --- a/lodash.isobject/index.d.ts +++ b/lodash.isobject/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isObject } from "lodash"; export = isObject; diff --git a/lodash.isobject/tslint.json b/lodash.isobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isobject/tslint.json +++ b/lodash.isobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isobjectlike/index.d.ts b/lodash.isobjectlike/index.d.ts index 5c5c4bcdb3..8423f18a2a 100644 --- a/lodash.isobjectlike/index.d.ts +++ b/lodash.isobjectlike/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isObjectLike } from "lodash"; export = isObjectLike; diff --git a/lodash.isobjectlike/tslint.json b/lodash.isobjectlike/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isobjectlike/tslint.json +++ b/lodash.isobjectlike/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isplainobject/index.d.ts b/lodash.isplainobject/index.d.ts index c5e4af82cd..33e85453d2 100644 --- a/lodash.isplainobject/index.d.ts +++ b/lodash.isplainobject/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isPlainObject } from "lodash"; export = isPlainObject; diff --git a/lodash.isplainobject/tslint.json b/lodash.isplainobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isplainobject/tslint.json +++ b/lodash.isplainobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isregexp/index.d.ts b/lodash.isregexp/index.d.ts index bb6e4c182b..509c93a365 100644 --- a/lodash.isregexp/index.d.ts +++ b/lodash.isregexp/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isRegExp } from "lodash"; export = isRegExp; diff --git a/lodash.isregexp/tslint.json b/lodash.isregexp/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isregexp/tslint.json +++ b/lodash.isregexp/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.issafeinteger/index.d.ts b/lodash.issafeinteger/index.d.ts index 9c86763ba2..28fe1c868c 100644 --- a/lodash.issafeinteger/index.d.ts +++ b/lodash.issafeinteger/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isSafeInteger } from "lodash"; export = isSafeInteger; diff --git a/lodash.issafeinteger/tslint.json b/lodash.issafeinteger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.issafeinteger/tslint.json +++ b/lodash.issafeinteger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isset/index.d.ts b/lodash.isset/index.d.ts index eb77cabac8..67f643bb74 100644 --- a/lodash.isset/index.d.ts +++ b/lodash.isset/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isSet } from "lodash"; export = isSet; diff --git a/lodash.isset/tslint.json b/lodash.isset/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isset/tslint.json +++ b/lodash.isset/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isstring/index.d.ts b/lodash.isstring/index.d.ts index 67ee27673d..42cca91fee 100644 --- a/lodash.isstring/index.d.ts +++ b/lodash.isstring/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isString } from "lodash"; export = isString; diff --git a/lodash.isstring/tslint.json b/lodash.isstring/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isstring/tslint.json +++ b/lodash.isstring/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.issymbol/index.d.ts b/lodash.issymbol/index.d.ts index d7be47d922..16468073cc 100644 --- a/lodash.issymbol/index.d.ts +++ b/lodash.issymbol/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isSymbol } from "lodash"; export = isSymbol; diff --git a/lodash.issymbol/tslint.json b/lodash.issymbol/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.issymbol/tslint.json +++ b/lodash.issymbol/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.istypedarray/index.d.ts b/lodash.istypedarray/index.d.ts index 138f4baa08..e93a364295 100644 --- a/lodash.istypedarray/index.d.ts +++ b/lodash.istypedarray/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isTypedArray } from "lodash"; export = isTypedArray; diff --git a/lodash.istypedarray/tslint.json b/lodash.istypedarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.istypedarray/tslint.json +++ b/lodash.istypedarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isundefined/index.d.ts b/lodash.isundefined/index.d.ts index 2b112959c9..e9a3553600 100644 --- a/lodash.isundefined/index.d.ts +++ b/lodash.isundefined/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isUndefined } from "lodash"; export = isUndefined; diff --git a/lodash.isundefined/tslint.json b/lodash.isundefined/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isundefined/tslint.json +++ b/lodash.isundefined/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isweakmap/index.d.ts b/lodash.isweakmap/index.d.ts index a6fbc47986..7e2be4cfb2 100644 --- a/lodash.isweakmap/index.d.ts +++ b/lodash.isweakmap/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isWeakMap } from "lodash"; export = isWeakMap; diff --git a/lodash.isweakmap/tslint.json b/lodash.isweakmap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isweakmap/tslint.json +++ b/lodash.isweakmap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.isweakset/index.d.ts b/lodash.isweakset/index.d.ts index d4b016f106..d7e1a801eb 100644 --- a/lodash.isweakset/index.d.ts +++ b/lodash.isweakset/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { isWeakSet } from "lodash"; export = isWeakSet; diff --git a/lodash.isweakset/tslint.json b/lodash.isweakset/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.isweakset/tslint.json +++ b/lodash.isweakset/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.iteratee/index.d.ts b/lodash.iteratee/index.d.ts index 3e494ef2c8..7f6a197f12 100644 --- a/lodash.iteratee/index.d.ts +++ b/lodash.iteratee/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { iteratee } from "lodash"; export = iteratee; diff --git a/lodash.iteratee/tslint.json b/lodash.iteratee/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.iteratee/tslint.json +++ b/lodash.iteratee/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.join/index.d.ts b/lodash.join/index.d.ts index 14f26d67ed..a8dd2622a1 100644 --- a/lodash.join/index.d.ts +++ b/lodash.join/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { join } from "lodash"; export = join; diff --git a/lodash.join/tslint.json b/lodash.join/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.join/tslint.json +++ b/lodash.join/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.kebabcase/index.d.ts b/lodash.kebabcase/index.d.ts index 0851c7672a..00163a5a33 100644 --- a/lodash.kebabcase/index.d.ts +++ b/lodash.kebabcase/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { kebabCase } from "lodash"; export = kebabCase; diff --git a/lodash.kebabcase/tslint.json b/lodash.kebabcase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.kebabcase/tslint.json +++ b/lodash.kebabcase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.keyby/index.d.ts b/lodash.keyby/index.d.ts index 51aac439ca..8b5700ad76 100644 --- a/lodash.keyby/index.d.ts +++ b/lodash.keyby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { keyBy } from "lodash"; export = keyBy; diff --git a/lodash.keyby/tslint.json b/lodash.keyby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.keyby/tslint.json +++ b/lodash.keyby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.keys/index.d.ts b/lodash.keys/index.d.ts index b514c21483..d862fb0541 100644 --- a/lodash.keys/index.d.ts +++ b/lodash.keys/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { keys } from "lodash"; export = keys; diff --git a/lodash.keys/tslint.json b/lodash.keys/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.keys/tslint.json +++ b/lodash.keys/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.keysin/index.d.ts b/lodash.keysin/index.d.ts index 66a18cdfa7..e15bece518 100644 --- a/lodash.keysin/index.d.ts +++ b/lodash.keysin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { keysIn } from "lodash"; export = keysIn; diff --git a/lodash.keysin/tslint.json b/lodash.keysin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.keysin/tslint.json +++ b/lodash.keysin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.last/index.d.ts b/lodash.last/index.d.ts index a06a998d86..29b4ce9c63 100644 --- a/lodash.last/index.d.ts +++ b/lodash.last/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { last } from "lodash"; export = last; diff --git a/lodash.last/tslint.json b/lodash.last/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.last/tslint.json +++ b/lodash.last/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lastindexof/index.d.ts b/lodash.lastindexof/index.d.ts index 5fccab48d0..a9459ada4d 100644 --- a/lodash.lastindexof/index.d.ts +++ b/lodash.lastindexof/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { lastIndexOf } from "lodash"; export = lastIndexOf; diff --git a/lodash.lastindexof/tslint.json b/lodash.lastindexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lastindexof/tslint.json +++ b/lodash.lastindexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lowercase/index.d.ts b/lodash.lowercase/index.d.ts index 4232be29ad..b9505737bc 100644 --- a/lodash.lowercase/index.d.ts +++ b/lodash.lowercase/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { lowerCase } from "lodash"; export = lowerCase; diff --git a/lodash.lowercase/tslint.json b/lodash.lowercase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lowercase/tslint.json +++ b/lodash.lowercase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lowerfirst/index.d.ts b/lodash.lowerfirst/index.d.ts index c5d0ea1ca6..424d02631b 100644 --- a/lodash.lowerfirst/index.d.ts +++ b/lodash.lowerfirst/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { lowerFirst } from "lodash"; export = lowerFirst; diff --git a/lodash.lowerfirst/tslint.json b/lodash.lowerfirst/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lowerfirst/tslint.json +++ b/lodash.lowerfirst/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lt/index.d.ts b/lodash.lt/index.d.ts index 71cc6c1c00..5bad744986 100644 --- a/lodash.lt/index.d.ts +++ b/lodash.lt/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { lt } from "lodash"; export = lt; diff --git a/lodash.lt/tslint.json b/lodash.lt/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lt/tslint.json +++ b/lodash.lt/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.lte/index.d.ts b/lodash.lte/index.d.ts index 61ddce98b1..5299138c0f 100644 --- a/lodash.lte/index.d.ts +++ b/lodash.lte/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { lte } from "lodash"; export = lte; diff --git a/lodash.lte/tslint.json b/lodash.lte/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.lte/tslint.json +++ b/lodash.lte/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mapkeys/index.d.ts b/lodash.mapkeys/index.d.ts index c56b7647f5..bb32f2862f 100644 --- a/lodash.mapkeys/index.d.ts +++ b/lodash.mapkeys/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { mapKeys } from "lodash"; export = mapKeys; diff --git a/lodash.mapkeys/tslint.json b/lodash.mapkeys/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mapkeys/tslint.json +++ b/lodash.mapkeys/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mapvalues/index.d.ts b/lodash.mapvalues/index.d.ts index 4507f9234e..db516f2de8 100644 --- a/lodash.mapvalues/index.d.ts +++ b/lodash.mapvalues/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { mapValues } from "lodash"; export = mapValues; diff --git a/lodash.mapvalues/tslint.json b/lodash.mapvalues/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mapvalues/tslint.json +++ b/lodash.mapvalues/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.matches/index.d.ts b/lodash.matches/index.d.ts index 9179ed074b..f80ba05944 100644 --- a/lodash.matches/index.d.ts +++ b/lodash.matches/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { matches } from "lodash"; export = matches; diff --git a/lodash.matches/tslint.json b/lodash.matches/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.matches/tslint.json +++ b/lodash.matches/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.matchesproperty/index.d.ts b/lodash.matchesproperty/index.d.ts index afbb8dbfb3..e240a6ebad 100644 --- a/lodash.matchesproperty/index.d.ts +++ b/lodash.matchesproperty/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { matchesProperty } from "lodash"; export = matchesProperty; diff --git a/lodash.matchesproperty/tslint.json b/lodash.matchesproperty/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.matchesproperty/tslint.json +++ b/lodash.matchesproperty/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.max/index.d.ts b/lodash.max/index.d.ts index 55167fee93..dc8297841f 100644 --- a/lodash.max/index.d.ts +++ b/lodash.max/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { max } from "lodash"; export = max; diff --git a/lodash.max/tslint.json b/lodash.max/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.max/tslint.json +++ b/lodash.max/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.maxby/index.d.ts b/lodash.maxby/index.d.ts index 2513ce999f..47210f79a7 100644 --- a/lodash.maxby/index.d.ts +++ b/lodash.maxby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { maxBy } from "lodash"; export = maxBy; diff --git a/lodash.maxby/tslint.json b/lodash.maxby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.maxby/tslint.json +++ b/lodash.maxby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mean/index.d.ts b/lodash.mean/index.d.ts index bbf8183e23..dc839ace51 100644 --- a/lodash.mean/index.d.ts +++ b/lodash.mean/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { mean } from "lodash"; export = mean; diff --git a/lodash.mean/tslint.json b/lodash.mean/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mean/tslint.json +++ b/lodash.mean/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.meanby/index.d.ts b/lodash.meanby/index.d.ts new file mode 100644 index 0000000000..8973d40ded --- /dev/null +++ b/lodash.meanby/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for lodash.meanBy 4.10 +// Project: http://lodash.com/ +// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { meanBy } from "lodash"; +export = meanBy; diff --git a/lodash.meanby/tsconfig.json b/lodash.meanby/tsconfig.json new file mode 100644 index 0000000000..92ebbc6458 --- /dev/null +++ b/lodash.meanby/tsconfig.json @@ -0,0 +1,21 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/lodash.meanby/tslint.json b/lodash.meanby/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/lodash.meanby/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/lodash.memoize/index.d.ts b/lodash.memoize/index.d.ts index 6a4c57a197..25002a9086 100644 --- a/lodash.memoize/index.d.ts +++ b/lodash.memoize/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { memoize } from "lodash"; export = memoize; diff --git a/lodash.memoize/tslint.json b/lodash.memoize/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.memoize/tslint.json +++ b/lodash.memoize/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.merge/index.d.ts b/lodash.merge/index.d.ts index f4250afe0a..a5352b8cc9 100644 --- a/lodash.merge/index.d.ts +++ b/lodash.merge/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { merge } from "lodash"; export = merge; diff --git a/lodash.merge/tslint.json b/lodash.merge/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.merge/tslint.json +++ b/lodash.merge/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mergewith/index.d.ts b/lodash.mergewith/index.d.ts index d22369299e..85cad973d9 100644 --- a/lodash.mergewith/index.d.ts +++ b/lodash.mergewith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { mergeWith } from "lodash"; export = mergeWith; diff --git a/lodash.mergewith/tslint.json b/lodash.mergewith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mergewith/tslint.json +++ b/lodash.mergewith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.method/index.d.ts b/lodash.method/index.d.ts index d890f661e2..cee310ff55 100644 --- a/lodash.method/index.d.ts +++ b/lodash.method/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { method } from "lodash"; export = method; diff --git a/lodash.method/tslint.json b/lodash.method/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.method/tslint.json +++ b/lodash.method/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.methodof/index.d.ts b/lodash.methodof/index.d.ts index b464af2fc4..5420de784a 100644 --- a/lodash.methodof/index.d.ts +++ b/lodash.methodof/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { methodOf } from "lodash"; export = methodOf; diff --git a/lodash.methodof/tslint.json b/lodash.methodof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.methodof/tslint.json +++ b/lodash.methodof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.min/index.d.ts b/lodash.min/index.d.ts index 5f4dc842dd..87fccd9876 100644 --- a/lodash.min/index.d.ts +++ b/lodash.min/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { min } from "lodash"; export = min; diff --git a/lodash.min/tslint.json b/lodash.min/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.min/tslint.json +++ b/lodash.min/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.minby/index.d.ts b/lodash.minby/index.d.ts index 95293a83bf..d46f507c70 100644 --- a/lodash.minby/index.d.ts +++ b/lodash.minby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { minBy } from "lodash"; export = minBy; diff --git a/lodash.minby/tslint.json b/lodash.minby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.minby/tslint.json +++ b/lodash.minby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.mixin/index.d.ts b/lodash.mixin/index.d.ts index 78190227b1..8a4190762b 100644 --- a/lodash.mixin/index.d.ts +++ b/lodash.mixin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { mixin } from "lodash"; export = mixin; diff --git a/lodash.mixin/tslint.json b/lodash.mixin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.mixin/tslint.json +++ b/lodash.mixin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.negate/index.d.ts b/lodash.negate/index.d.ts index 48796a3750..a4c8b4b88e 100644 --- a/lodash.negate/index.d.ts +++ b/lodash.negate/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { negate } from "lodash"; export = negate; diff --git a/lodash.negate/tslint.json b/lodash.negate/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.negate/tslint.json +++ b/lodash.negate/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.noop/index.d.ts b/lodash.noop/index.d.ts index 632d3d1292..04e6cacbb3 100644 --- a/lodash.noop/index.d.ts +++ b/lodash.noop/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { noop } from "lodash"; export = noop; diff --git a/lodash.noop/tslint.json b/lodash.noop/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.noop/tslint.json +++ b/lodash.noop/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.now/index.d.ts b/lodash.now/index.d.ts index 80e893d018..ecda7f778d 100644 --- a/lodash.now/index.d.ts +++ b/lodash.now/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { now } from "lodash"; export = now; diff --git a/lodash.now/tslint.json b/lodash.now/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.now/tslint.json +++ b/lodash.now/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.ntharg/index.d.ts b/lodash.ntharg/index.d.ts index 51eb387c96..0d35cb5772 100644 --- a/lodash.ntharg/index.d.ts +++ b/lodash.ntharg/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { nthArg } from "lodash"; export = nthArg; diff --git a/lodash.ntharg/tslint.json b/lodash.ntharg/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.ntharg/tslint.json +++ b/lodash.ntharg/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.omit/index.d.ts b/lodash.omit/index.d.ts index b60f1d503b..491b505016 100644 --- a/lodash.omit/index.d.ts +++ b/lodash.omit/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { omit } from "lodash"; export = omit; diff --git a/lodash.omit/tslint.json b/lodash.omit/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.omit/tslint.json +++ b/lodash.omit/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.omitby/index.d.ts b/lodash.omitby/index.d.ts index 82c8b6d063..fee479036b 100644 --- a/lodash.omitby/index.d.ts +++ b/lodash.omitby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { omitBy } from "lodash"; export = omitBy; diff --git a/lodash.omitby/tslint.json b/lodash.omitby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.omitby/tslint.json +++ b/lodash.omitby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.once/index.d.ts b/lodash.once/index.d.ts index 3089544fe9..3f8622e6a0 100644 --- a/lodash.once/index.d.ts +++ b/lodash.once/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { once } from "lodash"; export = once; diff --git a/lodash.once/tslint.json b/lodash.once/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.once/tslint.json +++ b/lodash.once/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.orderby/index.d.ts b/lodash.orderby/index.d.ts index e862a62e96..b348cefebc 100644 --- a/lodash.orderby/index.d.ts +++ b/lodash.orderby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { orderBy } from "lodash"; export = orderBy; diff --git a/lodash.orderby/tslint.json b/lodash.orderby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.orderby/tslint.json +++ b/lodash.orderby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.over/index.d.ts b/lodash.over/index.d.ts index 1df6138a41..5715f0a46e 100644 --- a/lodash.over/index.d.ts +++ b/lodash.over/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { over } from "lodash"; export = over; diff --git a/lodash.over/tslint.json b/lodash.over/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.over/tslint.json +++ b/lodash.over/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.overargs/index.d.ts b/lodash.overargs/index.d.ts index 1cd9c19126..576ab8588a 100644 --- a/lodash.overargs/index.d.ts +++ b/lodash.overargs/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { overArgs } from "lodash"; export = overArgs; diff --git a/lodash.overargs/tslint.json b/lodash.overargs/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.overargs/tslint.json +++ b/lodash.overargs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.overevery/index.d.ts b/lodash.overevery/index.d.ts index 2211dc569b..68d6cd3639 100644 --- a/lodash.overevery/index.d.ts +++ b/lodash.overevery/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { overEvery } from "lodash"; export = overEvery; diff --git a/lodash.overevery/tslint.json b/lodash.overevery/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.overevery/tslint.json +++ b/lodash.overevery/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.oversome/index.d.ts b/lodash.oversome/index.d.ts index f8ec5329f6..4e4fe4eb5c 100644 --- a/lodash.oversome/index.d.ts +++ b/lodash.oversome/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { overSome } from "lodash"; export = overSome; diff --git a/lodash.oversome/tslint.json b/lodash.oversome/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.oversome/tslint.json +++ b/lodash.oversome/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pad/index.d.ts b/lodash.pad/index.d.ts index 06a7c7f5ac..259c312381 100644 --- a/lodash.pad/index.d.ts +++ b/lodash.pad/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { pad } from "lodash"; export = pad; diff --git a/lodash.pad/tslint.json b/lodash.pad/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pad/tslint.json +++ b/lodash.pad/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.padend/index.d.ts b/lodash.padend/index.d.ts index b42ad0ab11..825479dae8 100644 --- a/lodash.padend/index.d.ts +++ b/lodash.padend/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { padEnd } from "lodash"; export = padEnd; diff --git a/lodash.padend/tslint.json b/lodash.padend/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.padend/tslint.json +++ b/lodash.padend/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.padstart/index.d.ts b/lodash.padstart/index.d.ts index b020c51ee5..b3607d61cc 100644 --- a/lodash.padstart/index.d.ts +++ b/lodash.padstart/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { padStart } from "lodash"; export = padStart; diff --git a/lodash.padstart/tslint.json b/lodash.padstart/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.padstart/tslint.json +++ b/lodash.padstart/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.parseint/index.d.ts b/lodash.parseint/index.d.ts index cafd05c882..4724867112 100644 --- a/lodash.parseint/index.d.ts +++ b/lodash.parseint/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { parseInt } from "lodash"; export = parseInt; diff --git a/lodash.parseint/tslint.json b/lodash.parseint/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.parseint/tslint.json +++ b/lodash.parseint/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.partial/index.d.ts b/lodash.partial/index.d.ts index 4d6dc3c303..8466a32963 100644 --- a/lodash.partial/index.d.ts +++ b/lodash.partial/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { partial } from "lodash"; export = partial; diff --git a/lodash.partial/tslint.json b/lodash.partial/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.partial/tslint.json +++ b/lodash.partial/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.partialright/index.d.ts b/lodash.partialright/index.d.ts index d24675203d..5f9f7bef4d 100644 --- a/lodash.partialright/index.d.ts +++ b/lodash.partialright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { partialRight } from "lodash"; export = partialRight; diff --git a/lodash.partialright/tslint.json b/lodash.partialright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.partialright/tslint.json +++ b/lodash.partialright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.partition/index.d.ts b/lodash.partition/index.d.ts index c79c676a46..d481bae93b 100644 --- a/lodash.partition/index.d.ts +++ b/lodash.partition/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { partition } from "lodash"; export = partition; diff --git a/lodash.partition/tslint.json b/lodash.partition/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.partition/tslint.json +++ b/lodash.partition/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pick/index.d.ts b/lodash.pick/index.d.ts index 7fa2ef6e84..f27646190a 100644 --- a/lodash.pick/index.d.ts +++ b/lodash.pick/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { pick } from "lodash"; export = pick; diff --git a/lodash.pick/tslint.json b/lodash.pick/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pick/tslint.json +++ b/lodash.pick/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pickby/index.d.ts b/lodash.pickby/index.d.ts index 2c72e96edd..0a77aaedc8 100644 --- a/lodash.pickby/index.d.ts +++ b/lodash.pickby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { pickBy } from "lodash"; export = pickBy; diff --git a/lodash.pickby/tslint.json b/lodash.pickby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pickby/tslint.json +++ b/lodash.pickby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.property/index.d.ts b/lodash.property/index.d.ts index e9ea2b894e..90e3eb20b3 100644 --- a/lodash.property/index.d.ts +++ b/lodash.property/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { property } from "lodash"; export = property; diff --git a/lodash.property/tslint.json b/lodash.property/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.property/tslint.json +++ b/lodash.property/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.propertyof/index.d.ts b/lodash.propertyof/index.d.ts index d52d898afa..2db1d2461f 100644 --- a/lodash.propertyof/index.d.ts +++ b/lodash.propertyof/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { propertyOf } from "lodash"; export = propertyOf; diff --git a/lodash.propertyof/tslint.json b/lodash.propertyof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.propertyof/tslint.json +++ b/lodash.propertyof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pull/index.d.ts b/lodash.pull/index.d.ts index b60aec6f73..7232218789 100644 --- a/lodash.pull/index.d.ts +++ b/lodash.pull/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { pull } from "lodash"; export = pull; diff --git a/lodash.pull/tslint.json b/lodash.pull/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pull/tslint.json +++ b/lodash.pull/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pullall/index.d.ts b/lodash.pullall/index.d.ts index 4c55d19fc0..9503a4c6e5 100644 --- a/lodash.pullall/index.d.ts +++ b/lodash.pullall/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { pullAll } from "lodash"; export = pullAll; diff --git a/lodash.pullall/tslint.json b/lodash.pullall/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pullall/tslint.json +++ b/lodash.pullall/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pullallby/index.d.ts b/lodash.pullallby/index.d.ts index 18bc32f579..4f5c91696f 100644 --- a/lodash.pullallby/index.d.ts +++ b/lodash.pullallby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { pullAllBy } from "lodash"; export = pullAllBy; diff --git a/lodash.pullallby/tslint.json b/lodash.pullallby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pullallby/tslint.json +++ b/lodash.pullallby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.pullat/index.d.ts b/lodash.pullat/index.d.ts index 4a7c29cb90..2330713675 100644 --- a/lodash.pullat/index.d.ts +++ b/lodash.pullat/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { pullAt } from "lodash"; export = pullAt; diff --git a/lodash.pullat/tslint.json b/lodash.pullat/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.pullat/tslint.json +++ b/lodash.pullat/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.random/index.d.ts b/lodash.random/index.d.ts index 018f4e1c99..87ba37f817 100644 --- a/lodash.random/index.d.ts +++ b/lodash.random/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { random } from "lodash"; export = random; diff --git a/lodash.random/tslint.json b/lodash.random/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.random/tslint.json +++ b/lodash.random/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.range/index.d.ts b/lodash.range/index.d.ts index 289101b98a..6e9871a10a 100644 --- a/lodash.range/index.d.ts +++ b/lodash.range/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { range } from "lodash"; export = range; diff --git a/lodash.range/tslint.json b/lodash.range/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.range/tslint.json +++ b/lodash.range/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.rangeright/index.d.ts b/lodash.rangeright/index.d.ts index 15d7f8be2b..b7fcfd8b34 100644 --- a/lodash.rangeright/index.d.ts +++ b/lodash.rangeright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { rangeRight } from "lodash"; export = rangeRight; diff --git a/lodash.rangeright/tslint.json b/lodash.rangeright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.rangeright/tslint.json +++ b/lodash.rangeright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.rearg/index.d.ts b/lodash.rearg/index.d.ts index 987565e162..8c6f912bcd 100644 --- a/lodash.rearg/index.d.ts +++ b/lodash.rearg/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { rearg } from "lodash"; export = rearg; diff --git a/lodash.rearg/tslint.json b/lodash.rearg/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.rearg/tslint.json +++ b/lodash.rearg/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reduce/index.d.ts b/lodash.reduce/index.d.ts index 44f4007e94..5ef634a93d 100644 --- a/lodash.reduce/index.d.ts +++ b/lodash.reduce/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { reduce } from "lodash"; export = reduce; diff --git a/lodash.reduce/tslint.json b/lodash.reduce/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reduce/tslint.json +++ b/lodash.reduce/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reduceright/index.d.ts b/lodash.reduceright/index.d.ts index 3377523e1a..ee3e05ea62 100644 --- a/lodash.reduceright/index.d.ts +++ b/lodash.reduceright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { reduceRight } from "lodash"; export = reduceRight; diff --git a/lodash.reduceright/tslint.json b/lodash.reduceright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reduceright/tslint.json +++ b/lodash.reduceright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reject/index.d.ts b/lodash.reject/index.d.ts index f7e56a60bc..2a7a953403 100644 --- a/lodash.reject/index.d.ts +++ b/lodash.reject/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { reject } from "lodash"; export = reject; diff --git a/lodash.reject/tslint.json b/lodash.reject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reject/tslint.json +++ b/lodash.reject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.remove/index.d.ts b/lodash.remove/index.d.ts index b6b2871f51..cf3ecdb008 100644 --- a/lodash.remove/index.d.ts +++ b/lodash.remove/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { remove } from "lodash"; export = remove; diff --git a/lodash.remove/tslint.json b/lodash.remove/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.remove/tslint.json +++ b/lodash.remove/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.repeat/index.d.ts b/lodash.repeat/index.d.ts index a0ab5e77f2..066a9f7741 100644 --- a/lodash.repeat/index.d.ts +++ b/lodash.repeat/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { repeat } from "lodash"; export = repeat; diff --git a/lodash.repeat/tslint.json b/lodash.repeat/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.repeat/tslint.json +++ b/lodash.repeat/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.replace/index.d.ts b/lodash.replace/index.d.ts index d1dc58bad0..deaf6f5925 100644 --- a/lodash.replace/index.d.ts +++ b/lodash.replace/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { replace } from "lodash"; export = replace; diff --git a/lodash.replace/tslint.json b/lodash.replace/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.replace/tslint.json +++ b/lodash.replace/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.rest/index.d.ts b/lodash.rest/index.d.ts index c8b2728ec5..12d89f07a4 100644 --- a/lodash.rest/index.d.ts +++ b/lodash.rest/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { rest } from "lodash"; export = rest; diff --git a/lodash.rest/tslint.json b/lodash.rest/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.rest/tslint.json +++ b/lodash.rest/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.result/index.d.ts b/lodash.result/index.d.ts index 344d75766a..ca67b40446 100644 --- a/lodash.result/index.d.ts +++ b/lodash.result/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { result } from "lodash"; export = result; diff --git a/lodash.result/tslint.json b/lodash.result/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.result/tslint.json +++ b/lodash.result/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.reverse/index.d.ts b/lodash.reverse/index.d.ts index 8da6b703f7..0486ee3715 100644 --- a/lodash.reverse/index.d.ts +++ b/lodash.reverse/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { reverse } from "lodash"; export = reverse; diff --git a/lodash.reverse/tslint.json b/lodash.reverse/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.reverse/tslint.json +++ b/lodash.reverse/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.round/index.d.ts b/lodash.round/index.d.ts index 828aee5487..5eb7dddb09 100644 --- a/lodash.round/index.d.ts +++ b/lodash.round/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { round } from "lodash"; export = round; diff --git a/lodash.round/tslint.json b/lodash.round/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.round/tslint.json +++ b/lodash.round/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sample/index.d.ts b/lodash.sample/index.d.ts index 2fa651cce8..b5873086e2 100644 --- a/lodash.sample/index.d.ts +++ b/lodash.sample/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sample } from "lodash"; export = sample; diff --git a/lodash.sample/tslint.json b/lodash.sample/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sample/tslint.json +++ b/lodash.sample/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.samplesize/index.d.ts b/lodash.samplesize/index.d.ts index 5be09b8960..01a187726b 100644 --- a/lodash.samplesize/index.d.ts +++ b/lodash.samplesize/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sampleSize } from "lodash"; export = sampleSize; diff --git a/lodash.samplesize/tslint.json b/lodash.samplesize/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.samplesize/tslint.json +++ b/lodash.samplesize/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.set/index.d.ts b/lodash.set/index.d.ts index 45c51f879a..f76b88790e 100644 --- a/lodash.set/index.d.ts +++ b/lodash.set/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { set } from "lodash"; export = set; diff --git a/lodash.set/tslint.json b/lodash.set/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.set/tslint.json +++ b/lodash.set/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.setwith/index.d.ts b/lodash.setwith/index.d.ts index 8c41eb3be6..43502688be 100644 --- a/lodash.setwith/index.d.ts +++ b/lodash.setwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { setWith } from "lodash"; export = setWith; diff --git a/lodash.setwith/tslint.json b/lodash.setwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.setwith/tslint.json +++ b/lodash.setwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.shuffle/index.d.ts b/lodash.shuffle/index.d.ts index 7b8e65fde0..1283f11844 100644 --- a/lodash.shuffle/index.d.ts +++ b/lodash.shuffle/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { shuffle } from "lodash"; export = shuffle; diff --git a/lodash.shuffle/tslint.json b/lodash.shuffle/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.shuffle/tslint.json +++ b/lodash.shuffle/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.size/index.d.ts b/lodash.size/index.d.ts index 6e7201c394..e0aa69d12f 100644 --- a/lodash.size/index.d.ts +++ b/lodash.size/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { size } from "lodash"; export = size; diff --git a/lodash.size/tslint.json b/lodash.size/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.size/tslint.json +++ b/lodash.size/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.slice/index.d.ts b/lodash.slice/index.d.ts index b9206644eb..2b53bb2386 100644 --- a/lodash.slice/index.d.ts +++ b/lodash.slice/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { slice } from "lodash"; export = slice; diff --git a/lodash.slice/tslint.json b/lodash.slice/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.slice/tslint.json +++ b/lodash.slice/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.snakecase/index.d.ts b/lodash.snakecase/index.d.ts index 36fbaec580..db2758999b 100644 --- a/lodash.snakecase/index.d.ts +++ b/lodash.snakecase/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { snakeCase } from "lodash"; export = snakeCase; diff --git a/lodash.snakecase/tslint.json b/lodash.snakecase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.snakecase/tslint.json +++ b/lodash.snakecase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.some/index.d.ts b/lodash.some/index.d.ts index e722a5ccae..3de45fa161 100644 --- a/lodash.some/index.d.ts +++ b/lodash.some/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { some } from "lodash"; export = some; diff --git a/lodash.some/tslint.json b/lodash.some/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.some/tslint.json +++ b/lodash.some/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortby/index.d.ts b/lodash.sortby/index.d.ts index 028b50fa20..cc75aa6dca 100644 --- a/lodash.sortby/index.d.ts +++ b/lodash.sortby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortBy } from "lodash"; export = sortBy; diff --git a/lodash.sortby/tslint.json b/lodash.sortby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortby/tslint.json +++ b/lodash.sortby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedindex/index.d.ts b/lodash.sortedindex/index.d.ts index 9c799fec11..ab6e8eca1f 100644 --- a/lodash.sortedindex/index.d.ts +++ b/lodash.sortedindex/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedIndex } from "lodash"; export = sortedIndex; diff --git a/lodash.sortedindex/tslint.json b/lodash.sortedindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedindex/tslint.json +++ b/lodash.sortedindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedindexby/index.d.ts b/lodash.sortedindexby/index.d.ts index 73601c7b4d..1f5d0c15ac 100644 --- a/lodash.sortedindexby/index.d.ts +++ b/lodash.sortedindexby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedIndexBy } from "lodash"; export = sortedIndexBy; diff --git a/lodash.sortedindexby/tslint.json b/lodash.sortedindexby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedindexby/tslint.json +++ b/lodash.sortedindexby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedindexof/index.d.ts b/lodash.sortedindexof/index.d.ts index 471e408bb9..814afd3e3c 100644 --- a/lodash.sortedindexof/index.d.ts +++ b/lodash.sortedindexof/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedIndexOf } from "lodash"; export = sortedIndexOf; diff --git a/lodash.sortedindexof/tslint.json b/lodash.sortedindexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedindexof/tslint.json +++ b/lodash.sortedindexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedlastindex/index.d.ts b/lodash.sortedlastindex/index.d.ts index 95825a983a..5a1c0faa7d 100644 --- a/lodash.sortedlastindex/index.d.ts +++ b/lodash.sortedlastindex/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedLastIndex } from "lodash"; export = sortedLastIndex; diff --git a/lodash.sortedlastindex/tslint.json b/lodash.sortedlastindex/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedlastindex/tslint.json +++ b/lodash.sortedlastindex/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedlastindexby/index.d.ts b/lodash.sortedlastindexby/index.d.ts index e5a167a17b..5b939599b2 100644 --- a/lodash.sortedlastindexby/index.d.ts +++ b/lodash.sortedlastindexby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedLastIndexBy } from "lodash"; export = sortedLastIndexBy; diff --git a/lodash.sortedlastindexby/tslint.json b/lodash.sortedlastindexby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedlastindexby/tslint.json +++ b/lodash.sortedlastindexby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sortedlastindexof/index.d.ts b/lodash.sortedlastindexof/index.d.ts index c908ede67a..9817ef54f5 100644 --- a/lodash.sortedlastindexof/index.d.ts +++ b/lodash.sortedlastindexof/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedLastIndexOf } from "lodash"; export = sortedLastIndexOf; diff --git a/lodash.sortedlastindexof/tslint.json b/lodash.sortedlastindexof/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sortedlastindexof/tslint.json +++ b/lodash.sortedlastindexof/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sorteduniq/index.d.ts b/lodash.sorteduniq/index.d.ts index c9ff4eb4e7..c8b8feea6f 100644 --- a/lodash.sorteduniq/index.d.ts +++ b/lodash.sorteduniq/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedUniq } from "lodash"; export = sortedUniq; diff --git a/lodash.sorteduniq/tslint.json b/lodash.sorteduniq/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sorteduniq/tslint.json +++ b/lodash.sorteduniq/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sorteduniqby/index.d.ts b/lodash.sorteduniqby/index.d.ts index 295d3bcaf3..637895af43 100644 --- a/lodash.sorteduniqby/index.d.ts +++ b/lodash.sorteduniqby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sortedUniqBy } from "lodash"; export = sortedUniqBy; diff --git a/lodash.sorteduniqby/tslint.json b/lodash.sorteduniqby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sorteduniqby/tslint.json +++ b/lodash.sorteduniqby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.split/index.d.ts b/lodash.split/index.d.ts index 43c187c455..fd5a261917 100644 --- a/lodash.split/index.d.ts +++ b/lodash.split/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { split } from "lodash"; export = split; diff --git a/lodash.split/tslint.json b/lodash.split/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.split/tslint.json +++ b/lodash.split/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.spread/index.d.ts b/lodash.spread/index.d.ts index adaec68385..7bbc4e9245 100644 --- a/lodash.spread/index.d.ts +++ b/lodash.spread/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { spread } from "lodash"; export = spread; diff --git a/lodash.spread/tslint.json b/lodash.spread/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.spread/tslint.json +++ b/lodash.spread/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.startcase/index.d.ts b/lodash.startcase/index.d.ts index 9c550e4a0c..53798256bc 100644 --- a/lodash.startcase/index.d.ts +++ b/lodash.startcase/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { startCase } from "lodash"; export = startCase; diff --git a/lodash.startcase/tslint.json b/lodash.startcase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.startcase/tslint.json +++ b/lodash.startcase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.startswith/index.d.ts b/lodash.startswith/index.d.ts index ebb4178ac5..84071e3d10 100644 --- a/lodash.startswith/index.d.ts +++ b/lodash.startswith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { startsWith } from "lodash"; export = startsWith; diff --git a/lodash.startswith/tslint.json b/lodash.startswith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.startswith/tslint.json +++ b/lodash.startswith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.subtract/index.d.ts b/lodash.subtract/index.d.ts index 6d148eb796..0b57101cee 100644 --- a/lodash.subtract/index.d.ts +++ b/lodash.subtract/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { subtract } from "lodash"; export = subtract; diff --git a/lodash.subtract/tslint.json b/lodash.subtract/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.subtract/tslint.json +++ b/lodash.subtract/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sum/index.d.ts b/lodash.sum/index.d.ts index df4194246e..e6aaf24aee 100644 --- a/lodash.sum/index.d.ts +++ b/lodash.sum/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sum } from "lodash"; export = sum; diff --git a/lodash.sum/tslint.json b/lodash.sum/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sum/tslint.json +++ b/lodash.sum/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.sumby/index.d.ts b/lodash.sumby/index.d.ts index dad7e3dfa7..e1f21e1454 100644 --- a/lodash.sumby/index.d.ts +++ b/lodash.sumby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { sumBy } from "lodash"; export = sumBy; diff --git a/lodash.sumby/tslint.json b/lodash.sumby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.sumby/tslint.json +++ b/lodash.sumby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tail/index.d.ts b/lodash.tail/index.d.ts index 1edf5423c0..7543f1ae31 100644 --- a/lodash.tail/index.d.ts +++ b/lodash.tail/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { tail } from "lodash"; export = tail; diff --git a/lodash.tail/tslint.json b/lodash.tail/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tail/tslint.json +++ b/lodash.tail/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.take/index.d.ts b/lodash.take/index.d.ts index f477178ee3..688eaf7b8d 100644 --- a/lodash.take/index.d.ts +++ b/lodash.take/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { take } from "lodash"; export = take; diff --git a/lodash.take/tslint.json b/lodash.take/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.take/tslint.json +++ b/lodash.take/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.takeright/index.d.ts b/lodash.takeright/index.d.ts index f44b5b7a99..9599696c72 100644 --- a/lodash.takeright/index.d.ts +++ b/lodash.takeright/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { takeRight } from "lodash"; export = takeRight; diff --git a/lodash.takeright/tslint.json b/lodash.takeright/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.takeright/tslint.json +++ b/lodash.takeright/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.takerightwhile/index.d.ts b/lodash.takerightwhile/index.d.ts index 1940bdab6a..b0ccc8647f 100644 --- a/lodash.takerightwhile/index.d.ts +++ b/lodash.takerightwhile/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { takeRightWhile } from "lodash"; export = takeRightWhile; diff --git a/lodash.takerightwhile/tslint.json b/lodash.takerightwhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.takerightwhile/tslint.json +++ b/lodash.takerightwhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.takewhile/index.d.ts b/lodash.takewhile/index.d.ts index b1c7464e21..8e557afdd4 100644 --- a/lodash.takewhile/index.d.ts +++ b/lodash.takewhile/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { takeWhile } from "lodash"; export = takeWhile; diff --git a/lodash.takewhile/tslint.json b/lodash.takewhile/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.takewhile/tslint.json +++ b/lodash.takewhile/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.template/index.d.ts b/lodash.template/index.d.ts index af31692e84..a81b832990 100644 --- a/lodash.template/index.d.ts +++ b/lodash.template/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { template } from "lodash"; export = template; diff --git a/lodash.template/tslint.json b/lodash.template/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.template/tslint.json +++ b/lodash.template/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.throttle/index.d.ts b/lodash.throttle/index.d.ts index ed74ec008b..0a2903b317 100644 --- a/lodash.throttle/index.d.ts +++ b/lodash.throttle/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { throttle } from "lodash"; export = throttle; diff --git a/lodash.throttle/tslint.json b/lodash.throttle/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.throttle/tslint.json +++ b/lodash.throttle/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.times/index.d.ts b/lodash.times/index.d.ts index adabd498e2..f899aac24e 100644 --- a/lodash.times/index.d.ts +++ b/lodash.times/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { times } from "lodash"; export = times; diff --git a/lodash.times/tslint.json b/lodash.times/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.times/tslint.json +++ b/lodash.times/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.toarray/index.d.ts b/lodash.toarray/index.d.ts index 42e878de35..f1cb6ecdea 100644 --- a/lodash.toarray/index.d.ts +++ b/lodash.toarray/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toArray } from "lodash"; export = toArray; diff --git a/lodash.toarray/tslint.json b/lodash.toarray/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.toarray/tslint.json +++ b/lodash.toarray/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tointeger/index.d.ts b/lodash.tointeger/index.d.ts index 19a97ef2fd..32f5bafbb7 100644 --- a/lodash.tointeger/index.d.ts +++ b/lodash.tointeger/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toInteger } from "lodash"; export = toInteger; diff --git a/lodash.tointeger/tslint.json b/lodash.tointeger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tointeger/tslint.json +++ b/lodash.tointeger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tolength/index.d.ts b/lodash.tolength/index.d.ts index 1170461e93..0af29d75fd 100644 --- a/lodash.tolength/index.d.ts +++ b/lodash.tolength/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toLength } from "lodash"; export = toLength; diff --git a/lodash.tolength/tslint.json b/lodash.tolength/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tolength/tslint.json +++ b/lodash.tolength/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tolower/index.d.ts b/lodash.tolower/index.d.ts index 1f350ff005..1403cc4cee 100644 --- a/lodash.tolower/index.d.ts +++ b/lodash.tolower/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toLower } from "lodash"; export = toLower; diff --git a/lodash.tolower/tslint.json b/lodash.tolower/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tolower/tslint.json +++ b/lodash.tolower/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tonumber/index.d.ts b/lodash.tonumber/index.d.ts index fd6fe57a0b..aeacc96956 100644 --- a/lodash.tonumber/index.d.ts +++ b/lodash.tonumber/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toNumber } from "lodash"; export = toNumber; diff --git a/lodash.tonumber/tslint.json b/lodash.tonumber/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tonumber/tslint.json +++ b/lodash.tonumber/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.topairs/index.d.ts b/lodash.topairs/index.d.ts index 0623631aac..e5c92897ba 100644 --- a/lodash.topairs/index.d.ts +++ b/lodash.topairs/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toPairs } from "lodash"; export = toPairs; diff --git a/lodash.topairs/tslint.json b/lodash.topairs/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.topairs/tslint.json +++ b/lodash.topairs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.topairsin/index.d.ts b/lodash.topairsin/index.d.ts index 6da8aac997..c4980bf227 100644 --- a/lodash.topairsin/index.d.ts +++ b/lodash.topairsin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toPairsIn } from "lodash"; export = toPairsIn; diff --git a/lodash.topairsin/tslint.json b/lodash.topairsin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.topairsin/tslint.json +++ b/lodash.topairsin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.topath/index.d.ts b/lodash.topath/index.d.ts index ed9ce7c5a9..5647cbca88 100644 --- a/lodash.topath/index.d.ts +++ b/lodash.topath/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toPath } from "lodash"; export = toPath; diff --git a/lodash.topath/tslint.json b/lodash.topath/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.topath/tslint.json +++ b/lodash.topath/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.toplainobject/index.d.ts b/lodash.toplainobject/index.d.ts index c1b5793d7d..27de1990bd 100644 --- a/lodash.toplainobject/index.d.ts +++ b/lodash.toplainobject/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toPlainObject } from "lodash"; export = toPlainObject; diff --git a/lodash.toplainobject/tslint.json b/lodash.toplainobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.toplainobject/tslint.json +++ b/lodash.toplainobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tosafeinteger/index.d.ts b/lodash.tosafeinteger/index.d.ts index b126b0188a..c8d7567a70 100644 --- a/lodash.tosafeinteger/index.d.ts +++ b/lodash.tosafeinteger/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toSafeInteger } from "lodash"; export = toSafeInteger; diff --git a/lodash.tosafeinteger/tslint.json b/lodash.tosafeinteger/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tosafeinteger/tslint.json +++ b/lodash.tosafeinteger/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.tostring/index.d.ts b/lodash.tostring/index.d.ts index bf9ed55be9..42f59393f1 100644 --- a/lodash.tostring/index.d.ts +++ b/lodash.tostring/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toString } from "lodash"; export = toString; diff --git a/lodash.tostring/tslint.json b/lodash.tostring/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.tostring/tslint.json +++ b/lodash.tostring/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.toupper/index.d.ts b/lodash.toupper/index.d.ts index 9e26f50c2b..02bef92ae3 100644 --- a/lodash.toupper/index.d.ts +++ b/lodash.toupper/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { toUpper } from "lodash"; export = toUpper; diff --git a/lodash.toupper/tslint.json b/lodash.toupper/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.toupper/tslint.json +++ b/lodash.toupper/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.transform/index.d.ts b/lodash.transform/index.d.ts index 78c4bfdb7c..ac5ee501cf 100644 --- a/lodash.transform/index.d.ts +++ b/lodash.transform/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { transform } from "lodash"; export = transform; diff --git a/lodash.transform/tslint.json b/lodash.transform/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.transform/tslint.json +++ b/lodash.transform/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.trim/index.d.ts b/lodash.trim/index.d.ts index 4848a6ddbd..7aa6fcc4e6 100644 --- a/lodash.trim/index.d.ts +++ b/lodash.trim/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { trim } from "lodash"; export = trim; diff --git a/lodash.trim/tslint.json b/lodash.trim/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.trim/tslint.json +++ b/lodash.trim/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.trimend/index.d.ts b/lodash.trimend/index.d.ts index 116f295b06..1e871b2126 100644 --- a/lodash.trimend/index.d.ts +++ b/lodash.trimend/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { trimEnd } from "lodash"; export = trimEnd; diff --git a/lodash.trimend/tslint.json b/lodash.trimend/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.trimend/tslint.json +++ b/lodash.trimend/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.trimstart/index.d.ts b/lodash.trimstart/index.d.ts index 93df2c2483..c525bf5c8e 100644 --- a/lodash.trimstart/index.d.ts +++ b/lodash.trimstart/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { trimStart } from "lodash"; export = trimStart; diff --git a/lodash.trimstart/tslint.json b/lodash.trimstart/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.trimstart/tslint.json +++ b/lodash.trimstart/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.truncate/index.d.ts b/lodash.truncate/index.d.ts index b658478894..cb421e8a26 100644 --- a/lodash.truncate/index.d.ts +++ b/lodash.truncate/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { truncate } from "lodash"; export = truncate; diff --git a/lodash.truncate/tslint.json b/lodash.truncate/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.truncate/tslint.json +++ b/lodash.truncate/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unary/index.d.ts b/lodash.unary/index.d.ts index 55c5e46f1d..12a281f507 100644 --- a/lodash.unary/index.d.ts +++ b/lodash.unary/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { unary } from "lodash"; export = unary; diff --git a/lodash.unary/tslint.json b/lodash.unary/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unary/tslint.json +++ b/lodash.unary/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unescape/index.d.ts b/lodash.unescape/index.d.ts index c78fecec34..8340900768 100644 --- a/lodash.unescape/index.d.ts +++ b/lodash.unescape/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { unescape } from "lodash"; export = unescape; diff --git a/lodash.unescape/tslint.json b/lodash.unescape/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unescape/tslint.json +++ b/lodash.unescape/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.union/index.d.ts b/lodash.union/index.d.ts index 386967dec1..cddbaf12aa 100644 --- a/lodash.union/index.d.ts +++ b/lodash.union/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { union } from "lodash"; export = union; diff --git a/lodash.union/tslint.json b/lodash.union/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.union/tslint.json +++ b/lodash.union/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unionby/index.d.ts b/lodash.unionby/index.d.ts index dc0c0f1245..9c64ce9ed8 100644 --- a/lodash.unionby/index.d.ts +++ b/lodash.unionby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { unionBy } from "lodash"; export = unionBy; diff --git a/lodash.unionby/tslint.json b/lodash.unionby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unionby/tslint.json +++ b/lodash.unionby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unionwith/index.d.ts b/lodash.unionwith/index.d.ts index da2cae278a..a3757085ba 100644 --- a/lodash.unionwith/index.d.ts +++ b/lodash.unionwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { unionWith } from "lodash"; export = unionWith; diff --git a/lodash.unionwith/tslint.json b/lodash.unionwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unionwith/tslint.json +++ b/lodash.unionwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniq/index.d.ts b/lodash.uniq/index.d.ts index 675b710028..a274db1b67 100644 --- a/lodash.uniq/index.d.ts +++ b/lodash.uniq/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { uniq } from "lodash"; export = uniq; diff --git a/lodash.uniq/tslint.json b/lodash.uniq/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniq/tslint.json +++ b/lodash.uniq/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniqby/index.d.ts b/lodash.uniqby/index.d.ts index 0eedfb6d3f..c6dcd7c0c1 100644 --- a/lodash.uniqby/index.d.ts +++ b/lodash.uniqby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { uniqBy } from "lodash"; export = uniqBy; diff --git a/lodash.uniqby/tslint.json b/lodash.uniqby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniqby/tslint.json +++ b/lodash.uniqby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniqueid/index.d.ts b/lodash.uniqueid/index.d.ts index abd2ebf55c..046d62d775 100644 --- a/lodash.uniqueid/index.d.ts +++ b/lodash.uniqueid/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { uniqueId } from "lodash"; export = uniqueId; diff --git a/lodash.uniqueid/tslint.json b/lodash.uniqueid/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniqueid/tslint.json +++ b/lodash.uniqueid/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uniqwith/index.d.ts b/lodash.uniqwith/index.d.ts index 6541b4ef03..515bcc2cba 100644 --- a/lodash.uniqwith/index.d.ts +++ b/lodash.uniqwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { uniqWith } from "lodash"; export = uniqWith; diff --git a/lodash.uniqwith/tslint.json b/lodash.uniqwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uniqwith/tslint.json +++ b/lodash.uniqwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unset/index.d.ts b/lodash.unset/index.d.ts index dcf8e6881a..7662c3fd56 100644 --- a/lodash.unset/index.d.ts +++ b/lodash.unset/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { unset } from "lodash"; export = unset; diff --git a/lodash.unset/tslint.json b/lodash.unset/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unset/tslint.json +++ b/lodash.unset/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unzip/index.d.ts b/lodash.unzip/index.d.ts index 6fe3ebc759..60adfd32e9 100644 --- a/lodash.unzip/index.d.ts +++ b/lodash.unzip/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { unzip } from "lodash"; export = unzip; diff --git a/lodash.unzip/tslint.json b/lodash.unzip/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unzip/tslint.json +++ b/lodash.unzip/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.unzipwith/index.d.ts b/lodash.unzipwith/index.d.ts index 64f86e45e7..641d1c1468 100644 --- a/lodash.unzipwith/index.d.ts +++ b/lodash.unzipwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { unzipWith } from "lodash"; export = unzipWith; diff --git a/lodash.unzipwith/tslint.json b/lodash.unzipwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.unzipwith/tslint.json +++ b/lodash.unzipwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.update/index.d.ts b/lodash.update/index.d.ts index 27c5499aeb..f861786fd0 100644 --- a/lodash.update/index.d.ts +++ b/lodash.update/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { update } from "lodash"; export = update; diff --git a/lodash.update/tslint.json b/lodash.update/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.update/tslint.json +++ b/lodash.update/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.uppercase/index.d.ts b/lodash.uppercase/index.d.ts index 82e3f7af39..152bf80399 100644 --- a/lodash.uppercase/index.d.ts +++ b/lodash.uppercase/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { upperCase } from "lodash"; export = upperCase; diff --git a/lodash.uppercase/tslint.json b/lodash.uppercase/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.uppercase/tslint.json +++ b/lodash.uppercase/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.upperfirst/index.d.ts b/lodash.upperfirst/index.d.ts index 27cfc0bdc2..b76d75f8b6 100644 --- a/lodash.upperfirst/index.d.ts +++ b/lodash.upperfirst/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { upperFirst } from "lodash"; export = upperFirst; diff --git a/lodash.upperfirst/tslint.json b/lodash.upperfirst/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.upperfirst/tslint.json +++ b/lodash.upperfirst/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.values/index.d.ts b/lodash.values/index.d.ts index 633dbed76d..ff22e7ef36 100644 --- a/lodash.values/index.d.ts +++ b/lodash.values/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { values } from "lodash"; export = values; diff --git a/lodash.values/tslint.json b/lodash.values/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.values/tslint.json +++ b/lodash.values/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.valuesin/index.d.ts b/lodash.valuesin/index.d.ts index 1cca8a411d..9137156620 100644 --- a/lodash.valuesin/index.d.ts +++ b/lodash.valuesin/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { valuesIn } from "lodash"; export = valuesIn; diff --git a/lodash.valuesin/tslint.json b/lodash.valuesin/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.valuesin/tslint.json +++ b/lodash.valuesin/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.without/index.d.ts b/lodash.without/index.d.ts index 41a55ad642..88cea94b79 100644 --- a/lodash.without/index.d.ts +++ b/lodash.without/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { without } from "lodash"; export = without; diff --git a/lodash.without/tslint.json b/lodash.without/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.without/tslint.json +++ b/lodash.without/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.words/index.d.ts b/lodash.words/index.d.ts index 6b886a190f..8076cee94f 100644 --- a/lodash.words/index.d.ts +++ b/lodash.words/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { words } from "lodash"; export = words; diff --git a/lodash.words/tslint.json b/lodash.words/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.words/tslint.json +++ b/lodash.words/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.wrap/index.d.ts b/lodash.wrap/index.d.ts index 18ee43f769..ef1e41cb4c 100644 --- a/lodash.wrap/index.d.ts +++ b/lodash.wrap/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { wrap } from "lodash"; export = wrap; diff --git a/lodash.wrap/tslint.json b/lodash.wrap/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.wrap/tslint.json +++ b/lodash.wrap/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.xor/index.d.ts b/lodash.xor/index.d.ts index 6a641cd153..819ad96d72 100644 --- a/lodash.xor/index.d.ts +++ b/lodash.xor/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { xor } from "lodash"; export = xor; diff --git a/lodash.xor/tslint.json b/lodash.xor/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.xor/tslint.json +++ b/lodash.xor/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.xorby/index.d.ts b/lodash.xorby/index.d.ts index 49ef941467..a60b78d049 100644 --- a/lodash.xorby/index.d.ts +++ b/lodash.xorby/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { xorBy } from "lodash"; export = xorBy; diff --git a/lodash.xorby/tslint.json b/lodash.xorby/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.xorby/tslint.json +++ b/lodash.xorby/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.xorwith/index.d.ts b/lodash.xorwith/index.d.ts index 30b53691f9..ccf6499b89 100644 --- a/lodash.xorwith/index.d.ts +++ b/lodash.xorwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { xorWith } from "lodash"; export = xorWith; diff --git a/lodash.xorwith/tslint.json b/lodash.xorwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.xorwith/tslint.json +++ b/lodash.xorwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.zip/index.d.ts b/lodash.zip/index.d.ts index f4793f82ae..278d7a7cff 100644 --- a/lodash.zip/index.d.ts +++ b/lodash.zip/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { zip } from "lodash"; export = zip; diff --git a/lodash.zip/tslint.json b/lodash.zip/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.zip/tslint.json +++ b/lodash.zip/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.zipobject/index.d.ts b/lodash.zipobject/index.d.ts index df8d4929f9..63e4661ff6 100644 --- a/lodash.zipobject/index.d.ts +++ b/lodash.zipobject/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { zipObject } from "lodash"; export = zipObject; diff --git a/lodash.zipobject/tslint.json b/lodash.zipobject/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.zipobject/tslint.json +++ b/lodash.zipobject/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash.zipwith/index.d.ts b/lodash.zipwith/index.d.ts index e5b4a6714a..93c417ca57 100644 --- a/lodash.zipwith/index.d.ts +++ b/lodash.zipwith/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { zipWith } from "lodash"; export = zipWith; diff --git a/lodash.zipwith/tslint.json b/lodash.zipwith/tslint.json index 192203ab54..377cc837d4 100644 --- a/lodash.zipwith/tslint.json +++ b/lodash.zipwith/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lodash/index.d.ts b/lodash/index.d.ts index 678e0c58b9..00de563bbb 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -2,6 +2,7 @@ // Project: http://lodash.com/ // Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /** ### 4.0.0 Changelog (https://github.com/lodash/lodash/wiki/Changelog) @@ -68,7 +69,7 @@ added 23 array methods: - [x] _.xorBy - [x] _.xorWith -added 18 lang methods: +added 20 lang methods: - [x] _.cloneDeepWith - [x] _.cloneWith - [x] _.eq @@ -87,6 +88,8 @@ added 18 lang methods: - [x] _.toNumber - [x] _.toSafeInteger - [x] _.toString +- [X] _.conforms +- [X] _.conformsTo added 13 object methods: - [x] _.assignIn @@ -225,7 +228,6 @@ Methods: - [ ] _.split - [ ] _.cond -- [ ] _.conforms - [ ] _.nthArg - [ ] _.over - [ ] _.overEvery @@ -241,7 +243,10 @@ export as namespace _; declare var _: _.LoDashStatic; +type PartialObject = Partial; + declare namespace _ { + type Many = T | T[]; interface LoDashStatic { @@ -6558,9 +6563,9 @@ declare namespace _ { /** * @see _.every */ - every( + every( collection: List|Dictionary|NumericDictionary, - predicate?: TObject + predicate?: PartialObject ): boolean; } @@ -6582,8 +6587,8 @@ declare namespace _ { /** * @see _.every */ - every( - predicate?: TObject + every( + predicate?: PartialObject ): boolean; } @@ -6605,8 +6610,8 @@ declare namespace _ { /** * @see _.every */ - every( - predicate?: TObject + every( + predicate?: PartialObject ): boolean; } @@ -6628,8 +6633,8 @@ declare namespace _ { /** * @see _.every */ - every( - predicate?: TObject + every( + predicate?: PartialObject ): LoDashExplicitWrapper; } @@ -6651,8 +6656,8 @@ declare namespace _ { /** * @see _.every */ - every( - predicate?: TObject + every( + predicate?: PartialObject ): LoDashExplicitWrapper; } @@ -6708,9 +6713,9 @@ declare namespace _ { /** * @see _.filter */ - filter( + filter( collection: List|Dictionary, - predicate: W + predicate: PartialObject ): T[]; } @@ -6741,7 +6746,7 @@ declare namespace _ { /** * @see _.filter */ - filter(predicate: W): LoDashImplicitArrayWrapper; + filter(predicate: PartialObject): LoDashImplicitArrayWrapper; } interface LoDashImplicitObjectWrapper { @@ -6762,7 +6767,7 @@ declare namespace _ { /** * @see _.filter */ - filter(predicate: W): LoDashImplicitArrayWrapper; + filter(predicate: PartialObject): LoDashImplicitArrayWrapper; } interface LoDashExplicitWrapper { @@ -6792,7 +6797,7 @@ declare namespace _ { /** * @see _.filter */ - filter(predicate: W): LoDashExplicitArrayWrapper; + filter(predicate: PartialObject): LoDashExplicitArrayWrapper; } interface LoDashExplicitObjectWrapper { @@ -6813,7 +6818,7 @@ declare namespace _ { /** * @see _.filter */ - filter(predicate: W): LoDashExplicitArrayWrapper; + filter(predicate: PartialObject): LoDashExplicitArrayWrapper; } //_.find @@ -6863,9 +6868,9 @@ declare namespace _ { /** * @see _.find */ - find( + find( collection: List|Dictionary, - predicate?: TObject, + predicate?: PartialObject, fromIndex?: number ): T|undefined; } @@ -6890,8 +6895,8 @@ declare namespace _ { /** * @see _.find */ - find( - predicate?: TObject, + find( + predicate?: PartialObject, fromIndex?: number ): T|undefined; } @@ -6916,8 +6921,8 @@ declare namespace _ { /** * @see _.find */ - find( - predicate?: TObject, + find( + predicate?: PartialObject, fromIndex?: number ): TResult|undefined; } @@ -9204,9 +9209,9 @@ declare namespace _ { /** * @see _.some */ - some( + some( collection: List|Dictionary|NumericDictionary, - predicate?: TObject + predicate?: PartialObject ): boolean; /** @@ -9214,15 +9219,15 @@ declare namespace _ { */ some( collection: List|Dictionary|NumericDictionary, - predicate?: Object + predicate?: PartialObject ): boolean; /** * @see _.some */ - some( + some( collection: Object, - predicate?: TObject + predicate?: PartialObject ): boolean; } @@ -9244,8 +9249,8 @@ declare namespace _ { /** * @see _.some */ - some( - predicate?: TObject + some( + predicate?: PartialObject ): boolean; } @@ -9267,8 +9272,8 @@ declare namespace _ { /** * @see _.some */ - some( - predicate?: TObject + some( + predicate?: PartialObject ): boolean; } @@ -9290,8 +9295,8 @@ declare namespace _ { /** * @see _.some */ - some( - predicate?: TObject + some( + predicate?: PartialObject ): LoDashExplicitWrapper; } @@ -9313,8 +9318,8 @@ declare namespace _ { /** * @see _.some */ - some( - predicate?: TObject + some( + predicate?: PartialObject ): LoDashExplicitWrapper; } @@ -11432,6 +11437,33 @@ declare namespace _ { ): LoDashExplicitObjectWrapper; } + /** + * An object containing predicate functions for each property of T + */ + type ConformsPredicateObject = { + [P in keyof T]: (val: T[P]) => boolean; + }; + + //_.conforms + interface LoDashStatic { + /** + * Creates a function that invokes the predicate properties of `source` with the corresponding + * property values of a given object, returning true if all predicates return truthy, else false. + */ + conforms(source: ConformsPredicateObject): (Target: T) => boolean; + } + + //_.conformsTo + interface LoDashStatic { + /** + * Checks if object conforms to source by invoking the predicate properties of source with the + * corresponding property values of object. + * + * Note: This method is equivalent to _.conforms when source is partially applied. + */ + conformsTo(object: T, source: ConformsPredicateObject): boolean; + } + //_.eq interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index c1a5ca3e64..a2adf6ff8c 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -80,7 +80,7 @@ var keys: IKey[] = [ class Dog { constructor(public name: string) { } - public bark() { + bark() { console.log('Woof, woof!'); } } @@ -3530,49 +3530,49 @@ namespace TestEvery { result = _.every(array, listIterator); result = _.every(array, 'a'); result = _.every(array, ['a', 42]); - result = _.every<{a: number}, SampleObject>(array, {a: 42}); + result = _.every(array, {a: 42}); result = _.every(list); result = _.every(list, listIterator); result = _.every(list, 'a'); result = _.every(list, ['a', 42]); - result = _.every<{a: number}, SampleObject>(list, {a: 42}); + result = _.every(list, {a: 42}); result = _.every(dictionary); result = _.every(dictionary, dictionaryIterator); result = _.every(dictionary, 'a'); result = _.every(dictionary, ['a', 42]); - result = _.every<{a: number}, SampleObject>(dictionary, {a: 42}); + result = _.every(dictionary, {a: 42}); result = _.every(numericDictionary); result = _.every(numericDictionary, numericDictionaryIterator); result = _.every(numericDictionary, 'a'); result = _.every(numericDictionary, ['a', 42]); - result = _.every<{a: number}, SampleObject>(numericDictionary, {a: 42}); + result = _.every(numericDictionary, {a: 42}); result = _(array).every(); result = _(array).every(listIterator); result = _(array).every('a'); result = _(array).every(['a', 42]); - result = _(array).every<{a: number}>({a: 42}); + result = _(array).every({a: 42}); result = _(list).every(); result = _(list).every(listIterator); result = _(list).every('a'); result = _(list).every(['a', 42]); - result = _(list).every<{a: number}>({a: 42}); + result = _(list).every({a: 42}); result = _(dictionary).every(); result = _(dictionary).every(dictionaryIterator); result = _(dictionary).every('a'); result = _(dictionary).every(['a', 42]); - result = _(dictionary).every<{a: number}>({a: 42}); + result = _(dictionary).every({a: 42}); result = _(numericDictionary).every(); result = _(numericDictionary).every(numericDictionaryIterator); result = _(numericDictionary).every('a'); result = _(numericDictionary).every(['a', 42]); - result = _(numericDictionary).every<{a: number}>({a: 42}); + result = _(numericDictionary).every({a: 42}); } { @@ -3582,19 +3582,19 @@ namespace TestEvery { result = _(array).chain().every(listIterator); result = _(array).chain().every('a'); result = _(array).chain().every(['a', 42]); - result = _(array).chain().every<{a: number}>({a: 42}); + result = _(array).chain().every({a: 42}); result = _(list).chain().every(); result = _(list).chain().every(listIterator); result = _(list).chain().every('a'); result = _(list).chain().every(['a', 42]); - result = _(list).chain().every<{a: number}>({a: 42}); + result = _(list).chain().every({a: 42}); result = _(dictionary).chain().every(); result = _(dictionary).chain().every(dictionaryIterator); result = _(dictionary).chain().every('a'); result = _(dictionary).chain().every(['a', 42]); - result = _(dictionary).chain().every<{a: number}>({a: 42}); + result = _(dictionary).chain().every({a: 42}); result = _(numericDictionary).chain().every(); result = _(numericDictionary).chain().every(numericDictionaryIterator); @@ -3625,15 +3625,15 @@ namespace TestFilter { result = _.filter(array, listIterator); result = _.filter(array, ''); - result = _.filter<{a: number}, TResult>(array, {a: 42}); + result = _.filter(array, {a: 42}); result = _.filter(list, listIterator); result = _.filter(list, ''); - result = _.filter<{a: number}, TResult>(list, {a: 42}); + result = _.filter(list, {a: 42}); result = _.filter(dictionary, dictionaryIterator); result = _.filter(dictionary, ''); - result = _.filter<{a: number}, TResult>(dictionary, {a: 42}); + result = _.filter(dictionary, {a: 42}); } { @@ -3647,15 +3647,15 @@ namespace TestFilter { result = _(array).filter(listIterator); result = _(array).filter(''); - result = _(array).filter<{a: number}>({a: 42}); + result = _(array).filter({a: 42}); result = _(list).filter(listIterator); result = _(list).filter(''); - result = _(list).filter<{a: number}, TResult>({a: 42}); + result = _(list).filter({a: 42}); result = _(dictionary).filter(dictionaryIterator); result = _(dictionary).filter(''); - result = _(dictionary).filter<{a: number}, TResult>({a: 42}); + result = _(dictionary).filter({a: 42}); } { @@ -3669,15 +3669,15 @@ namespace TestFilter { result = _(array).chain().filter(listIterator); result = _(array).chain().filter(''); - result = _(array).chain().filter<{a: number}>({a: 42}); + result = _(array).chain().filter({a: 42}); result = _(list).chain().filter(listIterator); result = _(list).chain().filter(''); - result = _(list).chain().filter<{a: number}, TResult>({a: 42}); + result = _(list).chain().filter({a: 42}); result = _(dictionary).chain().filter(dictionaryIterator); result = _(dictionary).chain().filter(''); - result = _(dictionary).chain().filter<{a: number}, TResult>({a: 42}); + result = _(dictionary).chain().filter({a: 42}); } } @@ -3697,61 +3697,57 @@ namespace TestFind { result = _.find(array, listIterator, 1); result = _.find(array, ''); result = _.find(array, '', 1); - result = _.find<{a: number}, TResult>(array, {a: 42}); - result = _.find<{a: number}, TResult>(array, {a: 42}, 1); + result = _.find(array, {a: 42}); + result = _.find(array, {a: 42}, 1); result = _.find(list); result = _.find(list, listIterator); result = _.find(list, listIterator, 1); result = _.find(list, ''); result = _.find(list, '', 1); - result = _.find<{a: number}, TResult>(list, {a: 42}); - result = _.find<{a: number}, TResult>(list, {a: 42}, 1); + result = _.find(list, {a: 42}); + result = _.find(list, {a: 42}, 1); result = _.find(dictionary); result = _.find(dictionary, dictionaryIterator); result = _.find(dictionary, dictionaryIterator, 1); result = _.find(dictionary, ''); result = _.find(dictionary, '', 1); - result = _.find<{a: number}, TResult>(dictionary, {a: 42}); - result = _.find<{a: number}, TResult>(dictionary, {a: 42}, 1); + result = _.find(dictionary, {a: 42}); + result = _.find(dictionary, {a: 42}, 1); result = _(array).find(); result = _(array).find(listIterator); result = _(array).find(listIterator, 1); result = _(array).find(''); result = _(array).find('', 1); - result = _(array).find<{a: number}>({a: 42}); - result = _(array).find<{a: number}>({a: 42}, 1); + result = _(array).find({a: 42}); + result = _(array).find({a: 42}, 1); result = _(list).find(); result = _(list).find(listIterator); result = _(list).find(listIterator, 1); result = _(list).find(''); result = _(list).find('', 1); - result = _(list).find<{a: number}, TResult>({a: 42}); - result = _(list).find<{a: number}, TResult>({a: 42}, 1); + result = _(list).find({a: 42}); + result = _(list).find({a: 42}, 1); result = _(dictionary).find(); result = _(dictionary).find(dictionaryIterator); result = _(dictionary).find(dictionaryIterator, 1); result = _(dictionary).find(''); result = _(dictionary).find('', 1); - result = _(dictionary).find<{a: number}, TResult>({a: 42}); - result = _(dictionary).find<{a: number}, TResult>({a: 42}, 1); + result = _(dictionary).find({a: 42}); + result = _(dictionary).find({a: 42}, 1); } -result = _.findLast([1, 2, 3, 4], function (num) { - return num % 2 == 0; -}); +result = _.findLast([1, 2, 3, 4], num => num % 2 == 0); result = _.findLast(foodsCombined, { 'type': 'vegetable' }); result = _.findLast(foodsCombined, 'organic'); result = _.findLast(foodsCombined, 'organic', 1); -result = _([1, 2, 3, 4]).findLast(function (num) { - return num % 2 == 0; -}); +result = _([1, 2, 3, 4]).findLast(num => num % 2 == 0); result = _(foodsCombined).findLast({ 'type': 'vegetable' }); result = _(foodsCombined).findLast('organic'); @@ -4711,29 +4707,23 @@ namespace TestReduce { c: number; } - result = _.reduce([1, 2, 3], function (sum: number, num: number) { - return sum + num; - }); + result = _.reduce([1, 2, 3], (sum: number, num: number) => sum + num); // chained - result = _.chain([1, 2 ,3]).reduce(function (sum: number, num: number) { - return sum + num; - }).value(); + result = _.chain([1, 2 ,3]).reduce((sum: number, num: number) => sum + num).value(); - result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { + result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, (r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); - result = _([1, 2, 3]).reduce(function (sum: number, num: number) { - return sum + num; - }); - result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { + result = _([1, 2, 3]).reduce((sum: number, num: number) => sum + num); + result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce((r: ABC, num: number, key: string) => { r[key] = num * 3; return r; }, {}); - result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); + result = _.reduceRight([[0, 1], [2, 3], [4, 5]], (a: number[], b: number[]) => a.concat(b), []); } // _.reject namespace TestReject { @@ -5014,25 +5004,25 @@ namespace TestSome { result = _.some(array, listIterator); result = _.some(array, 'a'); result = _.some(array, ['a', 42]); - result = _.some<{a: number}, SampleObject>(array, {a: 42}); + result = _.some(array, {a: 42}); result = _.some(list); result = _.some(list, listIterator); result = _.some(list, 'a'); result = _.some(list, ['a', 42]); - result = _.some<{a: number}, SampleObject>(list, {a: 42}); + result = _.some(list, {a: 42}); result = _.some(dictionary); result = _.some(dictionary, dictionaryIterator); result = _.some(dictionary, 'a'); result = _.some(dictionary, ['a', 42]); - result = _.some<{a: number}, SampleObject>(dictionary, {a: 42}); + result = _.some(dictionary, {a: 42}); result = _.some(numericDictionary); result = _.some(numericDictionary, numericDictionaryIterator); result = _.some(numericDictionary, 'a'); result = _.some(numericDictionary, ['a', 42]); - result = _.some<{a: number}, SampleObject>(numericDictionary, {a: 42}); + result = _.some(numericDictionary, {a: 42}); result = _.some(sampleObject); result = _.some(sampleObject, objectIterator); @@ -5044,31 +5034,31 @@ namespace TestSome { result = _(array).some(listIterator); result = _(array).some('a'); result = _(array).some(['a', 42]); - result = _(array).some<{a: number}>({a: 42}); + result = _(array).some({a: 42}); result = _(list).some(); result = _(list).some(listIterator); result = _(list).some('a'); result = _(list).some(['a', 42]); - result = _(list).some<{a: number}>({a: 42}); + result = _(list).some({a: 42}); result = _(dictionary).some(); result = _(dictionary).some(dictionaryIterator); result = _(dictionary).some('a'); result = _(dictionary).some(['a', 42]); - result = _(dictionary).some<{a: number}>({a: 42}); + result = _(dictionary).some({a: 42}); result = _(numericDictionary).some(); result = _(numericDictionary).some(numericDictionaryIterator); result = _(numericDictionary).some('a'); result = _(numericDictionary).some(['a', 42]); - result = _(numericDictionary).some<{a: number}>({a: 42}); + result = _(numericDictionary).some({a: 42}); result = _(sampleObject).some(); result = _(sampleObject).some(objectIterator); result = _(sampleObject).some('a'); result = _(sampleObject).some(['a', 42]); - result = _(sampleObject).some<{a: number}>({a: 42}); + result = _(sampleObject).some({a: 42}); } { @@ -5078,31 +5068,31 @@ namespace TestSome { result = _(array).chain().some(listIterator); result = _(array).chain().some('a'); result = _(array).chain().some(['a', 42]); - result = _(array).chain().some<{a: number}>({a: 42}); + result = _(array).chain().some({a: 42}); result = _(list).chain().some(); result = _(list).chain().some(listIterator); result = _(list).chain().some('a'); result = _(list).chain().some(['a', 42]); - result = _(list).chain().some<{a: number}>({a: 42}); + result = _(list).chain().some({a: 42}); result = _(dictionary).chain().some(); result = _(dictionary).chain().some(dictionaryIterator); result = _(dictionary).chain().some('a'); result = _(dictionary).chain().some(['a', 42]); - result = _(dictionary).chain().some<{a: number}>({a: 42}); + result = _(dictionary).chain().some({a: 42}); result = _(numericDictionary).chain().some(); result = _(numericDictionary).chain().some(numericDictionaryIterator); result = _(numericDictionary).chain().some('a'); result = _(numericDictionary).chain().some(['a', 42]); - result = _(numericDictionary).chain().some<{a: number}>({a: 42}); + result = _(numericDictionary).chain().some({a: 42}); result = _(sampleObject).chain().some(); result = _(sampleObject).chain().some(objectIterator); result = _(sampleObject).chain().some('a'); result = _(sampleObject).chain().some(['a', 42]); - result = _(sampleObject).chain().some<{a: number}>({a: 42}); + result = _(sampleObject).chain().some({a: 42}); } } @@ -5173,9 +5163,9 @@ namespace TestSortBy { } } -result = _.sortBy(stoogesAges, function(stooge) { return Math.sin(stooge.age); }, function(stooge) { return stooge.name.slice(1); }); +result = _.sortBy(stoogesAges, stooge => Math.sin(stooge.age), stooge => stooge.name.slice(1)); result = _.sortBy(stoogesAges, ['name', 'age']); -result = _.sortBy(stoogesAges, 'name', function(stooge) { return Math.sin(stooge.age); }); +result = _.sortBy(stoogesAges, 'name', stooge => Math.sin(stooge.age)); result = _(foodsOrganic).sortBy('organic', (food) => food.name, { organic: true }).value(); @@ -6017,7 +6007,7 @@ namespace TestOnce { } } -var greetPartial = function (greeting: string, name: string) { return greeting + ' ' + name; }; +var greetPartial = (greeting: string, name: string) => greeting + ' ' + name; var hi = _.partial(greetPartial, 'hi'); hi('moe'); @@ -6488,6 +6478,18 @@ namespace TestCloneWith { } } +// _.conforms +namespace TestConforms { + let result: boolean = _.conforms({foo: (v: string) => false})({foo: "foo"}); + let result2: boolean = _.conforms({})({foo: "foo"}); +} + +// _.conformsTo +namespace TestConformsTo { + let result: boolean = _.conformsTo({foo: "foo"}, {foo: (v: string) => false}); + let result2: boolean = _.conformsTo({}, {foo: (v: string) => false}); +} + // _.eq namespace TestEq { let customizer: (value: any, other: any, indexOrKey?: number|string) => boolean; @@ -7463,7 +7465,7 @@ namespace TestIsWeakMap { } // _.isWeakSet -module TestIsWeakSet { +namespace TestIsWeakSet { { let value: number|WeakSet; @@ -8608,7 +8610,7 @@ namespace TestDefaults { let s5: S5; { - let result: Obj; + let result: Obj; result = _.defaults(obj); } @@ -10484,7 +10486,7 @@ namespace TestValuesIn { let result: TResult[]; // Without this type hint, this will fail to compile, as expected. - result = _.valuesIn(new Object); + result = _.valuesIn({}); } { @@ -11693,7 +11695,7 @@ namespace TestNoConflict { // _.noop namespace TestNoop { { - let result: void; + let result: void; // tslint:disable-line:void-return result = _.noop(); result = _.noop(1); diff --git a/lodash/meanBy/index.d.ts b/lodash/meanBy/index.d.ts index 3004930ef6..e4651a4412 100644 --- a/lodash/meanBy/index.d.ts +++ b/lodash/meanBy/index.d.ts @@ -1,3 +1,2 @@ -import * as _ from "../index"; -declare const meanBy: typeof _.meanBy; -export = meanBy; +import { meanBy } from "../index"; +export = meanBy; \ No newline at end of file diff --git a/lodash/scripts/generate-modules.ts b/lodash/scripts/generate-modules.ts index 127f1f44c6..395bb7ab4d 100644 --- a/lodash/scripts/generate-modules.ts +++ b/lodash/scripts/generate-modules.ts @@ -1,16 +1,124 @@ -// Usage: ts-node generate-modules +// Usage: ts-node generate-modules.ts /// import * as fs from "fs"; +import { get, STATUS_CODES } from "http"; +import * as path from "path"; -for (const module of allModuleNames()) { - if (!fs.existsSync(module)) { - fs.mkdirSync(module); +main().catch(console.error); + +async function main() { + const all = new Set(allModuleNames()); + const notOnNpm = new Set(modulesNotOnNpm()); + for (const n of notOnNpm) { + if (!all.has(n)) { + throw new Error(n); + } + } + + for (const module of all) { + console.log(module); + + // Generate local module + const localDir = path.join("..", module); + ensureDir(localDir); + fs.writeFileSync(path.join(localDir, "index.d.ts"), `import { ${module} } from "../index";\nexport = ${module};`); + + // Generate non-local module + if (!notOnNpm.has(module)) { + const dir = path.join("..", "..", `lodash.${module.toLowerCase()}`); + ensureDir(dir); + fs.writeFileSync(path.join(dir, "index.d.ts"), await globalDefinitionText(module)); + fs.writeFileSync(path.join(dir, "tsconfig.json"), tsconfig()); + fs.writeFileSync(path.join(dir, "tslint.json"), tslint()); + } } - fs.writeFileSync(`${module}/index.d.ts`, `import { ${module} } from "../index";\nexport = ${module};`); } +function ensureDir(dir: string) { + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir); + } +} + +async function globalDefinitionText(moduleName: string): Promise { + const fullName = "lodash." + moduleName; + const url = `http://registry.npmjs.org/${fullName.toLowerCase()}`; + const npmInfo = JSON.parse(await loadString(url)); + const fullVersion = npmInfo["dist-tags"].latest; + const majorMinor = fullVersion.split(".").slice(0, 2).join("."); + + return ` +// Type definitions for ${fullName} ${majorMinor} +// Project: http://lodash.com/ +// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { ${moduleName} } from "lodash"; +export = ${moduleName}; +`.trim() + "\n"; +} + +function tsconfig() { + return JSON.stringify({ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } + }, undefined, 4); +} + +function tslint() { + return JSON.stringify({ + "extends": "../tslint.json" + }, undefined, 4); +} + + +function loadString(url: string): Promise { + return new Promise((resolve, reject) => { + get(url, (res) => { + if (res.statusCode !== 200) { + return reject(new Error(`HTTP Error ${res.statusCode}: ${STATUS_CODES[res.statusCode || 500]} for ${url}`)) + } + let rawData = "" + res.on("data", chunk => rawData += chunk) + res.on("end", () => resolve(rawData)) + }).on("error", e => reject(e)) + }) +} + +function modulesNotOnNpm() { + return [ + "chain", + "each", + "eachRight", + "extend", + "extendWith", + "noConflict", + "runInContext", + "tap", + "thru", + ]; +} + +// Note: "fb" is not a usual module, so it is made by hand. + function allModuleNames() { return [ "add", @@ -66,7 +174,6 @@ function allModuleNames() { "every", "extend", "extendWith", - "fb", "fill", "filter", "find", diff --git a/lodash/scripts/tsconfig.json b/lodash/scripts/tsconfig.json new file mode 100644 index 0000000000..a06b8ed24f --- /dev/null +++ b/lodash/scripts/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "es6", + "baseUrl": "../..", + "typeRoots": [ + "../../" + ], + "types": [] + } +} \ No newline at end of file diff --git a/lodash/tslint.json b/lodash/tslint.json index 8bcd32b3b1..62d13dc883 100644 --- a/lodash/tslint.json +++ b/lodash/tslint.json @@ -1,8 +1,21 @@ { "extends": "../tslint.json", "rules": { + "array-type": false, + "callable-types": false, + "comment-format": false, "forbidden-types": false, + "interface-name": false, + "interface-over-type-literal": false, + "max-line-length": false, "no-empty-interface": false, - "unified-signatures": false + "object-literal-key-quotes": false, + "one-line": false, + "prefer-const": false, + "semicolon": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "whitespace": false } -} \ No newline at end of file +} diff --git a/loopback-boot/index.d.ts b/loopback-boot/index.d.ts index 4c66af5ef8..93e912363e 100644 --- a/loopback-boot/index.d.ts +++ b/loopback-boot/index.d.ts @@ -17,35 +17,35 @@ import * as loopback from "loopback"; * ``` * var loopback= require('loopback'); * var boot = require('loopback-boot'); - * + * * var app = module.exports = loopback(); - * + * * boot(app, __dirname); - * + * * ``` - * + * * Initialize an application from an options object or a set of JSON and JavaScript files. - * - * NOTE: This module is primarily intended for use with LoopBack 2.0. It does work with LoopBack 1.x applications, + * + * NOTE: This module is primarily intended for use with LoopBack 2.0. It does work with LoopBack 1.x applications, * but none of the LoopBack 1.x examples or generated code (scaffolding) use it. - * + * * This function takes an optional argument that is either a string or an object. - * + * * If the argument is a string, then it sets the application root directory based on the string value. Then it: * Creates DataSources from the datasources.json file in the application root directory. - * + * * Configures Models from the model-config.json file in the application root directory. - * - * Configures the LoopBack Application object from the config.json file in the application root directory. + * + * Configures the LoopBack Application object from the config.json file in the application root directory. * These properties can be accessed using app.get('propname'). - * + * * If the argument is an object, then it looks for models, dataSources, 'config', modelsRootDir, dsRootDir, * appConfigRootDir and appRootDir properties of the object. - * + * * If the object has no appRootDir property then it sets the current working directory as the application root directory. - * + * * The execution environment, {env}, is established from, in order, - * + * * options.env * process.env.NODE_ENV, * the literal development. @@ -64,20 +64,21 @@ import * as loopback from "loopback"; * config.json, * config.local.js or config.local.json (only one), * config.{env}.js or config.{env}.json (only one) - * + * * in the directory designated by 'options.appConfigRootDir', if present, or the application root directory. * It merges the properties from the files found. - * - * In both cases, the function loads JavaScript files in the /boot subdirectory of the application root directory + * + * In both cases, the function loads JavaScript files in the /boot subdirectory of the application root directory * with require(). - * + * * NOTE: The version 2.0 of loopback-boot changed the way how models are created. - * The model-config.json file contains only configuration options like dataSource and extra relations. + * The model-config.json file contains only configuration options like dataSource and extra relations. * To define a model, create a per-model JSON file in models/ directory. - * - * NOTE: Mixing bootLoopBackApp(app, bootConfig) and app.model(name, modelConfig) in multiple files may result in models being undefined due to race conditions. To avoid this when using bootLoopBackApp() make sure all models are passed as part of the models definition. + * + * NOTE: Mixing bootLoopBackApp(app, bootConfig) and app.model(name, modelConfig) in multiple files may result in models being undefined due to race conditions. + * To avoid this when using bootLoopBackApp() make sure all models are passed as part of the models definition. * Throws an error if the config object is not valid or if boot fails. - * + * * @param {Loopback.LoopbackApplication} app LoopBack application created by loopback(). * @param {string|OptionsLB} options Boot options; If String, this is the application root directory; if object, has below properties. * @param {() => void} callback @@ -87,13 +88,13 @@ declare function lb(app: loopback.LoopBackApplication, options: string|OptionsLB interface OptionsLB { /** - * Directory to use when loading JSON and JavaScript files. + * Directory to use when loading JSON and JavaScript files. * Defaults to the current directory (process.cwd()). */ appRootDir: string; /** - * Directory to use when loading config.json. Defaults to appRootDir. + * Directory to use when loading config.json. Defaults to appRootDir. */ appConfigRootDir: string; @@ -103,7 +104,7 @@ interface OptionsLB { models: any; /** - * List of model definitions to use. When options.modelDefinitions is provided, + * List of model definitions to use. When options.modelDefinitions is provided, * loopback-boot does not search filesystem and use only the models provided in this argument. */ modelDefinitions: any[]; @@ -134,8 +135,8 @@ interface OptionsLB { componentRootDir: string; /** - * Environment type, defaults to process.env.NODE_ENV or development. - * Common values are development, staging and production; + * Environment type, defaults to process.env.NODE_ENV or development. + * Common values are development, staging and production; * however the applications are free to use any names. */ env: string; @@ -156,7 +157,7 @@ interface OptionsLB { components: any; /** - * List of directories where to look for files containing model mixin definitions. + * List of directories where to look for files containing model mixin definitions. * All files (mixins) found in these directory are loaded. */ mixinDirs: string[]; @@ -187,7 +188,7 @@ declare namespace lb { /** * compileToBrowserify - * + * * Compile boot instructions and add them to a browserify bundler. * @param {string|any} options as described in bootLoopBackApp above. * @param {any} bundler A browserify bundler created by browserify(). @@ -198,7 +199,7 @@ declare namespace lb { class compileToBrowserify { /** - * Application identifier used to load the correct boot configuration when + * Application identifier used to load the correct boot configuration when * building multiple applications using browserify. */ appId: string; diff --git a/loopback-boot/loopback-boot-tests.ts b/loopback-boot/loopback-boot-tests.ts index 75a0bf2ca5..4885fca1d0 100644 --- a/loopback-boot/loopback-boot-tests.ts +++ b/loopback-boot/loopback-boot-tests.ts @@ -1,4 +1,3 @@ -/// import * as loopback from 'loopback'; import * as boot from 'loopback-boot'; import * as cookieParser from 'cookie-parser'; diff --git a/loopback-boot/tslint.json b/loopback-boot/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/loopback-boot/tslint.json +++ b/loopback-boot/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/loopback/index.d.ts b/loopback/index.d.ts index 64aac97c92..ccfc270e10 100644 --- a/loopback/index.d.ts +++ b/loopback/index.d.ts @@ -88,7 +88,7 @@ declare namespace l { * @returns {any} http.Server A node `http.Server` with this application configured * as the request handle * listen(cb?: () => void):http.Serve - * + * */ // listen(port?: number, cb?: () => void): any; @@ -203,16 +203,16 @@ declare namespace l { /** * Register (new) middleware phases. - * + * * If all names are new, then the phases are added just before "routes" phase. * Otherwise the provided list of names is merged with the existing phases * in such way that the order of phases is preserved - * + * * **Examples* * ```js * // built-in phases: * // initial, session, auth, parse, routes, files, fina - * + * * app.defineMiddlewarePhases('custom'); * // new list of phases * // initial, session, auth, parse, custom, routes, files, fina @@ -340,7 +340,7 @@ declare namespace l { * In the second variant, the parameters `name`, `properties` and `options` * are provided in the config object. Any additional config entries are * interpreted as `options`, i.e. the following two configs are identical - * + * * ```js * { name: 'Customer', base: 'User' } * { name: 'Customer', options: { base: 'User' } } @@ -792,7 +792,7 @@ declare namespace l { * // => model with id 1 has been changed * }); * `` - * + * * #### Event: `deleted * Emitted after an individual model has been deleted. * Argument: `id`, model ID (number) @@ -803,7 +803,7 @@ declare namespace l { * }); * `` * #### Event: `deletedAll - * + * * Emitted after an individual model has been deleted. * Argument: `where` (optional), where filter, JSON object * ```js @@ -816,7 +816,7 @@ declare namespace l { * } * }); * `` - * + * * #### Event: `attached * Emitted after a `Model` has been attached to an `app` * #### Event: `dataSourceAttached @@ -830,7 +830,7 @@ declare namespace l { * // => model with id 1 has been changed * }); * `` - * + * * @param {any} data * @property {string} Model.modelName The name of the model. Static property. * @property {DataSource} Model.dataSource Data source to which the model is connected, if any. Static property. @@ -912,8 +912,15 @@ declare namespace l { * @param {any} SharedMethod object. See [here](apidocs.strongloop.com/strong-remoting/#sharedmethod). * @param {any} RelationDefinition object which includes relation `type`, `ModelConstructor` of `modelFrom`, `modelTo`, `keyFrom`, `keyTo` and more relation definitions */ - - static nestRemoting(relationName: string, pathName: string, filterMethod: string, paramName: string, getterName: string, hooks: boolean, options?: {}, filterCallback?: (SharedMethod: any, RelationDefinition: any) => void): void; + static nestRemoting( + relationName: string, + pathName: string, + filterMethod: string, + paramName: string, + getterName: string, + hooks: boolean, + options?: {}, + filterCallback?: (SharedMethod: any, RelationDefinition: any) => void): void; /** * Enable remote invocation for the specified method. @@ -943,12 +950,12 @@ declare namespace l { * SharedClass * Create a new SharedClass with the given options. * **NOTE** TODO : exported from another module type definition called strong-remoting - * + * * @param {string} name The SharedClass name * @param {() => void} constructor The constructor the SharedClass represents * @param {any} options Additional options. * @property {() => void } ctor The constructor - * @property {any} http The HTTP settings + * @property {any} http The HTTP settings */ class SharedClass { @@ -1013,7 +1020,7 @@ declare namespace l { /** * Get all shared methods belonging to this shared class. - * @param {any} options + * @param {any} options * @return {any[]} An array of shared methods SharedMethod[] */ @@ -1034,7 +1041,7 @@ declare namespace l { * cb(null, str); * } * ``` - * + * * @param {() => void} resolver The resolver function. */ @@ -1053,7 +1060,7 @@ declare namespace l { * **Change Event* * Listen for model changes using the `change` event * ```js - * MyPersistedModel.on('changed', function(obj) + * MyPersistedModel.on('changed', function(obj) * console.log(obj) // => the changed model * }); * ``` @@ -1116,10 +1123,10 @@ declare namespace l { static create(data?: any|any[], callback?: (err: Error, models: any) => void): void; - /** + /** * Create a change stream. See here for more info http://loopback.io/doc/en/lb2/Realtime-server-sent-events.html * @param {any} options Only changes to models matching this where filter will be included in the ChangeStream. - * @param {() => void} callback + * @param {() => void} callback */ static createChangeStream(options: {where: any}, callback: (err: Error, changes: any) => void): void; @@ -1150,7 +1157,7 @@ declare namespace l { * ``` *
See * [Where filter](docs.strongloop.com/display/LB/Where+filter#Wherefilter-Whereclauseforothermethods) - * + * * @callback {() => void} callback Optional callback function called with `(err, info)` arguments. * @param {Error} err Error object; see [Error object](docs.strongloop.com/display/LB/Error+object). * @param {any} info Additional information about the command outcome. @@ -1220,8 +1227,9 @@ declare namespace l { * @param {Error} err Error object; see [Error object](docs.strongloop.com/display/LB/Error+object). * @param {Array} models Model instances matching the filter, or null if none found */ - - static find(filter?: {fields?: string|any|any[]; include?: string|any|any[]; limit?: number; order?: string; skip?: number; where?: any; }, callback?: (err: Error, models: any[]) => void): void; + static find( + filter?: {fields?: string|any|any[]; include?: string|any|any[]; limit?: number; order?: string; skip?: number; where?: any; }, + callback?: (err: Error, models: any[]) => void): void; /** * Find object by ID with an optional filter for include/fields @@ -1270,7 +1278,7 @@ declare namespace l { * the same as `find`, but limited to one object. Returns an object, not * collection. If you don't provide the filter object argument, it tries to * locate an existing object that matches the `data` argument - * + * * @options {any} [filter] Optional Filter object; see below. * @property {string|any|Array} fields Identify fields to include in return result. *
See [Fields filter](docs.strongloop.com/display/LB/Fields+filter). @@ -1295,7 +1303,17 @@ declare namespace l { * @param {boolean} created True if the instance matching the `where` filter was created */ - static findOrCreate(data: any, filter?: {fields?: string|any|any[]; include?: string|any|any[]; limit?: number; order?: string; skip?: number; where?: any; }, callback?: (err: Error, instance: any, created: boolean) => void): void; + static findOrCreate( + data: any, + filter?: { + fields?: string | any | any[]; + include?: string | any | any[]; + limit?: number; + order?: string; + skip?: number; + where?: any; + }, + callback?: (err: Error, instance: any, created: boolean) => void): void; /** * Get the `Change` model. @@ -1627,7 +1645,7 @@ declare namespace l { function static(root: string, options: any): void; /** - * Return HTTP response with basic application status information: + * Return HTTP response with basic application status information: * date the application was started and uptime, in JSON format. For example: * ``` * { @@ -1651,7 +1669,7 @@ declare namespace l { * - `access_token` (params only) * - `X-Access-Token` (headers only) * - `authorization` (headers and cookies - * + * * It checks for these values in cookies, headers, and query string parameters _in addition_ to the items * specified in the options parameter * **NOTE:** This function only checks for [signed cookies](expressjs.com/api.html#req.signedCookies) @@ -1664,7 +1682,7 @@ declare namespace l { * params: ['foo-auth', 'foo_auth'] * })); * ``` - * + * * @options {any} [options] Each option Array is used to add additional keys to find an `accessToken` for a `request`. * @property {Array} [cookies] Array of cookie names. * @property {Array} [headers] Array of header names. @@ -1676,8 +1694,17 @@ declare namespace l { * @property {string} [currentUserLiteral] string literal for the current user. * @header loopback.token([options]) */ - - function token(options?: {cookies?: any[], headers?: any[], params?: any[], searchDefaultTokenKeys?: boolean, enableDoublecheck?: boolean, overwriteExistingToken?: boolean, model?: () => void|string, currentUserLiteral?: string}): void; + function token( + options?: { + cookies?: any[], + headers?: any[], + params?: any[], + searchDefaultTokenKeys?: boolean, + enableDoublecheck?: boolean, + overwriteExistingToken?: boolean, + model?: () => void|string, + currentUserLiteral?: string + }): void; /** * Convert any request not handled so far to a 404 error @@ -1985,7 +2012,7 @@ declare namespace l { * pushSettings.apns.feedbackOptions.port (APNS). * pushSettings.apns.feedbackOptions.batchFeedback (APNS). * pushSettings.apns.feedbackOptions.interval (APNS). - * pushSettings.gcm.serverApiKey: Google Cloud Messaging API key. + * pushSettings.gcm.serverApiKey: Google Cloud Messaging API key. */ pushSetings: { apns: { @@ -2091,7 +2118,7 @@ declare namespace l { /** Model ID. */ modelId: string; - /** + /** * settings Extends the `Model.settings` object. * settings.hashAlgorithm Algorithm used to create cryptographic hash, used as argument * to [crypto.createHash](nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm).Default is sha1. @@ -2260,7 +2287,7 @@ declare namespace l { /** * When two changes conflict a conflict is created * **Note**: call `conflict.fetch()` to get the `target` and `source` models - * + * * @param {*} modelId * @param {PersistedModel} SourceModel * @param {PersistedModel} TargetModel @@ -2337,7 +2364,7 @@ declare namespace l { * Return a new Conflict instance with swapped Source and Target models * This is useful when resolving a conflict in one-way * replication, where the source data must not be changed - * + * * ```js * conflict.swapParties().resolveUsingTarget(cb); * ``` @@ -2349,11 +2376,11 @@ declare namespace l { /** * Determine the conflict type * Possible results ar - * + * * - `Change.UPDATE`: Source and target models were updated * - `Change.DELETE`: Source and or target model was deleted. * - `Change.UNKNOWN`: the conflict type is uknown or due to an erro - * + * * @callback {() => void} callback * @param {Error} err * @param {string} type The conflict type @@ -2402,7 +2429,7 @@ declare namespace l { * } * `` * See github.com/andris9/Nodemailer for other supported options - * + * * @options {any} options See below * @prop {string} from Senders's email address * @prop {string} to List of one or more recipient email addresses (comma-delimited) @@ -2424,19 +2451,19 @@ declare namespace l { /** * Data model for key-value databases. - * @class + * @class */ class KeyValueModel { /** - * Set the TTL (time to live) in ms (milliseconds) for a given key. + * Set the TTL (time to live) in ms (milliseconds) for a given key. * TTL is the remaining time before a key-value pair is discarded from the database. - * - * Callback (Optional) Optional callback. + * + * Callback (Optional) Optional callback. * When the callback function is not provided, a promise is returned instead (see below). - * - * Promise - * this method supports both callback-based and promise-based invocation. + * + * Promise + * this method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead. * @param {string} key Key to use when searching the database. * @param {number} ttl TTL in ms to set for the key. @@ -2448,14 +2475,14 @@ declare namespace l { /** * Return the value associated with a given key. - * + * * Callback (Optional) * Optional callback. When the callback function is not provided, a promise is returned instead (see below). - * + * * Promise - * This method supports both callback-based and promise-based invocation. + * This method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead. - * + * * @param {string} key Key to use when searching the database. * @param {any} options * @param {() => void} callback @@ -2464,8 +2491,8 @@ declare namespace l { static get(key: string, option?: any, callback?: (err: Error, result: any) => void): PromiseLike; /** - * Asynchronously iterate all keys in the database. Similar to .keys() - * but instead allows for iteration over large data sets without having + * Asynchronously iterate all keys in the database. Similar to .keys() + * but instead allows for iteration over large data sets without having * to load everything into memory at once. * Callback example: * ``` @@ -2478,7 +2505,7 @@ declare namespace l { * }); * }); * ``` - * + * * Promise example: * ``` * // Given a model named `Color` with two keys `red` and `blue` @@ -2494,10 +2521,10 @@ declare namespace l { * // key contains `blue` * }); * ``` - * + * * @param {any} filter An optional filter object with the following * @param {string} filter.match Glob string to use to filter returned keys (i.e. userid.*). - * All connectors are required to support * and ?. + * All connectors are required to support * and ?. * They may also support additional special characters that are specific to the backing database. * @param {any} filter.options * @return {any} result AsyncIterator An Object implementing next(cb) -> Promise function that can be used to iterate all keys. @@ -2509,33 +2536,33 @@ declare namespace l { * Return all keys in the database. * WARNING: This method is not suitable for large data sets as all key-values pairs * are loaded into memory at once. For large data sets, use iterateKeys() instead. - * - * This method supports both callback-based and promise-based invocation. + * + * This method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead - * + * * WARNING: this promise implementation will not resolve according to the callback function. - * + * * @param {any} filter An optional filter object with the following - * @param {string} filter.match Glob string used to filter returned keys (i.e. userid.*). - * All connectors are required to support * and ?, but may also support additional special + * @param {string} filter.match Glob string used to filter returned keys (i.e. userid.*). + * All connectors are required to support * and ?, but may also support additional special * characters specific to the database. - * @param {any} filter.options + * @param {any} filter.options * @param {() => void} callback - * @return {PromiseLike} + * @return {PromiseLike} */ static keys(filter: {match: string; options: any}, callback: () => void): PromiseLike; /** * Persist a value and associate it with the given key. - * + * * Callback (Optional) * Optional callback. When the callback function is not provided, a promise is returned instead (see below). - * + * * Promise - * This method supports both callback-based and promise-based invocation. + * This method supports both callback-based and promise-based invocation. * Call this method with no callback argument to get back a promise instead. - * + * * @param {string} key Key to associate with the given value. * @param {any} value Value to persist. * @param {number|any} Optional settings for the key-value pair. If a Number is provided, it is set as the TTL (time to live) in ms (milliseconds) for the key-value pair. @@ -2545,15 +2572,15 @@ declare namespace l { static set(key: string, value: any, options?: number|any, callback?: (err: Error) => void): PromiseLike; /** - * Return the TTL (time to live) for a given key. + * Return the TTL (time to live) for a given key. * TTL is the remaining time before a key-value pair is discarded from the database. - * + * * Callback (Optional) - * Optional callback. When the callback function is not provided, + * Optional callback. When the callback function is not provided, * a promise is returned instead (see below). - * + * * @param {string} key Key to use when searching the database. - * @param {any} options + * @param {any} options * @param {() => void} callback */ @@ -2702,7 +2729,7 @@ declare namespace l { * - ALLOW EVERYONE `logout` * - ALLOW OWNER `findById` * - ALLOW OWNER `updateAttributes` - * + * * @property {string} username Must be unique. * @property {string} password Hidden from remote clients. * @property {string} email Must be valid email. @@ -2724,7 +2751,7 @@ declare namespace l { * @property {number} settings.resetPasswordTokenTTL Time to live for password reset `AccessToken`. Default is `900` (15 minutes). * @property {number} settings.saltWorkFactor The `bcrypt` salt work factor. Default is `10`. * @property {boolean} settings.caseSensitiveEmail Enable case sensitive email. - * + * * @class User * @inherits {PersistedModel} */ @@ -2771,7 +2798,18 @@ declare namespace l { * settings.saltWorkFactor The `bcrypt` salt work factor. Default is `10`. * settings.caseSensitiveEmail Enable case sensitive email. */ - settings: { http: { path: string }; acls: ACL; emailVerificationRequired: boolean; ttl: number; maxTTL: number; realmRequired: boolean; realmDelimiter: string; resetPasswordTokenTTL: number; saltWorkFactor: number; caseSensitiveEmail: boolean; }; + settings: { + http: { path: string }; + acls: ACL; + emailVerificationRequired: boolean; + ttl: number; + maxTTL: number; + realmRequired: boolean; + realmDelimiter: string; + resetPasswordTokenTTL: number; + saltWorkFactor: number; + caseSensitiveEmail: boolean; + }; /** * Confirm the user's identity @@ -2798,13 +2836,13 @@ declare namespace l { /** * Login a user by with the given `credentials` - * + * * ```js * User.login({username: 'foo', password: 'bar'}, function (err, token) { * console.log(token.id); * }); * ``` - * + * * @param {any} credentials username/password or email/password * @param {string[]|string} [include] Optionally set it to "user" to include * the user info @@ -2817,13 +2855,13 @@ declare namespace l { /** * Logout a user with the given accessToken id - * + * * ```js * User.logout('asd0a9f8dsj9s0s3223mk', function (err) { * console.log(err || 'Logged out'); * }); * ``` - * + * * @param {string} accessTokenID * @callback {() => void} callback * @param {Error} er @@ -2884,10 +2922,10 @@ declare namespace l { * redirect: '/', * tokenGenerator: function (user, cb) { cb("random-token"); } * }; - * + * * user.verify(options, next); * ``` - * + * * @options {any} options * @property {string} type Must be 'email'. * @property {string} to Email address to which verification email is sent. diff --git a/loopback/loopback-tests.ts b/loopback/loopback-tests.ts index 0c05a377df..b21bf8c759 100644 --- a/loopback/loopback-tests.ts +++ b/loopback/loopback-tests.ts @@ -1,4 +1,3 @@ -/// import * as loopback from 'loopback'; import * as cookieParser from 'cookie-parser'; @@ -13,7 +12,7 @@ class Server { this.app.use(cookieParser()); - this.app.start = function() { + this.app.start = () => { // start the web server }; } diff --git a/loopback/tslint.json b/loopback/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/loopback/tslint.json +++ b/loopback/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/lorem-ipsum/index.d.ts b/lorem-ipsum/index.d.ts new file mode 100644 index 0000000000..0a2210c0d8 --- /dev/null +++ b/lorem-ipsum/index.d.ts @@ -0,0 +1,65 @@ +// Type definitions for lorem-ipsum 1.0 +// Project: https://github.com/knicklabs/node-lorem-ipsum +// Definitions by: Dusan Radovanovic +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface LoremIpsumOptions { + /** + * Number of words, sentences, or paragraphs to generate. + */ + count?: number; + + /** + * Generate words, sentences, or paragraphs. + */ + units?: 'words' | 'sentences' | 'paragraphs'; + + /** + * Minimum words per sentence. + */ + sentenceLowerBound?: number; + + /** + * Maximum words per sentence. + */ + sentenceUpperBound?: number; + + /** + * Minimum sentences per paragraph. + */ + paragraphLowerBound?: number; + + /** + * Maximum sentences per paragraph. + */ + paragraphUpperBound?: number; + + /** + * Plain text or html. + */ + format?: 'plain' | 'html'; + + /** + * Custom word dictionary. + */ + words?: string[]; + + /** + * A PRNG function. Uses Math.random by default. + */ + random?: () => number; + + /** + * The character to insert between paragraphs. Defaults to default EOL. + */ + suffix?: string; +} + +declare namespace loremIpsum {} + +/** + * Generate a passage of lorem ipsum text. + */ +declare function loremIpsum(options?: LoremIpsumOptions): string; + +export = loremIpsum; diff --git a/lorem-ipsum/lorem-ipsum-tests.ts b/lorem-ipsum/lorem-ipsum-tests.ts new file mode 100644 index 0000000000..697c222257 --- /dev/null +++ b/lorem-ipsum/lorem-ipsum-tests.ts @@ -0,0 +1,14 @@ +import * as loremIpsum from 'lorem-ipsum'; + +let result: string; +result = loremIpsum(); +result = loremIpsum({}); +result = loremIpsum({ count: 20 }); +result = loremIpsum({ count: 20, units: 'words' }); +result = loremIpsum({ count: 3, units: 'paragraphs' }); +result = loremIpsum({ random: () => Math.random() * Math.random() }); +result = loremIpsum({ paragraphLowerBound: 3, paragraphUpperBound: 6, count: 3, units: 'paragraphs' }); +result = loremIpsum({ sentenceLowerBound: 10, sentenceUpperBound: 15, count: 5, units: 'sentences' }); +result = loremIpsum({ words: ['a', 'b', 'c'] }); +result = loremIpsum({ suffix: '-' }); +result = loremIpsum({ format: 'html' }); diff --git a/lorem-ipsum/tsconfig.json b/lorem-ipsum/tsconfig.json new file mode 100644 index 0000000000..e337082e32 --- /dev/null +++ b/lorem-ipsum/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", + "lorem-ipsum-tests.ts" + ] +} \ No newline at end of file diff --git a/lorem-ipsum/tslint.json b/lorem-ipsum/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/lorem-ipsum/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/ltx/index.d.ts b/ltx/index.d.ts new file mode 100644 index 0000000000..c5794f12bb --- /dev/null +++ b/ltx/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for ltx 2.6 +// Project: github.com/node-xmpp/ltx/ +// Definitions by: PJakcson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export {Element} from './lib/Element' +export {nameEqual, attrsEqual, childrenEqual, equal} from './lib/equal'; +export {isNode, isElement, isText} from './lib/is'; +export {clone} from './lib/clone'; +export {createElement} from './lib/createElement'; +export {escapeXML, unescapeXML, escapeXMLText, unescapeXMLText} from './lib/escape'; +export {Parser} from './lib/Parser'; +export {parse} from './lib/parse'; +export {tag} from './lib/tag'; +export {tagString} from './lib/tagString'; +export {stringify} from './lib/stringify'; diff --git a/ltx/lib/Element.d.ts b/ltx/lib/Element.d.ts new file mode 100644 index 0000000000..d0f50ae783 --- /dev/null +++ b/ltx/lib/Element.d.ts @@ -0,0 +1,119 @@ +/** + * Element + * + * Attributes are in the element.attrs object. Children is a list of + * either other Elements or Strings for text content. + **/ +export declare class Element { + name: string; + parent: Element; + children: Element[]; + attrs: any; + + constructor(name: string, attrs?: any); + + /** + * if (element.is('message', 'jabber:client')) ... + **/ + is(name: string, xmlns?: any): boolean; + + /** + * without prefix. + */ + getName(): string; + + /** + * retrieves the namespace of the current element, upwards recursively + **/ + getNS(): any; + + /** + * find the namespace to the given prefix, upwards recursively + **/ + findNS(prefix: string): any; + + /** + * Recursiverly gets all xmlns defined, in the form of {url:prefix} + **/ + getXmlns(): any; + + setAttrs(attrs: any): void; + + /** + * xmlns can be null, returns the matching attribute. + **/ + getAttr(name: string, xmlns?: any): any; + + /** + * xmlns can be null + **/ + getChild(name: string, xmlns?: any): Element; + + /** + * xmlns can be null + **/ + getChildren(name: string, xmlns?: any): Element[]; + + /** + * xmlns and recursive can be null + **/ + getChildByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element; + + + /** + * xmlns and recursive can be null + **/ + getChildrenByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element[]; + + getText(): string; + + getChildText(name: string, xmlns: any): string; + + /** + * Return all direct descendents that are Elements. + * This differs from `getChildren` in that it will exclude text nodes, + * processing instructions, etc. + */ + getChildElements(): Element[]; + + /** returns uppermost parent */ + root(): Element; + + tree(): Element; + + /** just parent or itself */ + up(): Element; + + /** create child node and return it */ + c(name: string, attrs?: any): Element; + + /** add text node and return element */ + t(text: string): Element; + + /** + * Either: + * el.remove(childEl) + * el.remove('author', 'urn:...') + */ + remove(el: Element, xmlns?: any): Element; + + clone(): Element; + + text(val: string): string; + + attr(attr: any, val: any): any; + + toString(): string; + + toJSON(): any; + + write(writer: any): void; + + nameEquals(el: Element): boolean; + + attrsEquals(el: Element): boolean; + + childrenEquals(el: Element): boolean; + + equals(el: Element): boolean; +} diff --git a/ltx/lib/Parser.d.ts b/ltx/lib/Parser.d.ts new file mode 100644 index 0000000000..3af418d21f --- /dev/null +++ b/ltx/lib/Parser.d.ts @@ -0,0 +1,5 @@ +/// +import {EventEmitter} from 'events'; +export declare class Parser extends EventEmitter { + constructor(options?: any); +} diff --git a/ltx/lib/clone.d.ts b/ltx/lib/clone.d.ts new file mode 100644 index 0000000000..41193a3f40 --- /dev/null +++ b/ltx/lib/clone.d.ts @@ -0,0 +1 @@ +export declare function clone(el: any): any; diff --git a/ltx/lib/createElement.d.ts b/ltx/lib/createElement.d.ts new file mode 100644 index 0000000000..2deead1663 --- /dev/null +++ b/ltx/lib/createElement.d.ts @@ -0,0 +1,2 @@ +import {Element} from './Element'; +export declare function createElement(name: string, attrs: any): Element; diff --git a/ltx/lib/equal.d.ts b/ltx/lib/equal.d.ts new file mode 100644 index 0000000000..520555e098 --- /dev/null +++ b/ltx/lib/equal.d.ts @@ -0,0 +1,4 @@ +export declare function nameEqual(a: any, b: any): boolean; +export declare function attrsEqual(a: any, b: any): boolean; +export declare function childrenEqual(a: any, b: any): boolean; +export declare function equal(a: any, b: any): boolean; diff --git a/ltx/lib/escape.d.ts b/ltx/lib/escape.d.ts new file mode 100644 index 0000000000..4bc45c223a --- /dev/null +++ b/ltx/lib/escape.d.ts @@ -0,0 +1,4 @@ +export declare function escapeXML(s: string): string; +export declare function unescapeXML(s: string): string; +export declare function escapeXMLText(s: string): string; +export declare function unescapeXMLText(s: string): string; diff --git a/ltx/lib/is.d.ts b/ltx/lib/is.d.ts new file mode 100644 index 0000000000..6515d23f80 --- /dev/null +++ b/ltx/lib/is.d.ts @@ -0,0 +1,3 @@ +export declare function isNode(el: any): boolean; +export declare function isElement(el: any): boolean; +export declare function isText(el: any): boolean; diff --git a/ltx/lib/parse.d.ts b/ltx/lib/parse.d.ts new file mode 100644 index 0000000000..cc4073113a --- /dev/null +++ b/ltx/lib/parse.d.ts @@ -0,0 +1 @@ +export declare function parse(data: any, options?: any): any; diff --git a/ltx/lib/stringify.d.ts b/ltx/lib/stringify.d.ts new file mode 100644 index 0000000000..770f7d324f --- /dev/null +++ b/ltx/lib/stringify.d.ts @@ -0,0 +1 @@ +export declare function stringify(el: any, indent: any, level: any): string; diff --git a/ltx/lib/tag.d.ts b/ltx/lib/tag.d.ts new file mode 100644 index 0000000000..8bbcb6fe7b --- /dev/null +++ b/ltx/lib/tag.d.ts @@ -0,0 +1 @@ +export declare function tag(d: any): any; diff --git a/ltx/lib/tagString.d.ts b/ltx/lib/tagString.d.ts new file mode 100644 index 0000000000..44036ce037 --- /dev/null +++ b/ltx/lib/tagString.d.ts @@ -0,0 +1 @@ +export declare function tagString(d: any): string; diff --git a/ltx/ltx-tests.ts b/ltx/ltx-tests.ts new file mode 100644 index 0000000000..a207efb4b7 --- /dev/null +++ b/ltx/ltx-tests.ts @@ -0,0 +1,16 @@ +import * as ltx from './index'; + +ltx.parse(''); + +let p = new ltx.Parser(); + +p.on('tree', (ignored: any) => {}); + +p.on('error', (ignored: any) => {}); + +let el = new ltx.Element('root').c('children'); +el.c('child', {age: 5}).t('Hello').up() + .c('child', {age: 7}).t('Hello').up() + .c('child', {age: 99}).t('Hello').up(); + +el.root().toString(); diff --git a/gaea-model/tsconfig.json b/ltx/tsconfig.json similarity index 86% rename from gaea-model/tsconfig.json rename to ltx/tsconfig.json index 05d346427a..28beec26d4 100644 --- a/gaea-model/tsconfig.json +++ b/ltx/tsconfig.json @@ -1,10 +1,12 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, - "strictNullChecks": true, "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -15,6 +17,6 @@ }, "files": [ "index.d.ts", - "gaea-model-tests.ts" + "ltx-tests.ts" ] } diff --git a/ltx/tslint.json b/ltx/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/ltx/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/lz-string/tslint.json b/lz-string/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/lz-string/tslint.json +++ b/lz-string/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/magnet-uri/magnet-uri-tests.ts b/magnet-uri/magnet-uri-tests.ts index ee97fb3451..aba247b19c 100644 --- a/magnet-uri/magnet-uri-tests.ts +++ b/magnet-uri/magnet-uri-tests.ts @@ -1,6 +1,7 @@ import * as magnet from 'magnet-uri'; // "Leaves of Grass" by Walt Whitman +// tslint:disable-next-line:max-line-length const uri = 'magnet:?xt=urn:btih:d2474e86c95b19b8bcfdb92bc12c9d44667cfa36&dn=Leaves+of+Grass+by+Walt+Whitman.epub&tr=udp%3A%2F%2Ftracker.example4.com%3A80&tr=udp%3A%2F%2Ftracker.example5.com%3A80&tr=udp%3A%2F%2Ftracker.example3.com%3A6969&tr=udp%3A%2F%2Ftracker.example2.com%3A80&tr=udp%3A%2F%2Ftracker.example1.com%3A1337'; const parsed = magnet.decode(uri); diff --git a/magnet-uri/tslint.json b/magnet-uri/tslint.json index ec365f164b..377cc837d4 100644 --- a/magnet-uri/tslint.json +++ b/magnet-uri/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/mailgen/mailgen-tests.ts b/mailgen/mailgen-tests.ts index 87d04ee943..fd9429b770 100644 --- a/mailgen/mailgen-tests.ts +++ b/mailgen/mailgen-tests.ts @@ -1,4 +1,4 @@ -import * as Mailgen from "mailgen" +import * as Mailgen from "mailgen"; const generator: Mailgen = new Mailgen({ theme: "default", @@ -8,7 +8,7 @@ const generator: Mailgen = new Mailgen({ } }); -let content: Mailgen.Content = { +const content: Mailgen.Content = { body: { name: "Hi", intro: "test", diff --git a/mapbox-gl/index.d.ts b/mapbox-gl/index.d.ts index 360eb1ce33..2e75704dde 100644 --- a/mapbox-gl/index.d.ts +++ b/mapbox-gl/index.d.ts @@ -986,3 +986,7 @@ declare namespace mapboxgl { declare module 'mapbox-gl' { export = mapboxgl; } + +declare module 'mapbox-gl/dist/mapbox-gl' { + export = mapboxgl; +} diff --git a/mapbox/mapbox-tests.ts b/mapbox/mapbox-tests.ts index aaa7dd1c5f..f336d66e1a 100644 --- a/mapbox/mapbox-tests.ts +++ b/mapbox/mapbox-tests.ts @@ -16,7 +16,7 @@ var marker = L.marker(new L.LatLng([0, 0]), { }).addTo(map); // every time the marker is dragged, update the coordinates container -marker.on('dragend', function() { +marker.on('dragend', () => { var m = marker.getLatLng(); coordinates.innerHTML = 'Latitude: ' + m.lat + '
Longitude: ' + m.lng; }); @@ -29,13 +29,13 @@ var marker2 = L.mapbox.featureLayer({ coordinates: [-73.9840, 40.7271] }, properties: { - title: 'Hello world!', + 'title': 'Hello world!', 'marker-color': '#f86767' } }).addTo(map); // Iterate over the featureLayer we've called "marker" // and open its popup instead of clicking to trigger it. -marker2.eachLayer(function(marker: L.Marker) { +marker2.eachLayer((marker: L.Marker) => { marker.openPopup(); }); \ No newline at end of file diff --git a/mapbox/tslint.json b/mapbox/tslint.json index 0f47deabb4..f05741c59b 100644 --- a/mapbox/tslint.json +++ b/mapbox/tslint.json @@ -3,4 +3,4 @@ "rules": { "forbidden-types": false } -} \ No newline at end of file +} diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index 716505987d..c399116482 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/callemall/material-ui // Definitions by: Nathan Brown , Oliver Herrmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// @@ -129,6 +130,7 @@ declare namespace __MaterialUI { accent2Color?: string; accent3Color?: string; textColor?: string; + secondaryTextColor?: string; alternateTextColor?: string; canvasColor?: string; borderColor?: string; @@ -452,7 +454,10 @@ declare namespace __MaterialUI { var lightBaseTheme: RawTheme; var darkBaseTheme: RawTheme; - export function muiThemeable, P, S>(): (component: TComponent) => TComponent; + export function muiThemeable(): < + TComponent extends React.ComponentClass

| React.StatelessComponent

, + P extends {muiTheme?: MuiTheme} + >(component: TComponent) => TComponent; interface MuiThemeProviderProps { muiTheme?: Styles.MuiTheme; @@ -1734,6 +1739,7 @@ declare namespace __MaterialUI { } interface TabProps extends SharedEnhancedButtonProps { + buttonStyle?: React.CSSProperties; className?: string; icon?: React.ReactNode; label?: React.ReactNode; diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index 04b8f0ec32..f2acb7922f 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -7,6 +7,7 @@ import * as React from 'react'; import {Component, PropTypes} from 'react'; import * as ReactDOM from 'react-dom'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; +import {muiThemeable} from 'material-ui/styles/muiThemeable'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import {MuiTheme} from 'material-ui/styles'; @@ -166,8 +167,8 @@ const styles = { root: { display: 'flex', flexWrap: 'wrap', - justifyContent: 'space-around', - } as React.CSSProperties, + justifyContent: 'space-around' as 'space-around', + }, gridList: { width: 500, height: 500, @@ -188,7 +189,7 @@ const styles = { }, h3: { marginTop: 20, - fontWeight: 400, + fontWeight: 400 as 400, }, block: { display: 'flex', @@ -222,7 +223,7 @@ const styles = { fontSize: 24, paddingTop: 16, marginBottom: 12, - fontWeight: 400, + fontWeight: 400 as 400, }, errorStyle: { color: orange500, @@ -321,6 +322,35 @@ class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}, {}> { } +const MuiThemeableFunction = muiThemeable()((props: {label: string, muiTheme?: MuiTheme}) => { + return ( + + Applied the Theme to functional component: {props.label}. + + ); +}); + +@muiThemeable() +class MuiThemeableClass extends React.Component<{label: string} & {muiTheme?: MuiTheme}, {}> { + render() { + return ( + + Applied the Theme to class component decorated: {this.props.label}. + + ); + } +} + +const MuiThemeableContainer = (props: {}) => ( + +

+ + +
+ +); + + // "http://www.material-ui.com/#/customization/inline-styles" const InlineStylesCheckbox = () => ( { } handleExpandChange = (expanded) => { - this.setState({expanded: expanded}); - }; + this.setState({expanded}); + } handleToggle = (event, toggle) => { this.setState({expanded: toggle}); - }; + } handleExpand = () => { this.setState({expanded: true}); - }; + } handleReduce = () => { this.setState({expanded: false}); - }; + } render() { return ( @@ -1106,8 +1136,8 @@ class DatePickerExampleToggle extends React.Component<{}, DatePickerExampleToggl maxDate.setHours(0, 0, 0, 0); this.state = { - minDate: minDate, - maxDate: maxDate, + minDate, + maxDate, autoOk: false, disableYearSelection: false, }; @@ -1117,19 +1147,19 @@ class DatePickerExampleToggle extends React.Component<{}, DatePickerExampleToggl this.setState({ minDate: date, }); - }; + } handleChangeMaxDate = (event, date) => { this.setState({ maxDate: date, }); - }; + } handleToggle = (event, toggled) => { this.setState({ [event.target.name]: toggled, }); - }; + } render() { return ( @@ -1190,7 +1220,7 @@ class DatePickerExampleControlled extends React.Component<{}, {controlledDate?: this.setState({ controlledDate: date, }); - }; + } render() { return ( @@ -1252,11 +1282,11 @@ class DialogExampleSimple extends React.Component<{}, {open?: boolean}> { handleOpen = () => { this.setState({open: true}); - }; + } handleClose = () => { this.setState({open: false}); - }; + } render() { const actions = [ @@ -1297,11 +1327,11 @@ class DialogExampleModal extends React.Component<{}, {open?: boolean}> { handleOpen = () => { this.setState({open: true}); - }; + } handleClose = () => { this.setState({open: false}); - }; + } render() { const actions = [ @@ -1341,11 +1371,11 @@ class DialogExampleCustomWidth extends React.Component<{}, {open?: boolean}> { handleOpen = () => { this.setState({open: true}); - }; + } handleClose = () => { this.setState({open: false}); - }; + } render() { const actions = [ @@ -1385,11 +1415,11 @@ class DialogExampleDialogDatePicker extends React.Component<{}, {open?: boolean} handleOpen = () => { this.setState({open: true}); - }; + } handleClose = () => { this.setState({open: false}); - }; + } render() { const actions = [ @@ -1426,11 +1456,11 @@ class DialogExampleScrollable extends React.Component<{}, {open?: boolean}> { handleOpen = () => { this.setState({open: true}); - }; + } handleClose = () => { this.setState({open: false}); - }; + } render() { const actions = [ @@ -1486,11 +1516,11 @@ class DialogExampleAlert extends React.Component<{}, {open?: boolean}> { handleOpen = () => { this.setState({open: true}); - }; + } handleClose = () => { this.setState({open: false}); - }; + } render() { const actions = [ @@ -2258,7 +2288,7 @@ function wrapState(ComposedComponent: React.ComponentClass<__MaterialUI.List.Sel this.setState({ selectedIndex: index, }); - }; + } render() { return ( @@ -2537,13 +2567,13 @@ class IconMenuExampleControlled extends React.Component<{}, IconMenuExampleContr this.setState({ valueSingle: value, }); - }; + } handleChangeMultiple = (event, value) => { this.setState({ valueMultiple: value, }); - }; + } handleOpenMenu = () => { this.setState({ @@ -2856,13 +2886,13 @@ class PopoverExampleSimple extends React.Component<{}, {open?: boolean, anchorEl open: true, anchorEl: event.currentTarget, }); - }; + } handleRequestClose = () => { this.setState({ open: false, }); - }; + } render() { return ( @@ -2907,13 +2937,13 @@ class PopoverExampleAnimation extends React.Component<{}, {open?: boolean, ancho open: true, anchorEl: event.currentTarget, }); - }; + } handleRequestClose = () => { this.setState({ open: false, }); - }; + } render() { return ( @@ -2974,31 +3004,31 @@ class PopoverExampleConfigurable extends React.Component<{}, PopoverExampleConfi open: true, anchorEl: event.currentTarget, }); - }; + } handleRequestClose = () => { this.setState({ open: false, }); - }; + } setAnchor = (positionElement, position) => { const {anchorOrigin} = this.state; anchorOrigin[positionElement] = position; this.setState({ - anchorOrigin: anchorOrigin, + anchorOrigin }); - }; + } setTarget = (positionElement, position) => { const {targetOrigin} = this.state; targetOrigin[positionElement] = position; this.setState({ - targetOrigin: targetOrigin, + targetOrigin }); - }; + } render() { return ( @@ -3453,7 +3483,7 @@ class SliderExampleControlled extends React.Component<{}, {firstSlider?: number, state = { firstSlider: 0.5, secondSlider: 50, - } + }; handleFirstSlider(event, value) { this.setState({firstSlider: value}); @@ -3622,13 +3652,13 @@ class SnackbarExampleSimple extends React.Component<{}, {open?: boolean}> { this.setState({ open: true, }); - }; + } handleRequestClose = () => { this.setState({ open: false, }); - }; + } render() { return ( @@ -3664,27 +3694,27 @@ class SnackbarExampleAction extends React.Component<{}, {open?: boolean, autoHid this.setState({ open: true, }); - }; + } handleActionTouchTap = () => { this.setState({ open: false, }); alert('Event removed from your calendar.'); - }; + } handleChangeDuration = (event) => { const value = event.target.value; this.setState({ - autoHideDuration: value.length > 0 ? parseInt(value) : 0, + autoHideDuration: value.length > 0 ? parseInt(value, 10) : 0, }); - }; + } handleRequestClose = () => { this.setState({ open: false, }); - }; + } render() { return ( @@ -3739,13 +3769,13 @@ class SnackbarExampleTwice extends React.Component<{}, {open?: boolean, message? message: `Event ${Math.round(Math.random() * 100)} added to your calendar`, }); }, 1500); - }; + } handleRequestClose = () => { this.setState({ open: false, }); - }; + } render() { return ( @@ -3781,14 +3811,14 @@ class HorizontalLinearStepper extends React.Component<{}, {stepIndex?: number, f stepIndex: stepIndex + 1, finished: stepIndex >= 2, }); - }; + } handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } - }; + } getStepContent(stepIndex) { switch (stepIndex) { @@ -3870,14 +3900,14 @@ class VerticalLinearStepper extends React.Component<{}, {stepIndex?: number, fin stepIndex: stepIndex + 1, finished: stepIndex >= 2, }); - }; + } handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } - }; + } renderStepActions(step) { const {stepIndex} = this.state; @@ -3971,14 +4001,14 @@ class HorizontalNonLinearStepper extends React.Component<{}, {stepIndex?: number if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } - }; + } handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } - }; + } getStepContent(stepIndex) { switch (stepIndex) { @@ -4049,14 +4079,14 @@ class VerticalNonLinear extends React.Component<{}, {stepIndex?: number}> { if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } - }; + } handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } - }; + } renderStepActions(step) { return ( @@ -4176,14 +4206,14 @@ class GranularControlStepper extends React.Component<{}, {stepIndex?: number, vi if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } - }; + } handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } - }; + } getStepContent(stepIndex) { switch (stepIndex) { @@ -4266,14 +4296,14 @@ class CustomIcon extends React.Component<{}, {stepIndex?: number}> { if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } - }; + } handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } - }; + } getStepContent(stepIndex) { switch (stepIndex) { @@ -4389,16 +4419,16 @@ const tableData: {name: string, status: string, selected?: boolean}[] = [ ]; interface TableExampleComplexState { - fixedHeader?: boolean, - fixedFooter?: boolean, - stripedRows?: boolean, - showRowHover?: boolean, - selectable?: boolean, - multiSelectable?: boolean, - enableSelectAll?: boolean, - deselectOnClickaway?: boolean, - showCheckboxes?: boolean, - height?: string, + fixedHeader?: boolean; + fixedFooter?: boolean; + stripedRows?: boolean; + showRowHover?: boolean; + selectable?: boolean; + multiSelectable?: boolean; + enableSelectAll?: boolean; + deselectOnClickaway?: boolean; + showCheckboxes?: boolean; + height?: string; } class TableExampleComplex extends React.Component<{}, TableExampleComplexState> { @@ -4424,11 +4454,11 @@ class TableExampleComplex extends React.Component<{}, TableExampleComplexState> this.setState({ [event.target.name]: toggled, }); - }; + } handleChange = (event) => { this.setState({height: event.target.value}); - }; + } render() { return ( @@ -4608,9 +4638,9 @@ class TabsExampleControlled extends React.Component<{}, {value?: string}> { handleChange = (value) => { this.setState({ - value: value, + value }); - }; + } render() { return ( @@ -4807,7 +4837,7 @@ class TextFieldExampleControlled extends React.Component<{}, {value?: string}> { this.setState({ value: event.target.value, }); - }; + } render() { return ( @@ -4849,11 +4879,11 @@ class TimePickerExampleComplex extends React.Component<{}, {value24?: Date, valu handleChangeTimePicker24 = (event, date) => { this.setState({value24: date}); - }; + } handleChangeTimePicker12 = (event, date) => { this.setState({value12: date}); - }; + } render() { return ( @@ -4948,7 +4978,7 @@ class BottomNavigationExample extends React.Component<{}, { return } onTouchTap={() => this.setState({index: 0})}/> } onTouchTap={() => this.setState({index: 1})}/> - + ; } } diff --git a/materialize-css/index.d.ts b/materialize-css/index.d.ts index 14e68a7c21..8b4c610e13 100644 --- a/materialize-css/index.d.ts +++ b/materialize-css/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for materialize-css v0.97.5 +// Type definitions for materialize-css v0.98.0 // Project: http://materializecss.com/ -// Definitions by: Erik Lieben , Leon Yu +// Definitions by: Erik Lieben , Leon Yu , Sukhdeep Singh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -15,14 +15,42 @@ declare namespace Materialize { /** * A setting that changes the collapsible behavior to expandable instead of the default accordion style */ - accordion: boolean; + accordion?: boolean; + + /** + * Callback for Collapsible section close. + * Default: function() { alert('Closed'); } + */ + onClose?: Function; + + /** + * Callback for Collapsible section open. + * Default: function() { alert('Opened'); } + */ + onOpen?: Function; } interface TooltipOptions { /** * The delay before the tooltip shows (in milliseconds) */ - delay:number; + delay: number; + /** + * Tooltip text. Can use custom HTML if you set the html option + */ + tooltip?: string; + /** + * Set the direction of the tooltip. 'top', 'right', 'bottom', 'left'. + * + * (Default: 'bottom') + */ + position?: string; + /** + * Allow custom html inside the tooltip. + * + * (Default: false) + */ + html?: boolean; } /** @@ -34,43 +62,49 @@ declare namespace Materialize { * The duration of the transition enter in milliseconds. * Default: 300 */ - inDuration?:number; + inDuration?: number; /** * The duration of the transition out in milliseconds. * Default: 225 */ - outDuration?:number; + outDuration?: number; + - // TODO: constrain_width /** * If true, constrainWidth to the size of the dropdown activator. * Default: true */ - constrain_width?:boolean; + constrainWidth?: boolean; /** * If true, the dropdown will open on hover. * Default: false */ - hover?:boolean; + hover?: boolean; /** * This defines the spacing from the aligned edge. * Default: 0 */ - gutter?:number; + gutter?: number; /** * If true, the dropdown will show below the activator. * Default: false */ - belowOrigin?:boolean; + belowOrigin?: boolean; /** * Defines the edge the menu is aligned to. * Default: 'left' */ - alignment?:string; + alignment?: string; + /** + * If true, stops the event propagating from the dropdown origin click handler. + * + * Default: false + */ + stopPropagation?: boolean } /** @@ -108,10 +142,10 @@ declare namespace Materialize { */ interface CarouselOptions { /** - * Transition time. + * Transition duration in milliseconds * Default: 200 */ - time_constant?: number; + duration?: number; /** * Perspective zoom. If 0, all items are the same size. @@ -135,13 +169,25 @@ declare namespace Materialize { * Set the width of the carousel. * Default: false */ - full_width?: boolean; + fullWidth?: boolean; + /** + * Set to true to show indicators. + * + * Default: false + */ + indicators?: boolean; + /** + * Don't wrap around and cycle through items. + * + * Default: false + */ + noWrap?: boolean; } /** - * The lean modal options + * The modal options */ - interface LeanModalOptions { + interface ModalOptions { /** * Modal can be dismissed by clicking outside of the modal. @@ -159,13 +205,23 @@ declare namespace Materialize { * Transition in duration. * Default: 300 */ - in_duration?: number; + inDuration?: number; /** * Transition out duration. * Default: 200 */ - out_duration?: number; + outDuration?: number; + /** + * Starting top style attribute + * Default: `4%` + */ + startingTop?: string; + /** + * Ending top style attribute + * Default : `10%` + */ + endingTop?: string; /** * Callback for Modal open. @@ -189,19 +245,19 @@ declare namespace Materialize { * The distance in pixels from the top of the page where the element becomes fixed. * Default: 0 */ - top?:number; + top?: number; /** * The distance in pixels from the top of the page where the elements stops being fixed. * Default: Infinity */ - bottom?:number; + bottom?: number; /** * The offset from the top the element will be fixed at. * Default: 0 */ - offset?:number; + offset?: number; } /** @@ -261,44 +317,97 @@ declare namespace Materialize { * It will only be called once. * Example: 'console.log("hello, world!")'; */ - callback?: string; + callback?: Function; } + interface TabOptions { /** + * Execute a callback function when the tab is changed. + * + * The callback provides a parameter which refers to the current tab being shown. + */ + onShow?: Function; + + /** + * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option. + * + * Default: false + */ + swipeable?: boolean; + + /** + * The maximum width of the screen, in pixels, where the swipeable functionality initializes. + * + * Default: Infinity + */ + responsiveThreshold?: number; + } + + interface ChipDataObject { + tag: string, + image?: string, + id?: number + } + + interface ChipOptions { + /** + * Set the chip data + */ + data?: Materialize.ChipDataObject[]; + /** + * Set first placeholder when there are no tags + */ + placeholder?: string; + /** + * Set second placeholder when adding additional tags. + */ + secondaryPlaceholder?: string; + /** + * Set autocomplete data. + */ + autocompleteData?: any; + /** + * Set autocomplete limit. + */ + autocompleteLimit?: number; + } + + + /** * The Materialize object */ interface Materialize { /** - * Displays a toast message on screen - * - * @name message The message to display on screen - * @name displayLength The duration in milliseconds to display the message on screen - * @name className The className to use to format the message to display - * @name completeCallback Callback function to call when the messages completes/hides. - */ - toast(message:string|JQuery, displayLength:number, className?:string, completeCallback?:Function): void; + * Displays a toast message on screen + * + * @name message The message to display on screen + * @name displayLength The duration in milliseconds to display the message on screen + * @name className The className to use to format the message to display + * @name completeCallback Callback function to call when the messages completes/hides. + */ + toast(message: string | JQuery, displayLength: number, className?: string, completeCallback?: Function): void; /** * Fires an event when the page is scrolled to a certain area * * @name options optional parameter with scroll fire options */ - scrollFire(options?:ScrollFireOptions): void; + scrollFire(options?: ScrollFireOptions): void; /** * A staggered reveal effect for any UL Tag with list items * * @name selector the selector for the list to show in staggered fasion */ - showStaggeredList(selector:string): void; + showStaggeredList(selector: string): void; /** * Fade in images. It also animates grayscale and brightness to give it a unique effect. * * @name selector the selector for the image to fade in */ - fadeInImage(selector:string): void; + fadeInImage(selector: string): void; /** * Update all text field to reinitialize all the Materialize labels on the page if dynamically adding inputs @@ -307,7 +416,7 @@ declare namespace Materialize { } } -declare var Materialize : Materialize.Materialize; +declare var Materialize: Materialize.Materialize; interface JQuery { @@ -353,7 +462,7 @@ interface JQuery { * * @name options the tooltip options or the string "remove" to remove the tooltip function */ - tooltip(options?: Materialize.TooltipOptions|string): JQuery; + tooltip(options?: Materialize.TooltipOptions | string): JQuery; /** * Add a dropdown list to any button. @@ -402,28 +511,32 @@ interface JQuery { * * @name method the methods to pause, start, move to next and move to previous slide. */ - carousel(method: string, count: [number]): JQuery; + carousel(method: string, count?: number): JQuery; /** - * Modal for dialog boxes, confirmation messages, or other content that can be called up. + * Modal for dialog boxes, confirmation messages, or other content that can be called up. + * + * For Initialization. + */ + modal(): JQuery; + + /** + * Modal for dialog boxes, confirmation messages, or other content that can be called up. + * + * For opening and closing modals programatically. + * + * @name string action action to do (`open` or `close) + */ + modal(action: string): void; + + /** + * Modal for dialog boxes, confirmation messages, or other content that can be called up. + * + * To customize the behaviour of a modal * * @name options the lean modal options */ - leanModal(options?: Materialize.LeanModalOptions): JQuery; - - /** - * Open a modal programatically - * - * @name options the lean modal options - */ - openModal(options?: Materialize.LeanModalOptions): void; - - /** - * Close a modal programatically - * - * @name options the lean modal options - */ - closeModal(options?: Materialize.LeanModalOptions): void; + modal(options: Materialize.ModalOptions): void; /** * Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling. @@ -449,12 +562,33 @@ interface JQuery { * * @params methodOrOptions the slide navigation options or a string with "show" to reveal or "hide" to hide the menu */ - sideNav(methodOrOptions?: Materialize.SideNavOptions|string): void; + sideNav(methodOrOptions?: Materialize.SideNavOptions | string): void; /** * Programmatically trigger the tab change event * * @name method, the method to call (always "select_tab") and a param containing the id of the tab to open */ - tabs(method?:string, tab?:string): JQuery; + tabs(method?: string, tab?: string): JQuery; + + /** + * Tab Initialization with options + * + * @name TabOptions options jQuery plugin options + */ + tabs(options?: Materialize.TabOptions): JQuery; + + /** + * Chip Initialization + * + * @name ChipOptions options Material chip options + */ + material_chip(options?: Materialize.ChipOptions): JQuery; + + /** + * To access chip data + * + * @name string method name of the method to invoke + */ + material_chip(method: string): Materialize.ChipDataObject[] | Materialize.ChipDataObject; } diff --git a/materialize-css/materialize-css-tests.ts b/materialize-css/materialize-css-tests.ts index 45c9c84a76..9c7d7d1ea2 100644 --- a/materialize-css/materialize-css-tests.ts +++ b/materialize-css/materialize-css-tests.ts @@ -22,7 +22,7 @@ $('input#input_text, textarea#textarea1').characterCounter(); // Navbar $(".dropdown-button").dropdown(); -$(".dropdown-button").dropdown({hover: false}); +$(".dropdown-button").dropdown({ hover: false }); $(".button-collapse").sideNav(); @@ -30,22 +30,22 @@ $(".button-collapse").sideNav(); // Collapsible var collapseHtml = '
    ' + - '
  • ' + - '
    filter_dramaFirst
    ' + - '

    Lorem ipsum dolor sit amet.

    ' + - '
  • ' + - '
  • ' + - '
    placeSecond
    ' + - '

    Lorem ipsum dolor sit amet.

    ' + - '
  • ' + - '
  • ' + - '
    whatshotThird
    ' + - '

    Lorem ipsum dolor sit amet.

    ' + - '
  • ' + + '
  • ' + + '
    filter_dramaFirst
    ' + + '

    Lorem ipsum dolor sit amet.

    ' + + '
  • ' + + '
  • ' + + '
    placeSecond
    ' + + '

    Lorem ipsum dolor sit amet.

    ' + + '
  • ' + + '
  • ' + + '
    whatshotThird
    ' + + '

    Lorem ipsum dolor sit amet.

    ' + + '
  • ' + '
'; -$(collapseHtml).collapsible({ accordion : false }); -$(collapseHtml).collapsible({ accordion : true }); +$(collapseHtml).collapsible({ accordion: false, onClose: function () { alert('Closed'); } }); +$(collapseHtml).collapsible({ accordion: true, onOpen: function () { alert('Opened'); } }); // Dialogs - Toasts Materialize.toast('I am a toast!', 4000); @@ -57,19 +57,21 @@ Materialize.toast($toastContent, 5000); // Dialogs - Tooltip var tooltipHtml = 'Hover me!'; $(tooltipHtml).tooltip(); -$(tooltipHtml).tooltip({delay: 100}); +$(tooltipHtml).tooltip({ delay: 100 }); $(tooltipHtml).tooltip('remove'); // DropDown var dropDownHtml = 'Drop Me!'; $(dropDownHtml).dropdown({ - inDuration: 300, - outDuration: 225, - constrain_width: false, - hover: true, - gutter: 0, - belowOrigin: false, - alignment: 'left' + inDuration: 300, + outDuration: 225, + constrainWidth: false, // Does not change width of dropdown to that of the activator + hover: true, // Activate on hover + gutter: 0, // Spacing from edge + belowOrigin: false, // Displays dropdown below the button + alignment: 'left', // Displays dropdown with edge aligned to the left of button + stopPropagation: false // Stops event propagation + }); $(dropDownHtml).dropdown({}); @@ -79,136 +81,138 @@ $(materialboxHtml).materialbox(); // Media - slider var sliderHtml = '
' + - '
    ' + - '
  • ' + - ' ' + - '
    ' + - '

    This is our big Tagline!

    ' + - '
    Here\'s our small slogan.
    ' + - '
    ' + - '
  • ' + - '
  • ' + - ' ' + - '
    ' + - '

    Left Aligned Caption

    ' + - '
    Here\'s our small slogan.
    ' + - '
    ' + - '
  • ' + - '
  • ' + - ' ' + - '
    ' + - '

    Right Aligned Caption

    ' + - '
    Here\'s our small slogan.
    ' + - '
    ' + - '
  • ' + - '
  • ' + - ' ' + - '
    ' + - '

    This is our big Tagline!

    ' + - '
    Here\'s our small slogan.
    ' + - '
    ' + - '
  • ' + - '
' + + '
    ' + + '
  • ' + + ' ' + + '
    ' + + '

    This is our big Tagline!

    ' + + '
    Here\'s our small slogan.
    ' + + '
    ' + + '
  • ' + + '
  • ' + + ' ' + + '
    ' + + '

    Left Aligned Caption

    ' + + '
    Here\'s our small slogan.
    ' + + '
    ' + + '
  • ' + + '
  • ' + + ' ' + + '
    ' + + '

    Right Aligned Caption

    ' + + '
    Here\'s our small slogan.
    ' + + '
    ' + + '
  • ' + + '
  • ' + + ' ' + + '
    ' + + '

    This is our big Tagline!

    ' + + '
    Here\'s our small slogan.
    ' + + '
    ' + + '
  • ' + + '
' + '
'; - $(sliderHtml).slider(); - $(sliderHtml).slider({}); - $(sliderHtml).slider({ indicators: true }); - $(sliderHtml).slider({ indicators: true, height: 5 }); - $(sliderHtml).slider({ indicators: true, height: 5, transition: 4 }); - $(sliderHtml).slider({ indicators: true, height: 5, transition: 4, interval: 5 }); +$(sliderHtml).slider(); +$(sliderHtml).slider({}); +$(sliderHtml).slider({ indicators: true }); +$(sliderHtml).slider({ indicators: true, height: 5 }); +$(sliderHtml).slider({ indicators: true, height: 5, transition: 4 }); +$(sliderHtml).slider({ indicators: true, height: 5, transition: 4, interval: 5 }); // Carousel $('.carousel').carousel(); $('.carousel').carousel({}); -$('.carousel').carousel({ time_constant: 200, dist: -100, shift: 500, padding: 6000, full_width: true }); +$('.carousel').carousel({ duration: 200, dist: -100, shift: 500, padding: 6000, fullWidth: true, indicators: false, noWrap: false }); // Next slide $('.carousel').carousel('next'); -$('.carousel').carousel('next', [3]); // Move next n times. +$('.carousel').carousel('next', 3); // Move next n times. // Previous slide $('.carousel').carousel('prev'); -$('.carousel').carousel('prev', [4]); // Move prev n times. +$('.carousel').carousel('prev', 4); // Move prev n times. // Modals var modalhtml = ''; -$(modalhtml).openModal(); -$(modalhtml).closeModal(); +$(modalhtml).modal('open'); +$(modalhtml).modal('close'); var modalTriggerHtml = ''; -$(modalTriggerHtml).leanModal(); -$(modalTriggerHtml).leanModal({}); -$(modalTriggerHtml).leanModal({ dismissible: true }); -$(modalTriggerHtml).leanModal({ dismissible: true, opacity: 1 }); -$(modalTriggerHtml).leanModal({ dismissible: true, opacity: 1, in_duration: 100 }); -$(modalTriggerHtml).leanModal({ dismissible: true, opacity: 1, in_duration: 100, out_duration: 100 }); -$(modalTriggerHtml).leanModal({ dismissible: true, opacity: 1, in_duration: 100, out_duration: 100, ready: () => console.log('ready') }); -$(modalTriggerHtml).leanModal({ dismissible: true, opacity: 1, in_duration: 100, out_duration: 100, ready: () => console.log('ready'), complete: () => console.log('complete')}); +$(modalTriggerHtml).modal(); +$(modalTriggerHtml).modal({}); +$(modalTriggerHtml).modal({ dismissible: true }); +$(modalTriggerHtml).modal({ dismissible: true, opacity: 1 }); +$(modalTriggerHtml).modal({ dismissible: true, opacity: 1, inDuration: 100 }); +$(modalTriggerHtml).modal({ dismissible: true, opacity: 1, inDuration: 100, outDuration: 100 }); +$(modalTriggerHtml).modal({ dismissible: true, opacity: 1, inDuration: 100, outDuration: 100, startingTop: "4%" }); +$(modalTriggerHtml).modal({ dismissible: true, opacity: 1, inDuration: 100, outDuration: 100, startingTop: "4%", endingTop: "10%" }); +$(modalTriggerHtml).modal({ dismissible: true, opacity: 1, inDuration: 100, outDuration: 100, startingTop: "4%", endingTop: "10%", ready: () => console.log('ready') }); +$(modalTriggerHtml).modal({ dismissible: true, opacity: 1, inDuration: 100, outDuration: 100, startingTop: "4%", endingTop: "10%", ready: () => console.log('ready'), complete: () => console.log('complete') }); // Parallax var parallaxHtml = '
' + - '
' + - '
'; - $(parallaxHtml).parallax(); + '
' + + '
'; +$(parallaxHtml).parallax(); - // PushPin - $('
').pushpin(); - $('
').pushpin({ top: 1 }); - $('
').pushpin({ top: 1, bottom: 1 }); - $('
').pushpin({ top: 1, bottom: 1, offset: 2 }); +// PushPin +$('
').pushpin(); +$('
').pushpin({ top: 1 }); +$('
').pushpin({ top: 1, bottom: 1 }); +$('
').pushpin({ top: 1, bottom: 1, offset: 2 }); // ScrollFire var options = [ - {selector: '.class', offset: 200, callback: 'console.log(".class")' }, - {selector: '.other-class', offset: 200, callback: 'console.log(".other-class")' }, + { selector: '.class', offset: 200, callback: 'console.log(".class")' }, + { selector: '.other-class', offset: 200, callback: 'console.log(".other-class")' }, ]; Materialize.scrollFire(options); // ScrollSpy var scrollSpyHtml = '
' + - '
' + - '
' + - '

Content

' + - '
' + - '
' + - '

Content

' + - '
' + - '
' + - '

Content

' + - '
' + - '
' + - '
' + - '' + - '
' + + '
' + + '
' + + '

Content

' + + '
' + + '
' + + '

Content

' + + '
' + + '
' + + '

Content

' + + '
' + + '
' + + '
' + + '' + + '
' + '
'; $(scrollSpyHtml, ".scrollspy").scrollSpy(); // Side-Nav var sideNavHtml = ''; + ''; $(sideNavHtml).sideNav(); $(sideNavHtml).sideNav({}); $(sideNavHtml).sideNav({ menuWidth: 100 }); @@ -220,24 +224,55 @@ $(sideNavHtml).sideNav("hide"); // Tabs var tabsHtml = '
' + - '
' + - '' + - '
' + - '
Test 1
' + - '
Test 2
' + - '
Test 3
' + - '
Test 4
' + + '
' + + '' + + '
' + + '
Test 1
' + + '
Test 2
' + + '
Test 3
' + + '
Test 4
' + '
'; - $(tabsHtml).tabs(); - $(tabsHtml).tabs('select_tab', 'test1'); +$(tabsHtml).tabs(); +$(tabsHtml).tabs('select_tab', 'test1'); +$(tabsHtml).tabs({ onShow: (currentTab: any) => { console.log(currentTab) }, swipeable: false, responsiveThreshold: 5000 }); // Transitions Materialize.showStaggeredList('#staggered-test'); -Materialize.updateTextFields(); \ No newline at end of file +Materialize.updateTextFields(); + +let chipsHTML = '
' + + '
' + + '
' + + '
'; + +$(chipsHTML).material_chip(); +$(chipsHTML).material_chip({ + data: [{ + tag: 'Apple', + }, { + tag: 'Microsoft', + }, { + tag: 'Google', + }], +}); + +$('.chips-placeholder').material_chip({ + placeholder: 'Enter a tag', + secondaryPlaceholder: '+Tag', +}); +$('.chips-autocomplete').material_chip({ + autocompleteData: { + 'Apple': null, + 'Microsoft': null, + 'Google': null + } +}); + +let chipData: Materialize.ChipDataObject | Materialize.ChipDataObject[] = $('.chips-initial').material_chip('data'); \ No newline at end of file diff --git a/math3d/math3d-tests.ts b/math3d/math3d-tests.ts index d04ddbefb9..9647038565 100644 --- a/math3d/math3d-tests.ts +++ b/math3d/math3d-tests.ts @@ -1,7 +1,7 @@ import * as math3d from 'math3d'; const v = new math3d.Vector3(1, 2, 3); v.add(new math3d.Vector3(0, 0, 1)); -new math3d.Matrix4x4([1,1,1,1, - 2,2,2,2, - 3,3,3,3, - 4,4,4,4]); +new math3d.Matrix4x4([1, 1, 1, 1, + 2, 2, 2, 2, + 3, 3, 3, 3, + 4, 4, 4, 4]); diff --git a/mathjs/index.d.ts b/mathjs/index.d.ts index d11a72d97b..f255546b0e 100644 --- a/mathjs/index.d.ts +++ b/mathjs/index.d.ts @@ -1036,7 +1036,7 @@ declare namespace mathjs { asech(x: MathArray): MathArray; asech(x: Matrix): Matrix; - /** + /** * Calculate the inverse sine of a value. For matrices, the function is evaluated element wise. */ asin(x: number): number; @@ -1163,6 +1163,16 @@ declare namespace mathjs { sin(x: MathArray): MathArray; sin(x: Matrix): Matrix; + /** + * Calculate the cosine of a value. For matrices, the function is evaluated element wise. + */ + cos(x: number): number; + cos(x: BigNumber): BigNumber; + cos(x: Complex): Complex; + cos(x: Unit): number; + cos(x: MathArray): MathArray; + cos(x: Matrix): Matrix; + /** * Calculate the hyperbolic sine of a value, defined as sinh(x) = 1/2 * (exp(x) - exp(-x)). For matrices, the function is evaluated element wise. */ @@ -1385,8 +1395,8 @@ declare namespace mathjs { * @param {MathNode} callback(node [description] * @return {[type]} [description] */ - forEach(callback: (node: MathNode, path: string, parent: MathNode)=>boolean): MathNode[]; - + forEach(callback: (node: MathNode, path: string, parent: MathNode)=>any): MathNode[]; + /** * `traverse(callback)` @@ -1416,9 +1426,38 @@ declare namespace mathjs { */ traverse(callback: (node: MathNode, path: string, parent: MathNode)=> void): any; //addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any); - - transform(callback: (node: MathNode, path: string, parent: MathNode)=>boolean): MathNode[]; - + /** + * Recursively transform an expression tree via a transform function. Similar to Array.map, + * but recursively executed on all nodes in the expression tree. The callback function is a + * mapping function accepting a node, and returning a replacement for the node or the original node. + * Function callback is called as callback(node: Node, path: string, parent: Node) for every node in + * the tree, and must return a Node. Parameter path is a string containing a relative JSON Path. + * + * For example, to replace all nodes of type SymbolNode having name ‘x’ with a ConstantNode with value 3: + * ```js + * var node = math.parse('x^2 + 5*x'); + * var transformed = node.transform(function (node, path, parent) { + * if (node.SymbolNode && node.name == 'x') { + * return new math.expression.node.ConstantNode(3); + * } + * else { + * return node; + * } + * }); + * transformed.toString(); // returns '(3 ^ 2) + (5 * 3)' + * ``` + */ + transform(callback: (node: MathNode, path: string, parent: MathNode)=>MathNode): MathNode; + /** + * Transform a node. Creates a new Node having it’s childs be the results of calling the provided + * callback function for each of the childs of the original node. The callback function is called + * as `callback(child: Node, path: string, parent: Node)` and must return a Node. + * Parameter path is a string containing a relative JSON Path. + * + * + * See also transform, which is a recursive version of map. + */ + map(callback: (node: MathNode, path: string, parent: MathNode)=>MathNode): MathNode; } diff --git a/mathjs/mathjs-tests.ts b/mathjs/mathjs-tests.ts index c174ca1c95..3d4d87d72a 100644 --- a/mathjs/mathjs-tests.ts +++ b/mathjs/mathjs-tests.ts @@ -11,6 +11,8 @@ Basic usage examples math.log(10000, 10); // 4 math.sqrt(-4); // 2i math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]] + var angle = 0.2; + math.add(math.pow(math.sin(angle), 2), math.pow(math.cos(angle), 2)); // returns number ~1 // expressions math.eval('1.2 * (2 + 4.5)'); // 7.8 diff --git a/mem/tslint.json b/mem/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/mem/tslint.json +++ b/mem/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/memoizee/memoizee-tests.ts b/memoizee/memoizee-tests.ts index e8e73a2d6a..c78c240ac9 100644 --- a/memoizee/memoizee-tests.ts +++ b/memoizee/memoizee-tests.ts @@ -1,6 +1,6 @@ import memoize = require('memoizee'); -var fn = function (one: string, two?: number, three?: any) { /* ... */ }; +var fn = (one: string, two?: number, three?: any) => { /* ... */ }; let memoized = memoize(fn); memoized('foo', 3, 'bar'); @@ -18,15 +18,15 @@ memoized('foo', 3, 13); memoized = memoize(fn, { primitive: true }); memoized('/path/one'); memoized('/path/one'); -memoized = memoize(fn, { dispose: function (value:number) { /*…*/ } }); +memoized = memoize(fn, { dispose(value: number) { /*…*/ } }); var foo3 = memoized('foo', 3); var bar7 = memoized('bar', 7); memoized.clear('foo', 3); // Dispose called with foo3 value memoized.clear('bar', 7); // Dispose called with bar7 value memoized.delete('foo', 0); -var mFn = memoize(function (hash:any) { +var mFn = memoize((hash: any) => { // body of memoized function -}, { normalizer: function (args:any) { +}, { normalizer: (args: any) => { // args is arguments object as accessible in memoized function return JSON.stringify(args[0]); } }); @@ -34,15 +34,15 @@ var mFn = memoize(function (hash:any) { mFn({ foo: 'bar' }); memoized = memoize(fn, { length: 2, resolvers: [String, Boolean] }); -memoized(String(12), [1,2,3].length); +memoized(String(12), [1, 2, 3].length); memoized("12", Number(true)); -memoized(String({ toString: function () { return "12"; } }), Number({})); +memoized(String({ toString() { return "12"; } }), Number({})); { - var afn = function (a:number, b:number) { - return new Promise(function (res) { res(a + b); }); + var afn = (a: number, b: number) => { + return new Promise(res => { res(a + b); }); }; - let memoized = memoize(afn, { promise: true }); + const memoized = memoize(afn, { promise: true }); memoized(3, 7); memoized(3, 7); } @@ -52,10 +52,10 @@ memoized = memoize(fn, { maxAge: 1000, preFetch: 0.6 }); memoized('foo', 3); memoized('foo', 3); -setTimeout(function () { +setTimeout(() => { memoized('foo', 3); }, 500); -setTimeout(function () { +setTimeout(() => { memoized('foo', 3); }, 1300); diff --git a/memoizee/tslint.json b/memoizee/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/memoizee/tslint.json +++ b/memoizee/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/meow/tslint.json b/meow/tslint.json index f9e30021f4..377cc837d4 100644 --- a/meow/tslint.json +++ b/meow/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/merge-descriptors/index.d.ts b/merge-descriptors/index.d.ts index d9ccc201a1..82ded472b0 100644 --- a/merge-descriptors/index.d.ts +++ b/merge-descriptors/index.d.ts @@ -1,12 +1,7 @@ -// Type definitions for merge-descriptors +// Type definitions for merge-descriptors 1.0 // Project: https://github.com/component/merge-descriptors // Definitions by: Zhiyuan Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare function merge(destination: Object, source: Object): Object; - -declare function merge(destination: Object, source: Object, redefine: boolean): Object; - +declare function merge(destination: Object, source: Object, redefine?: boolean): Object; export = merge; diff --git a/merge-descriptors/merge-descriptors-tests.ts b/merge-descriptors/merge-descriptors-tests.ts index ca2e326f3b..df8f444fa9 100644 --- a/merge-descriptors/merge-descriptors-tests.ts +++ b/merge-descriptors/merge-descriptors-tests.ts @@ -6,7 +6,7 @@ function testAssertion(condition: boolean, errorMessage: string) { } } -interface IMergedObject { +interface MergedObject { InSrc?: string; name: string; InTarget: string; @@ -17,9 +17,9 @@ var src = { get name(): string { return 'from src name'; } -} +}; -var target: IMergedObject = { name: 'my target name', InTarget: 'target' }; +var target: MergedObject = { name: 'my target name', InTarget: 'target' }; var target2 = mixin(target, src, true); @@ -30,5 +30,5 @@ testAssertion(target.name === 'from src name', "[redfine]=true, source member wi testAssertion(target.InTarget === 'target', "overwrite do not affect members only in [destination]"); testAssertion(target['InSrc'] === 'src', "members from [source] must be copied to [destination]"); -var nameProperty:PropertyDescriptor = Object.getOwnPropertyDescriptor(target, "name"); +var nameProperty: PropertyDescriptor = Object.getOwnPropertyDescriptor(target, "name"); testAssertion(nameProperty.set === undefined, "member descriptor must be overwritten"); \ No newline at end of file diff --git a/merge-descriptors/tsconfig.json b/merge-descriptors/tsconfig.json index 50246ffb88..4e224b187b 100644 --- a/merge-descriptors/tsconfig.json +++ b/merge-descriptors/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/merge-descriptors/tslint.json b/merge-descriptors/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/merge-descriptors/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/meteor-collection-hooks/README.md b/meteor-collection-hooks/README.md new file mode 100644 index 0000000000..158fb76e7c --- /dev/null +++ b/meteor-collection-hooks/README.md @@ -0,0 +1,4 @@ +# Meteor Collection Hooks Definitions + +Type definitions for Meteor package `matb33:collection-hooks`. +Be sure to reference any sort of basic Meteor type definitions file before use. \ No newline at end of file diff --git a/meteor-collection-hooks/index.d.ts b/meteor-collection-hooks/index.d.ts new file mode 100644 index 0000000000..8aaf03f91d --- /dev/null +++ b/meteor-collection-hooks/index.d.ts @@ -0,0 +1,159 @@ +// Type definitions for Meteor package matb33:collection-hooks 0.8 +// Project: https://github.com/matb33/meteor-collection-hooks +// Definitions by: Trygve Wastvedt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Mongo { + interface Collection { + before: { + find(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + findOne(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + insert(hook: ( + userId: string, + doc: T + ) => void + ): void; + remove(hook: ( + userId: string, + doc: T + ) => void + ): void; + update(hook: ( + userId: string, + doc: T, + fieldNames: string[], + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + upsert(hook: ( + userId: string, + doc: T, + selector: Mongo.Selector, + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + }; + after: { + find(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions, + cursor: Mongo.Cursor + ) => void + ): void; + findOne(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions, + doc: T + ) => void + ): void; + insert(hook: ( + userId: string, + doc: T + ) => void + ): void; + remove(hook: ( + userId: string, + doc: T + ) => void + ): void; + update(hook: ( + userId: string, + doc: T, + fieldNames: string[], + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void, + options?: CollectionHooks.HookOptionValue + ): void; + upsert(hook: ( + userId: string, + doc: T, + selector: Mongo.Selector, + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + }; + direct: { + find(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + limit?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: (doc: any) => void; + }): Mongo.Cursor; + findOne(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: (doc: any) => void; + }): T; + insert( + doc: T, + callback?: () => void + ): string; + remove( + selector: Mongo.Selector | Mongo.ObjectID | string, callback?: () => void + ): number; + update( + selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, + callback?: () => void + ): number; + upsert( + selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { + multi?: boolean; + }, + callback?: () => void + ): { numberAffected?: number; insertedId?: string; }; + }; + hookOptions: CollectionHooks.GlobalHookOptions; + } +} + +declare namespace CollectionHooks { + interface ModifierOptions { + multi?: boolean; + upsert?: boolean; + } + + interface HookOptionValue { + fetchPrevious?: boolean; + } + + interface LocalHookOptions { + all?: HookOptionValue; + find?: HookOptionValue; + findOne?: HookOptionValue; + insert?: HookOptionValue; + remove?: HookOptionValue; + update?: HookOptionValue; + upsert?: HookOptionValue; + } + + interface GlobalHookOptions { + before?: LocalHookOptions; + after?: LocalHookOptions; + all?: LocalHookOptions; + } +} \ No newline at end of file diff --git a/meteor-collection-hooks/meteor-collection-hooks-tests.ts b/meteor-collection-hooks/meteor-collection-hooks-tests.ts new file mode 100644 index 0000000000..b8c0c63247 --- /dev/null +++ b/meteor-collection-hooks/meteor-collection-hooks-tests.ts @@ -0,0 +1,79 @@ +/// + +interface Model { + _id: string; + value: number; +} + +const Collection = new Mongo.Collection("test_collection"); +let cursor: Mongo.Cursor; +let doc: Model; + +const selector = { + sort: { createdAt: -1 }, + skip: 5, + limit: 5, + fields: { createdAt: 1 }, + reacrive: true, + transform: () => {} +}; + +Collection.before.find((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }) => {}); +Collection.before.findOne((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }) => {}); +Collection.before.insert((userId: string, doc: Model) => {}); +Collection.before.remove((userId: string, doc: Model) => {}); +Collection.before.update((userId: string, doc: Model, fieldNames: string[], modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}); +Collection.before.upsert((userId: string, doc: Model, selector: Mongo.Selector, modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}); + +Collection.after.find((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }, cursor: Mongo.Cursor) => {}); +Collection.after.findOne((userId: string, selector: Mongo.Selector, options: { multi?: boolean; upsert?: boolean; }, doc: Model) => {}); +Collection.after.insert((userId: string, doc: Model) => {}); +Collection.after.remove((userId: string, doc: Model) => {}); +Collection.after.update((userId: string, doc: Model, fieldNames: string[], modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}, { fetchPrevious: true }); +Collection.after.upsert((userId: string, doc: Model, selector: Mongo.Selector, modifier: Mongo.Modifier, options: { multi?: boolean; upsert?: boolean; }) => {}); + +cursor = Collection.direct.find({ _id: doc._id }, { sort: { createdAt: -1 }, skip: 5, limit: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); +cursor = Collection.direct.find(doc._id, { sort: { createdAt: -1 }, skip: 5, limit: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); + +doc = Collection.direct.findOne({ _id: doc._id }, { sort: { createdAt: -1 }, skip: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); +doc = Collection.direct.findOne(doc._id, { sort: { createdAt: -1 }, skip: 5, fields: { createdAt: 1 }, reactive: true, transform: () => {} }); + +doc._id = Collection.direct.insert(doc, () => {}); + +doc.value = Collection.direct.remove({ _id: doc._id }, () => {}); +doc.value = Collection.direct.remove(doc._id, () => {}); + +doc.value = Collection.direct.update({ _id: doc._id }, { $inc: { votes: 2 } }, { multi: true, upsert: true }, () => {}); +doc.value = Collection.direct.update(doc._id, { $inc: { votes: 2 } }, { multi: true, upsert: true }, () => {}); + +let { numberAffected, insertedId }: { numberAffected?: number; insertedId?: string; } = Collection.direct.upsert(doc._id, { $inc: { votes: 2 } }, { multi: true }, () => {}); + +Collection.hookOptions = { + before: { + all: { fetchPrevious: true }, + find: { fetchPrevious: true }, + findOne: { fetchPrevious: true }, + insert: { fetchPrevious: true }, + remove: { fetchPrevious: true }, + update: { fetchPrevious: true }, + upsert: { fetchPrevious: true } + }, + after: { + all: { fetchPrevious: true }, + find: { fetchPrevious: true }, + findOne: { fetchPrevious: true }, + insert: { fetchPrevious: true }, + remove: { fetchPrevious: true }, + update: { fetchPrevious: true }, + upsert: { fetchPrevious: true } + }, + all: { + all: { fetchPrevious: true }, + find: { fetchPrevious: true }, + findOne: { fetchPrevious: true }, + insert: { fetchPrevious: true }, + remove: { fetchPrevious: true }, + update: { fetchPrevious: true }, + upsert: { fetchPrevious: true } + } +}; \ No newline at end of file diff --git a/meteor-collection-hooks/meteor-mongo.d.ts b/meteor-collection-hooks/meteor-mongo.d.ts new file mode 100644 index 0000000000..d45bd7582a --- /dev/null +++ b/meteor-collection-hooks/meteor-mongo.d.ts @@ -0,0 +1,154 @@ +declare module 'meteor/mongo' { + namespace Mongo { + interface Collection { + before: { + find(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + findOne(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + insert(hook: ( + userId: string, + doc: T + ) => void + ): void; + remove(hook: ( + userId: string, + doc: T + ) => void + ): void; + update(hook: ( + userId: string, + doc: T, + fieldNames: string[], + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + upsert(hook: ( + userId: string, + doc: T, + selector: Mongo.Selector, + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + }; + after: { + find(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions, + cursor: Mongo.Cursor + ) => void + ): void; + findOne(hook: ( + userId: string, + selector: Mongo.Selector, + options: CollectionHooks.ModifierOptions, + doc: T + ) => void + ): void; + insert(hook: ( + userId: string, + doc: T + ) => void + ): void; + remove(hook: ( + userId: string, + doc: T + ) => void + ): void; + update(hook: ( + userId: string, + doc: T, + fieldNames: string[], + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void, + options?: CollectionHooks.HookOptionValue + ): void; + upsert(hook: ( + userId: string, + doc: T, + selector: Mongo.Selector, + modifier: Mongo.Modifier, + options: CollectionHooks.ModifierOptions + ) => void + ): void; + }; + direct: { + find(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + limit?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: (doc: any) => void; + }): Mongo.Cursor; + findOne(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: (doc: any) => void; + }): T; + insert( + doc: T, + callback?: () => void + ): string; + remove( + selector: Mongo.Selector | Mongo.ObjectID | string, callback?: () => void + ): number; + update( + selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, + callback?: () => void + ): number; + upsert( + selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { + multi?: boolean; + }, + callback?: () => void + ): { numberAffected?: number; insertedId?: string; }; + }; + hookOptions: CollectionHooks.GlobalHookOptions; + } + } + + namespace CollectionHooks { + interface ModifierOptions { + multi?: boolean; + upsert?: boolean; + } + + interface HookOptionValue { + fetchPrevious?: boolean; + } + + interface LocalHookOptions { + all?: HookOptionValue; + find?: HookOptionValue; + findOne?: HookOptionValue; + insert?: HookOptionValue; + remove?: HookOptionValue; + update?: HookOptionValue; + upsert?: HookOptionValue; + } + + interface GlobalHookOptions { + before?: LocalHookOptions; + after?: LocalHookOptions; + all?: LocalHookOptions; + } + } +} \ No newline at end of file diff --git a/meteor-collection-hooks/package.json b/meteor-collection-hooks/package.json new file mode 100644 index 0000000000..39dfad28b6 --- /dev/null +++ b/meteor-collection-hooks/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "meteor-typings": "^1.3.1" + } +} diff --git a/meteor-collection-hooks/tsconfig.json b/meteor-collection-hooks/tsconfig.json new file mode 100644 index 0000000000..90fa93f2b5 --- /dev/null +++ b/meteor-collection-hooks/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "meteor-collection-hooks-tests.ts" + ] +} \ No newline at end of file diff --git a/meteor-collection-hooks/tslint.json b/meteor-collection-hooks/tslint.json new file mode 100644 index 0000000000..0b14fdec0d --- /dev/null +++ b/meteor-collection-hooks/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/meteor/index.d.ts b/meteor/index.d.ts index e411947122..0eb949e57b 100644 --- a/meteor/index.d.ts +++ b/meteor/index.d.ts @@ -428,6 +428,7 @@ declare namespace Accounts { function onCreateUser(func: Function): void; function validateLoginAttempt(cb: (params: Accounts.IValidateLoginAttemptCbOpts) => boolean): { stop: () => void }; function validateNewUser(func: Function): boolean; + function _hashPassword(password: string): { digest: string; algorithm: string; }; } declare namespace App { diff --git a/metismenu/index.d.ts b/metismenu/index.d.ts index 43faa279c7..8117328bf8 100644 --- a/metismenu/index.d.ts +++ b/metismenu/index.d.ts @@ -1,19 +1,22 @@ -// Type definitions for metisMenu 2.0.3 +// Type definitions for metisMenu 2.6 // Project: http://github.com/onokumus/metisMenu -// Definitions by: onokums +// Definitions by: onokums , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// interface MetisMenuOptions { toggle?: boolean; - doubleTapToGo?: boolean; activeClass?: string; collapseClass?: string; collapseInClass?: string; collapsingClass?: string; + preventDefault?: boolean; } +type MetisMenuEvents = "show.metisMenu" | "shown.metisMenu" | "hide.metisMenu" | "hidden.metisMenu"; + interface JQuery { - metisMenu(options?: MetisMenuOptions): JQuery; + metisMenu(options?: MetisMenuOptions | "dispose"): JQuery; + on(events: MetisMenuEvents, handler: (eventObject: JQueryEventObject) => any): JQuery; } diff --git a/metismenu/metismenu-tests.ts b/metismenu/metismenu-tests.ts index b2e36f1d53..eb17270021 100644 --- a/metismenu/metismenu-tests.ts +++ b/metismenu/metismenu-tests.ts @@ -1,12 +1,28 @@ /// $('#menu').metisMenu(); + $('.metismenu').metisMenu({toggle: false}); + $('.test').metisMenu({ toggle: false, - doubleTapToGo: true, activeClass: 'active', collapseClass: 'collapse', collapseInClass: 'in', - collapsingClass: 'collapsing' + collapsingClass: 'collapsing', + preventDefault: true }); + +$('.metismenu').metisMenu('dispose'); + +$('.metismenu') + .metisMenu() + .on('show.metisMenu', function(e) { + // empty logic + }).on('shown.metisMenu', function(e) { + // empty logic + }).on('hide.metisMenu', function(e) { + // empty logic + }).on('hidden.metisMenu', function(e) { + // empty logic + }); diff --git a/mobservable-react/index.d.ts b/mobservable-react/index.d.ts index a5f77cf5d4..4c035c2b5f 100644 --- a/mobservable-react/index.d.ts +++ b/mobservable-react/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mweststrate/mobservable-react // Definitions by: Michel Weststrate // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; diff --git a/mobservable/index.d.ts b/mobservable/index.d.ts index 1fcd580045..719eddaf31 100644 --- a/mobservable/index.d.ts +++ b/mobservable/index.d.ts @@ -1,179 +1,170 @@ -// Type definitions for mobservable v0.6.10 +// Type definitions for mobservable 0.6 // Project: https://mweststrate.github.io/mobservable // Definitions by: Michel Weststrate // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface _IMobservableStatic { - /** - * Turns an object, array or function into a reactive structure. - * @param value the value which should become observable. - */ - makeReactive: IMakeReactive; - - /** - * Extends an object with reactive capabilities. - * @param target the object to which reactive properties should be added - * @param properties the properties that should be added and made reactive - * @returns targer - */ - extendReactive(target: Object, properties: Object):Object; - - /** - * Returns true if the provided value is reactive. - * @param value object, function or array - * @param propertyName if propertyName is specified, checkes whether value.propertyName is reactive. - */ - isReactive(value: any, propertyName?:string): boolean; - - /** - * Can be used in combination with makeReactive / extendReactive. - * Enforces that a reference to 'value' is stored as property, - * but that 'value' itself is not turned into something reactive. - * Future assignments to the same property will inherit this behavior. - * @param value initial value of the reactive property that is being defined. - */ - asReference(value: any):{value:T}; - - /** - * ES6 / Typescript decorator which can to make class properties and getter functions reactive. - */ - observable(target: Object, key: string):any; // decorator / annotation - - /** - * Creates a reactive view and keeps it alive, so that the view is always - * updated if one of the dependencies changes, even when the view is not further used by something else. - * @param func The reactive view - * @param scope (optional) - * @returns disposer function, which can be used to stop the view from being updated in the future. - */ - observe(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * Deprecated, use mobservable.observe instead. - */ - sideEffect(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * Similar to 'observer', observes the given predicate until it returns true. - * Once it returns true, the 'effect' function is invoked an the observation is cancelled. - * @param predicate - * @param effect - * @param scope (optional) - * @returns disposer function to prematurely end the observer. - */ - observeUntil(predicate: ()=>boolean, effect: Mobservable.Lambda, scope?: any): Mobservable.Lambda; - - /** - * During a transaction no views are updated until the end of the transaction. - * The transaction will be run synchronously nonetheless. - * @param action a function that updates some reactive state - * @returns any value that was returned by the 'action' parameter. - */ - transaction(action: ()=>T): T; - - /** - * Converts a reactive structure into a non-reactive structure. - * Basically a deep-clone. - */ - toJSON(value: T): T; - - /** - * Sets the reporting level Defaults to 1. Use 0 for production or 2 for increased verbosity. - */ - logLevel: number; // 0 = production, 1 = development, 2 = debugging - - extras: { - getDependencyTree(thing:any, property?:string): Mobservable.IDependencyTree; - - getObserverTree(thing:any, property?:string): Mobservable.IObserverTree; - - trackTransitions(extensive?:boolean, onReport?:(lines:Mobservable.ITransitionEvent) => void) : Mobservable.Lambda; - } -} - -interface IMakeReactive { - (value: T[], opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableArray; - (value: ()=>T, opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableValue; - (value: T, opts?: Mobservable.IMakeReactiveOptions): Mobservable.IObservableValue; - (value: Object, opts?: Mobservable.IMakeReactiveOptions): T; -} - -interface IMobservableStatic extends _IMobservableStatic, IMakeReactive { -} - declare namespace Mobservable { - interface IMakeReactiveOptions { - as?: string /* "auto" | "reference" | TODO: see #8 "structure" */ - scope?: Object, - context?: Object, - recurse?: boolean; + interface Static extends MakeReactive { + /** + * Turns an object, array or function into a reactive structure. + * @param value the value which should become observable. + */ + makeReactive: MakeReactive; + + /** + * Extends an object with reactive capabilities. + * @param target the object to which reactive properties should be added + * @param properties the properties that should be added and made reactive + * @returns targer + */ + extendReactive(target: Object, properties: Object): Object; + + /** + * Returns true if the provided value is reactive. + * @param value object, function or array + * @param propertyName if propertyName is specified, checkes whether value.propertyName is reactive. + */ + isReactive(value: any, propertyName?: string): boolean; + + /** + * Can be used in combination with makeReactive / extendReactive. + * Enforces that a reference to 'value' is stored as property, + * but that 'value' itself is not turned into something reactive. + * Future assignments to the same property will inherit this behavior. + * @param value initial value of the reactive property that is being defined. + */ + asReference(value: any): {value: T}; + + /** + * ES6 / Typescript decorator which can to make class properties and getter functions reactive. + */ + observable(target: Object, key: string): any; // decorator / annotation + + /** + * Creates a reactive view and keeps it alive, so that the view is always + * updated if one of the dependencies changes, even when the view is not further used by something else. + * @param func The reactive view + * @param scope (optional) + * @returns disposer function, which can be used to stop the view from being updated in the future. + */ + observe(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * Deprecated, use mobservable.observe instead. + */ + sideEffect(func: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * Similar to 'observer', observes the given predicate until it returns true. + * Once it returns true, the 'effect' function is invoked an the observation is cancelled. + * @param predicate + * @param effect + * @param scope (optional) + * @returns disposer function to prematurely end the observer. + */ + observeUntil(predicate: () => boolean, effect: Mobservable.Lambda, scope?: any): Mobservable.Lambda; + + /** + * During a transaction no views are updated until the end of the transaction. + * The transaction will be run synchronously nonetheless. + * @param action a function that updates some reactive state + * @returns any value that was returned by the 'action' parameter. + */ + transaction(action: () => T): T; + + /** + * Converts a reactive structure into a non-reactive structure. + * Basically a deep-clone. + */ + toJSON(value: T): T; + + /** + * Sets the reporting level Defaults to 1. Use 0 for production or 2 for increased verbosity. + */ + logLevel: number; // 0 = production, 1 = development, 2 = debugging + + extras: { + getDependencyTree(thing: any, property?: string): Mobservable.DependencyTree; + + getObserverTree(thing: any, property?: string): Mobservable.ObserverTree; + + trackTransitions(extensive?: boolean, onReport?: (lines: Mobservable.TransitionEvent) => void): Mobservable.Lambda; + }; + } + + interface MakeReactive { + (value: T[], opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableArray; + (value: () => T, opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableValue; + (value: T, opts?: Mobservable.MakeReactiveOptions): Mobservable.ObservableValue; + (value: Object, opts?: Mobservable.MakeReactiveOptions): T; + } + + interface MakeReactiveOptions { + as?: string; /* "auto" | "reference" | TODO: see #8 "structure" */ + scope?: Object; + context?: Object; + recurse?: boolean; name?: string; - // protected: boolean TODO: see #9 + // protected: boolean TODO: see #9 } - export interface IContextInfoStruct { - object: Object; - name: string; - } - - export type IContextInfo = IContextInfoStruct | string; + type ContextInfo = { object: Object; name: string } | string; interface Lambda { (): void; name?: string; } - interface IObservable { - observe(callback: (...args: any[])=>void, fireImmediately?: boolean): Lambda; + interface Observable { + observe(callback: (...args: any[]) => void, fireImmediately?: boolean): Lambda; } - interface IObservableValue extends IObservable { + interface ObservableValue extends Observable { (): T; - (value: T):void; - observe(callback: (newValue: T, oldValue: T)=>void, fireImmediately?: boolean): Lambda; + (value: T): void; + observe(callback: (newValue: T, oldValue: T) => void, fireImmediately?: boolean): Lambda; } - interface IObservableArray extends IObservable, Array { + interface ObservableArray extends Observable, Array { spliceWithArray(index: number, deleteCount?: number, newItems?: T[]): T[]; - observe(listener: (changeData: IArrayChange|IArraySplice)=>void, fireImmediately?: boolean): Lambda; + observe(listener: (changeData: ArrayChange|ArraySplice) => void, fireImmediately?: boolean): Lambda; clear(): T[]; replace(newItems: T[]): T[]; - find(predicate: (item: T,index: number,array: IObservableArray)=>boolean,thisArg?: any,fromIndex?: number): T; + find(predicate: (item: T, index: number, array: ObservableArray) => boolean, thisArg?: any, fromIndex?: number): T; remove(value: T): boolean; } - interface IArrayChange { - type: string; // Always: 'update' - object: IObservableArray; - index: number; - oldValue: T; + interface ArrayChange { + type: string; // Always: 'update' + object: ObservableArray; + index: number; + oldValue: T; } - interface IArraySplice { - type: string; // Always: 'splice' - object: IObservableArray; - index: number; - removed: T[]; - addedCount: number; + interface ArraySplice { + type: string; // Always: 'splice' + object: ObservableArray; + index: number; + removed: T[]; + addedCount: number; } - interface IDependencyTree { + interface DependencyTree { id: number; name: string; context: any; - dependencies?: IDependencyTree[]; + dependencies?: DependencyTree[]; } - interface IObserverTree { + interface ObserverTree { id: number; name: string; context: any; - observers?: IObserverTree[]; + observers?: ObserverTree[]; listeners?: number; // amount of functions manually attached using an .observe method } - interface ITransitionEvent { + interface TransitionEvent { id: number; name: string; context: Object; @@ -183,7 +174,5 @@ declare namespace Mobservable { } } -declare module "mobservable" { - var m : IMobservableStatic; - export = m; -} +declare const Mobservable: Mobservable.Static; +export = Mobservable; diff --git a/mobservable/mobservable-tests.ts b/mobservable/mobservable-tests.ts index 07088d5d87..060f0d14b3 100644 --- a/mobservable/mobservable-tests.ts +++ b/mobservable/mobservable-tests.ts @@ -4,12 +4,12 @@ import {observable} from "mobservable"; var v = mobservable(3); v.observe(() => {}); -var a = mobservable([1,2,3]); +var a = mobservable([1, 2, 3]); class Order { - @observable price:number = 3; - @observable amount:number = 2; - @observable orders:string[] = []; + @observable price: number = 3; + @observable amount: number = 2; + @observable orders: string[] = []; @observable get total() { return this.amount * this.price * (1 + this.orders.length); @@ -22,12 +22,12 @@ export function testObservable() { } export function testAnnotations() { - var order1totals:number[] = []; + var order1totals: number[] = []; var order1 = new Order(); var order2 = new Order(); var disposer = mobservable.observe(() => { - order1totals.push(order1.total) + order1totals.push(order1.total); }); order2.price = 4; @@ -35,22 +35,22 @@ export function testAnnotations() { order2.orders.push('bla'); - order1.orders.splice(0,0,'boe', 'hoi'); + order1.orders.splice(0, 0, 'boe', 'hoi'); disposer(); order1.orders.pop(); }; export function testTyping() { - var ar:Mobservable.IObservableArray = mobservable.makeReactive([1,2]); - ar.observe((d:Mobservable.IArrayChange|Mobservable.IArraySplice) => { + var ar: mobservable.ObservableArray = mobservable.makeReactive([1, 2]); + ar.observe((d: mobservable.ArrayChange | mobservable.ArraySplice) => { console.log(d.type); }); - var ar2:Mobservable.IObservableArray = mobservable([1,2]); - ar2.observe((d:Mobservable.IArrayChange|Mobservable.IArraySplice) => { + var ar2: mobservable.ObservableArray = mobservable([1, 2]); + ar2.observe((d: mobservable.ArrayChange | mobservable.ArraySplice) => { console.log(d.type); }); - var x:Mobservable.IObservableValue = mobservable(3); + var x: mobservable.ObservableValue = mobservable(3); } \ No newline at end of file diff --git a/mobservable/tsconfig.json b/mobservable/tsconfig.json index 26c2a7df47..cee6db4b01 100644 --- a/mobservable/tsconfig.json +++ b/mobservable/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/mobservable/tslint.json b/mobservable/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/mobservable/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 41d08c685d..40210dc69d 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -120,6 +120,7 @@ declare namespace Mocha { interface IHookCallbackContext { skip(): void; timeout(ms: number): void; + [index: string]: any; } @@ -128,6 +129,7 @@ declare namespace Mocha { timeout(ms: number): void; retries(n: number): void; slow(ms: number): void; + [index: string]: any; } /** Partial interface for Mocha's `Runnable` class. */ diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index fc17a18221..8e8dc0d938 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -47,6 +47,8 @@ function test_it() { it('does something', () => { }); + it('does something', function () { this['sharedState'] = true; }); + it('does something', (done) => { done(); }); it.only('does something', () => { }); @@ -64,6 +66,8 @@ function test_test() { test('does something', () => { }); + test('does something', function () { this['sharedState'] = true; }); + test('does something', (done) => { done(); }); test.only('does something', () => { }); @@ -81,6 +85,8 @@ function test_specify() { specify('does something', () => { }); + specify('does something', function () { this['sharedState'] = true; }); + specify('does something', (done) => { done(); }); specify.only('does something', () => { }); @@ -97,6 +103,8 @@ function test_specify() { function test_before() { before(() => { }); + before(function () { this['sharedState'] = true; }); + before((done) => { done(); }); before("my description", () => { }); @@ -120,6 +128,17 @@ function test_setup() { string = this.currentTest.state; }); + setup(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + setup(function (done) { done(); boolean = this.currentTest.async; @@ -135,6 +154,8 @@ function test_setup() { function test_after() { after(() => { }); + after(function () { this['sharedState'] = true; }); + after((done) => { done(); }); after("my description", () => { }); @@ -153,6 +174,17 @@ function test_teardown() { string = this.currentTest.state; }); + teardown(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + teardown(function(done) { done(); boolean = this.currentTest.async; @@ -176,6 +208,17 @@ function test_beforeEach() { string = this.currentTest.state; }); + beforeEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + beforeEach(function (done) { done(); boolean = this.currentTest.async; @@ -212,6 +255,8 @@ function test_beforeEach() { function test_suiteSetup() { suiteSetup(() => { }); + suiteSetup(function () { this['sharedState'] = true; }); + suiteSetup((done) => { done(); }); } @@ -226,6 +271,17 @@ function test_afterEach() { string = this.currentTest.state; }); + afterEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + afterEach(function (done) { done(); boolean = this.currentTest.async; @@ -263,6 +319,8 @@ function test_afterEach() { function test_suiteTeardown() { suiteTeardown(() => { }); + suiteTeardown(function () { this['sharedState'] = true; }); + suiteTeardown((done) => { done(); }); } diff --git a/mock-raf/index.d.ts b/mock-raf/index.d.ts index 4d87655042..bbcbe5e444 100644 --- a/mock-raf/index.d.ts +++ b/mock-raf/index.d.ts @@ -17,7 +17,10 @@ declare namespace MockRaf { /** Creates a mockRaf instance, exposing the functions you'll use to interact with the mock. */ interface Creator { - /** Returns the current now value of the mock. Starts at 0 and increases with each step() taken. Useful for stubbing out performance.now() or a polyfill when using requestAnimationFrame with timers. */ + /** + * Returns the current now value of the mock. Starts at 0 and increases with each step() taken. + * Useful for stubbing out performance.now() or a polyfill when using requestAnimationFrame with timers. + */ now(): number; /** Replacement for requestAnimationFrame or a polyfill.Adds a callback to be fired on the next step. */ diff --git a/mock-raf/tsconfig.json b/mock-raf/tsconfig.json index d035910a65..7d4b6c5a8e 100644 --- a/mock-raf/tsconfig.json +++ b/mock-raf/tsconfig.json @@ -1,20 +1,23 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "mock-raf-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mock-raf-tests.ts" + ] } \ No newline at end of file diff --git a/mock-raf/tslint.json b/mock-raf/tslint.json index fdc7cdc370..377cc837d4 100644 --- a/mock-raf/tslint.json +++ b/mock-raf/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/modernizr/index.d.ts b/modernizr/index.d.ts index a447f3acea..7fd0ffa316 100644 --- a/modernizr/index.d.ts +++ b/modernizr/index.d.ts @@ -1,382 +1,379 @@ -// Type definitions for Modernizr 3.2.0 +// Type definitions for Modernizr 3.2 // Project: http://modernizr.com/ -// Definitions by: Boris Yankov , Theodore Brown , Leon Yu +// Definitions by: Boris Yankov , Theodore Brown , Leon Yu , Luca Trazzi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = Modernizr; // support AMD require -export as namespace Modernizr; // keep a global namespace - -declare namespace __Modernizr { - interface AudioBoolean { - ogg: boolean; - mp3: boolean; - wav: boolean; - m4a: boolean; - } - - interface VideoBoolean { - ogg: boolean; - h264: boolean; - webm: boolean; - } - - interface InputBoolean { - autocomplete: boolean; - autofocus: boolean; - list: boolean; - placeholder: boolean; - max: boolean; - min: boolean; - multiple: boolean; - pattern: boolean; - required: boolean; - step: boolean; - } - - interface InputTypesBoolean { - color: boolean; - date: boolean; - datetime: boolean; - "datetime-local": boolean; - email: boolean; - month: boolean; - number: boolean; - range: boolean; - search: boolean; - tel: boolean; - time: boolean; - url: boolean; - week: boolean; - } - - interface FeatureDetects { - // Documented - - ambientlight: boolean; - applicationcache: boolean; - audio: AudioBoolean; - batteryapi: boolean; - blobconstructor: boolean; - canvas: boolean; - canvastext: boolean; - contenteditable: boolean; - contextmenu: boolean; - cookies: boolean; - cors: boolean; - cryptography: boolean; - customprotocolhandler: boolean; - customevent: boolean; - dart: boolean; - dataview: boolean; - emoji: boolean; - eventlistener: boolean; - exiforientation: boolean; - flash: boolean; - forcetouch: boolean; - fullscreen: boolean; - gamepads: boolean; - geolocation: boolean; - hashchange: boolean; - hiddenscroll: boolean; - history: boolean; - htmlimports: boolean; - ie8compat: boolean; - indexeddb: boolean; - indexeddbblob: boolean; - input: InputBoolean; - search: boolean; - inputtypes: InputTypesBoolean; - intl: boolean; - json: boolean; - ligatures: boolean; - olreversed: boolean; - mathml: boolean; - notification: boolean; - pagevisibility: boolean; - performance: boolean; - pointerevents: boolean; - pointerlock: boolean; - postmessage: boolean; - proximity: boolean; - queryselector: boolean; - quotamanagement: boolean; - requestanimationframe: boolean; - serviceworker: boolean; - svg: boolean; - templatestrings: boolean; - touchevents: boolean; - typedarrays: boolean; - unicoderange: boolean; - unicode: boolean; - userdata: boolean; - vibrate: boolean; - video: VideoBoolean; - vml: boolean; - webintents: boolean; - animation: boolean; - webgl: boolean; - websockets: boolean; - xdomainrequest: boolean; - adownload: boolean; - audioloop: boolean; - audiopreload: boolean; - webaudio: boolean; - lowbattery: boolean; - canvasblending: boolean; - todataurljpeg: boolean; - todataurlpng: boolean; - todataurlwebp: boolean; - canvaswinding: boolean; - getrandomvalues: boolean; - cssall: boolean; - cssanimations: boolean; - appearance: boolean; - backdropfilter: boolean; - backgroundblendmode: boolean; - backgroundcliptext: boolean; - bgpositionshorthand: boolean; - bgpositionxy: boolean; - bgrepeatspace: boolean; - bgrepeatround: boolean; - backgroundsize: boolean; - bgsizecover: boolean; - borderimage: boolean; - borderradius: boolean; - boxshadow: boolean; - boxsizing: boolean; - csscalc: boolean; - checked: boolean; - csschunit: boolean; - csscolumns: boolean; - cubicbezierrange: boolean; - "display-runin": boolean; - displaytable: boolean; - ellipsis: boolean; - cssescape: boolean; - cssexunit: boolean; - cssfilters: boolean; - flexbox: boolean; - flexboxlegacy: boolean; - flexboxtweener: boolean; - flexwrap: boolean; - fontface: boolean; - generatedcontent: boolean; - cssgradients: boolean; - csshairline: boolean; - hsla: boolean; - csshyphens: boolean; - softhyphens: boolean; - softhyphensfind: boolean; - cssinvalid: boolean; - lastchild: boolean; - cssmask: boolean; - mediaqueries: boolean; - multiplebgs: boolean; - nthchild: boolean; - objectfit: boolean; - opacity: boolean; - overflowscrolling: boolean; - csspointerevents: boolean; - csspositionsticky: boolean; - csspseudoanimations: boolean; - csspseudotransitions: boolean; - cssreflections: boolean; - regions: boolean; - cssremunit: boolean; - cssresize: boolean; - rgba: boolean; - cssscrollbar: boolean; - scrollsnappoints: boolean; - shapes: boolean; - siblinggeneral: boolean; - subpixelfont: boolean; - supports: boolean; - target: boolean; - textalignlast: boolean; - textshadow: boolean; - csstransforms: boolean; - csstransforms3d: boolean; - preserve3d: boolean; - csstransitions: boolean; - userselect: boolean; - cssvalid: boolean; - cssvhunit: boolean; - cssvmaxunit: boolean; - cssvminunit: boolean; - cssvwunit: boolean; - willchange: boolean; - wrapflow: boolean; - classlist: boolean; - createelementattrs: boolean; - "createelement-attrs": boolean; - dataset: boolean; - documentfragment: boolean; - hidden: boolean; - microdata: boolean; - mutationobserver: boolean; - bdi: boolean; - datalistelem: boolean; - details: boolean; - outputelem: boolean; - picture: boolean; - progressbar: boolean; - meter: boolean; - ruby: boolean; - template: boolean; - time: boolean; - texttrackapi: boolean; - track: boolean; - unknownelements: boolean; - es5array: boolean; - es5date: boolean; - es5function: boolean; - es5object: boolean; - es5: boolean; - strictmode: boolean; - es5string: boolean; - es5syntax: boolean; - es5undefined: boolean; - es6array: boolean; - es6collections: boolean; - contains: boolean; - generators: boolean; - es6math: boolean; - es6number: boolean; - es6object: boolean; - promises: boolean; - es6string: boolean; - devicemotion: boolean; - deviceorientation: boolean; - oninput: boolean; - filereader: boolean; - filesystem: boolean; - capture: boolean; - fileinput: boolean; - directory: boolean; - formattribute: boolean; - localizednumber: boolean; - placeholder: boolean; - requestautocomplete: boolean; - formvalidation: boolean; - sandbox: boolean; - seamless: boolean; - srcdoc: boolean; - apng: boolean; - imgcrossorigin: boolean; - jpeg2000: boolean; - jpegxr: boolean; - sizes: boolean; - srcset: boolean; - webpalpha: boolean; - webpanimation: boolean; - webplossless: boolean; - "webp-lossless": boolean; - webp: boolean; - inputformaction: boolean; - inputformenctype: boolean; - inputformmethod: boolean; - inputformtarget: boolean; - beacon: boolean; - lowbandwidth: boolean; - eventsource: boolean; - fetch: boolean; - xhrresponsetypearraybuffer: boolean; - xhrresponsetypeblob: boolean; - xhrresponsetypedocument: boolean; - xhrresponsetypejson: boolean; - xhrresponsetypetext: boolean; - xhrresponsetype: boolean; - xhr2: boolean; - scriptasync: boolean; - scriptdefer: boolean; - speechrecognition: boolean; - speechsynthesis: boolean; - localstorage: boolean; - sessionstorage: boolean; - websqldatabase: boolean; - stylescoped: boolean; - svgasimg: boolean; - svgclippaths: boolean; - svgfilters: boolean; - svgforeignobject: boolean; - inlinesvg: boolean; - smil: boolean; - textareamaxlength: boolean; - bloburls: boolean; - datauri: boolean; - urlparser: boolean; - videoautoplay: boolean; - videoloop: boolean; - videopreload: boolean; - webglextensions: boolean; - datachannel: boolean; - getusermedia: boolean; - peerconnection: boolean; - websocketsbinary: boolean; - atobbtoa: boolean; - framed: boolean; - matchmedia: boolean; - blobworkers: boolean; - dataworkers: boolean; - sharedworkers: boolean; - transferables: boolean; - webworkers: boolean; - - // Undocumented - usually aliases or new features - - "atob-btoa": boolean; - "battery-api": boolean; - "blob-constructor": boolean; - "display-table": boolean; - "input-formaction": boolean; - "input-formenctype": boolean; - "input-formtarget": boolean; - "object-fit": boolean; - crypto: boolean; - displayrunin: boolean; - fileinputdirectory: boolean; - hairline: boolean; - inputsearchevent: boolean; - raf: boolean; - webanimations: boolean; - } - - interface Dictionary { - [key: string]: T; - } - - interface ModernizrAPI { - on(feature: string, cb: (result: boolean) => any): void; - - addTest(feature: string, test: () => boolean): void; - addTest(feature: string, test: boolean): void; - addTest(feature: Dictionary): void; - - atRule(prop: string): boolean; - - _domPrefixes: string[]; - - hasEvent(eventName: string, element?: EventTarget): boolean; - - mq(mq: string): boolean; - - prefixed(prop: string): string; - prefixed(prop: string, obj: EventTarget, element?: boolean): any; - - prefixedCSS(prop: string): string; - - prefixedCSSValue(prop: string, value: string): string; - - _prefixes: string[]; - - testAllProps(prop: string, value?: string, skipValueTest?: boolean): boolean; - - testProp(prop: string, value?: string, useValue?: boolean): boolean; - - testStyles(rule: string, callback: (elem: HTMLDivElement, rule: string) => void, nodes?: number, testnames?: string[]): boolean; - } - - export interface ModernizrStatic extends ModernizrAPI, FeatureDetects { } +interface AudioBoolean { + ogg: boolean; + mp3: boolean; + wav: boolean; + m4a: boolean; } -declare var Modernizr: __Modernizr.ModernizrStatic; +interface VideoBoolean { + ogg: boolean; + h264: boolean; + webm: boolean; +} + +interface InputBoolean { + autocomplete: boolean; + autofocus: boolean; + list: boolean; + placeholder: boolean; + max: boolean; + min: boolean; + multiple: boolean; + pattern: boolean; + required: boolean; + step: boolean; +} + +interface InputTypesBoolean { + color: boolean; + date: boolean; + datetime: boolean; + "datetime-local": boolean; + email: boolean; + month: boolean; + number: boolean; + range: boolean; + search: boolean; + tel: boolean; + time: boolean; + url: boolean; + week: boolean; +} + +interface FeatureDetects { + // Documented + + ambientlight: boolean; + applicationcache: boolean; + audio: AudioBoolean; + batteryapi: boolean; + blobconstructor: boolean; + canvas: boolean; + canvastext: boolean; + contenteditable: boolean; + contextmenu: boolean; + cookies: boolean; + cors: boolean; + cryptography: boolean; + customprotocolhandler: boolean; + customevent: boolean; + dart: boolean; + dataview: boolean; + emoji: boolean; + eventlistener: boolean; + exiforientation: boolean; + flash: boolean; + forcetouch: boolean; + fullscreen: boolean; + gamepads: boolean; + geolocation: boolean; + hashchange: boolean; + hiddenscroll: boolean; + history: boolean; + htmlimports: boolean; + ie8compat: boolean; + indexeddb: boolean; + indexeddbblob: boolean; + input: InputBoolean; + search: boolean; + inputtypes: InputTypesBoolean; + intl: boolean; + json: boolean; + ligatures: boolean; + olreversed: boolean; + mathml: boolean; + notification: boolean; + pagevisibility: boolean; + performance: boolean; + pointerevents: boolean; + pointerlock: boolean; + postmessage: boolean; + proximity: boolean; + queryselector: boolean; + quotamanagement: boolean; + requestanimationframe: boolean; + serviceworker: boolean; + svg: boolean; + templatestrings: boolean; + touchevents: boolean; + typedarrays: boolean; + unicoderange: boolean; + unicode: boolean; + userdata: boolean; + vibrate: boolean; + video: VideoBoolean; + vml: boolean; + webintents: boolean; + animation: boolean; + webgl: boolean; + websockets: boolean; + xdomainrequest: boolean; + adownload: boolean; + audioloop: boolean; + audiopreload: boolean; + webaudio: boolean; + lowbattery: boolean; + canvasblending: boolean; + todataurljpeg: boolean; + todataurlpng: boolean; + todataurlwebp: boolean; + canvaswinding: boolean; + getrandomvalues: boolean; + cssall: boolean; + cssanimations: boolean; + appearance: boolean; + backdropfilter: boolean; + backgroundblendmode: boolean; + backgroundcliptext: boolean; + bgpositionshorthand: boolean; + bgpositionxy: boolean; + bgrepeatspace: boolean; + bgrepeatround: boolean; + backgroundsize: boolean; + bgsizecover: boolean; + borderimage: boolean; + borderradius: boolean; + boxshadow: boolean; + boxsizing: boolean; + csscalc: boolean; + checked: boolean; + csschunit: boolean; + csscolumns: boolean; + cubicbezierrange: boolean; + "display-runin": boolean; + displaytable: boolean; + ellipsis: boolean; + cssescape: boolean; + cssexunit: boolean; + cssfilters: boolean; + flexbox: boolean; + flexboxlegacy: boolean; + flexboxtweener: boolean; + flexwrap: boolean; + fontface: boolean; + generatedcontent: boolean; + cssgradients: boolean; + csshairline: boolean; + hsla: boolean; + csshyphens: boolean; + softhyphens: boolean; + softhyphensfind: boolean; + cssinvalid: boolean; + lastchild: boolean; + cssmask: boolean; + mediaqueries: boolean; + multiplebgs: boolean; + nthchild: boolean; + objectfit: boolean; + opacity: boolean; + overflowscrolling: boolean; + csspointerevents: boolean; + csspositionsticky: boolean; + csspseudoanimations: boolean; + csspseudotransitions: boolean; + cssreflections: boolean; + regions: boolean; + cssremunit: boolean; + cssresize: boolean; + rgba: boolean; + cssscrollbar: boolean; + scrollsnappoints: boolean; + shapes: boolean; + siblinggeneral: boolean; + subpixelfont: boolean; + supports: boolean; + target: boolean; + textalignlast: boolean; + textshadow: boolean; + csstransforms: boolean; + csstransforms3d: boolean; + preserve3d: boolean; + csstransitions: boolean; + userselect: boolean; + cssvalid: boolean; + cssvhunit: boolean; + cssvmaxunit: boolean; + cssvminunit: boolean; + cssvwunit: boolean; + willchange: boolean; + wrapflow: boolean; + classlist: boolean; + createelementattrs: boolean; + "createelement-attrs": boolean; + dataset: boolean; + documentfragment: boolean; + hidden: boolean; + microdata: boolean; + mutationobserver: boolean; + bdi: boolean; + datalistelem: boolean; + details: boolean; + outputelem: boolean; + picture: boolean; + progressbar: boolean; + meter: boolean; + ruby: boolean; + template: boolean; + time: boolean; + texttrackapi: boolean; + track: boolean; + unknownelements: boolean; + es5array: boolean; + es5date: boolean; + es5function: boolean; + es5object: boolean; + es5: boolean; + strictmode: boolean; + es5string: boolean; + es5syntax: boolean; + es5undefined: boolean; + es6array: boolean; + es6collections: boolean; + contains: boolean; + generators: boolean; + es6math: boolean; + es6number: boolean; + es6object: boolean; + promises: boolean; + es6string: boolean; + devicemotion: boolean; + deviceorientation: boolean; + oninput: boolean; + filereader: boolean; + filesystem: boolean; + capture: boolean; + fileinput: boolean; + directory: boolean; + formattribute: boolean; + localizednumber: boolean; + placeholder: boolean; + requestautocomplete: boolean; + formvalidation: boolean; + sandbox: boolean; + seamless: boolean; + srcdoc: boolean; + apng: boolean; + imgcrossorigin: boolean; + jpeg2000: boolean; + jpegxr: boolean; + sizes: boolean; + srcset: boolean; + webpalpha: boolean; + webpanimation: boolean; + webplossless: boolean; + "webp-lossless": boolean; + webp: boolean; + inputformaction: boolean; + inputformenctype: boolean; + inputformmethod: boolean; + inputformtarget: boolean; + beacon: boolean; + lowbandwidth: boolean; + eventsource: boolean; + fetch: boolean; + xhrresponsetypearraybuffer: boolean; + xhrresponsetypeblob: boolean; + xhrresponsetypedocument: boolean; + xhrresponsetypejson: boolean; + xhrresponsetypetext: boolean; + xhrresponsetype: boolean; + xhr2: boolean; + scriptasync: boolean; + scriptdefer: boolean; + speechrecognition: boolean; + speechsynthesis: boolean; + localstorage: boolean; + sessionstorage: boolean; + websqldatabase: boolean; + stylescoped: boolean; + svgasimg: boolean; + svgclippaths: boolean; + svgfilters: boolean; + svgforeignobject: boolean; + inlinesvg: boolean; + smil: boolean; + textareamaxlength: boolean; + bloburls: boolean; + datauri: boolean; + urlparser: boolean; + videoautoplay: boolean; + videoloop: boolean; + videopreload: boolean; + webglextensions: boolean; + datachannel: boolean; + getusermedia: boolean; + peerconnection: boolean; + websocketsbinary: boolean; + atobbtoa: boolean; + framed: boolean; + matchmedia: boolean; + blobworkers: boolean; + dataworkers: boolean; + sharedworkers: boolean; + transferables: boolean; + webworkers: boolean; + + // Undocumented - usually aliases or new features + + "atob-btoa": boolean; + "battery-api": boolean; + "blob-constructor": boolean; + "display-table": boolean; + "input-formaction": boolean; + "input-formenctype": boolean; + "input-formtarget": boolean; + "object-fit": boolean; + crypto: boolean; + displayrunin: boolean; + fileinputdirectory: boolean; + hairline: boolean; + inputsearchevent: boolean; + raf: boolean; + webanimations: boolean; +} + +interface Dictionary { + [key: string]: T; +} + +interface ModernizrAPI { + on(feature: string, cb: (result: boolean) => any): void; + + addTest(feature: string, test: (() => boolean) | boolean): void; + addTest(feature: Dictionary): void; + + atRule(prop: string): boolean; + + _domPrefixes: string[]; + + hasEvent(eventName: string, element?: EventTarget): boolean; + + mq(mq: string): boolean; + + prefixed(prop: string): string; + prefixed(prop: string, obj: EventTarget, element?: boolean): any; + + prefixedCSS(prop: string): string; + + prefixedCSSValue(prop: string, value: string): string; + + _prefixes: string[]; + + testAllProps(prop: string, value?: string, skipValueTest?: boolean): boolean; + + testProp(prop: string, value?: string, useValue?: boolean): boolean; + + testStyles(rule: string, callback: (elem: HTMLDivElement, rule: string) => void, nodes?: number, testnames?: string[]): boolean; +} + +interface ModernizrStatic extends ModernizrAPI, FeatureDetects { } + +declare var Modernizr: ModernizrStatic; +declare module "Modernizr" { + export = Modernizr; +} diff --git a/modernizr/modernizr-tests.ts b/modernizr/modernizr-tests.ts index 1807a5f377..3e62ae478e 100644 --- a/modernizr/modernizr-tests.ts +++ b/modernizr/modernizr-tests.ts @@ -2,11 +2,11 @@ declare var $: any; -window.alert = function(thing?: string) { +window.alert = (thing?: string) => { $('#content').append('
' + thing + '
'); -} +}; -$(function () { +$(() => { var audio = new Audio(); audio.src = Modernizr.audio.ogg ? 'background.ogg' : Modernizr.audio.mp3 ? 'background.mp3' : @@ -30,15 +30,15 @@ $(function () { Modernizr.addTest('track', () => { var video = document.createElement('video'); - return typeof video.addTextTrack === 'function' + return typeof video.addTextTrack === 'function'; }); Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', (elem, rule) => { - Modernizr.addTest('width', elem.offsetWidth == 9); + Modernizr.addTest('width', elem.offsetWidth === 9); }); Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', (elem, rule) => { - Modernizr.addTest('width', elem.offsetWidth == 9); + Modernizr.addTest('width', elem.offsetWidth === 9); }, 2, ["video", "image"]); Modernizr.testProp('pointerEvents'); @@ -54,7 +54,7 @@ $(function () { }); -Modernizr.on('flash', function( result ) { +Modernizr.on('flash', result => { if (result) { // the browser has flash } else { @@ -62,7 +62,7 @@ Modernizr.on('flash', function( result ) { } }); -Modernizr.addTest('itsTuesday', function() { +Modernizr.addTest('itsTuesday', () => { var d = new Date(); return d.getDay() === 2; }); @@ -70,12 +70,12 @@ Modernizr.addTest('itsTuesday', function() { Modernizr.addTest('hasJquery', 'jQuery' in window); var detects = { - 'hasjquery': 'jQuery' in window, - 'itstuesday': function() { + hasjquery: 'jQuery' in window, + itstuesday: () => { var d = new Date(); return d.getDay() === 2; } -} +}; Modernizr.addTest(detects); var keyframes = Modernizr.atRule('@keyframes'); @@ -88,56 +88,56 @@ if (keyframes) { Modernizr._domPrefixes === [ "Moz", "O", "ms", "Webkit" ]; -Modernizr.hasEvent('blur') // true; +Modernizr.hasEvent('blur'); // true; -Modernizr.hasEvent('devicelight', window) // true; +Modernizr.hasEvent('devicelight', window); // true; var query = Modernizr.mq('(min-width: 900px)'); if (query) { // the browser window is larger than 900px } -Modernizr.prefixed('boxSizing') +Modernizr.prefixed('boxSizing'); var raf = Modernizr.prefixed('requestAnimationFrame', window); -raf(function() { +raf(() => { }); var rAFProp = Modernizr.prefixed('requestAnimationFrame', window, false); -rAFProp === 'WebkitRequestAnimationFrame' // in older webkit +rAFProp === 'WebkitRequestAnimationFrame'; // in older webkit -Modernizr.prefixedCSS('transition') // '-moz-transition' in old Firefox +Modernizr.prefixedCSS('transition'); // '-moz-transition' in old Firefox -Modernizr.prefixedCSSValue('background', 'linear-gradient(left, red, red)') +Modernizr.prefixedCSSValue('background', 'linear-gradient(left, red, red)'); var rule = Modernizr._prefixes.join('transform: rotate(20deg); '); -rule === 'transform: rotate(20deg); webkit-transform: rotate(20deg); moz-transform: rotate(20deg); o-transform: rotate(20deg); ms-transform: rotate(20deg);' +rule === 'transform: rotate(20deg); webkit-transform: rotate(20deg); moz-transform: rotate(20deg); o-transform: rotate(20deg); ms-transform: rotate(20deg);'; rule = 'display:' + Modernizr._prefixes.join('flex; display:') + 'flex'; -rule === 'display:flex; display:-webkit-flex; display:-moz-flex; display:-o-flex; display:-ms-flex; display:flex' +rule === 'display:flex; display:-webkit-flex; display:-moz-flex; display:-o-flex; display:-ms-flex; display:flex'; -Modernizr.testAllProps('boxSizing') // true -Modernizr.testAllProps('display', 'block') // true -Modernizr.testAllProps('display', 'penguin') // false +Modernizr.testAllProps('boxSizing'); // true +Modernizr.testAllProps('display', 'block'); // true +Modernizr.testAllProps('display', 'penguin'); // false Modernizr.testAllProps('shapeOutside', 'content-box', true); -Modernizr.testProp('pointerEvents') // true -Modernizr.testProp('pointerEvents', 'none') // true -Modernizr.testProp('pointerEvents', 'penguin') // false +Modernizr.testProp('pointerEvents'); // true +Modernizr.testProp('pointerEvents', 'none'); // true +Modernizr.testProp('pointerEvents', 'penguin'); // false -Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', function(elem, rule) { +Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', (elem, rule) => { // elem is the first DOM node in the page (by default #modernizr) // rule is the first argument you supplied - the CSS rule in string form - Modernizr.addTest('widthworks', elem.style.width === '9px') + Modernizr.addTest('widthworks', elem.style.width === '9px'); }); -Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', function(elem) { +Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', elem => { document.getElementById('modernizr').style.width === '1px'; // true document.getElementById('modernizr2').style.width === '2px'; // true elem.firstChild === document.getElementById('modernizr2'); // true }, 1); -Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', function(elem) { +Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', elem => { document.getElementById('modernizr').style.width === '1px'; // true document.getElementById('modernizr2').style.width === '2px'; // true elem.firstChild === document.getElementById('modernizr2'); // true diff --git a/modernizr/tslint.json b/modernizr/tslint.json new file mode 100644 index 0000000000..d8284f73b9 --- /dev/null +++ b/modernizr/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false, + "no-empty-interface": false + } +} diff --git a/modesl/index.d.ts b/modesl/index.d.ts new file mode 100644 index 0000000000..6b1c532bd3 --- /dev/null +++ b/modesl/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for modesl 1.1 +// Project: https://github.com/englercj/node-esl +// Definitions by: Nischit Ranganath +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import EventEmitter = NodeJS.EventEmitter; +export class Connection extends EventEmitter { + constructor(...args: any[]); + + api(command: any, args: string[], cb?: () => void): void; + + auth(cb: () => void): void; + + bgapi(command: any, args: string[], jobid?: any, cb?: () => void): void; + + connected(): any; + + disconnect(): void; + + events(type: 'json' | 'plain' | 'xml', events: string, cb?: () => void): void; + + execute(app: any, arg?: string, uuid?: string, cb?: () => void): any; + + executeAsync(app: any, arg?: string, uuid?: string, cb?: () => void): any; + + filter(header: any, value: any, cb?: () => void): void; + + filterDelete(header: any, value: any, cb?: () => void): void; + + getInfo(): any; + + message(options: any, cb?: () => void): void; + + originate(options: any, cb?: () => void): void; + + recvEvent(cb?: () => void): void; + + recvEventTimed(ms: any, cb?: () => void): void; + + send(command: any, args: any): void; + + sendEvent(event: any, cb?: () => void): void; + + sendRecv(command: any, args: any, cb?: () => void): void; + + setAsyncExecute(value: any): void; + + setEventLock(value: any): void; + + show(item: any, format: any, cb?: () => void): void; + + socketDescriptor(): any; + + subscribe(events: any, cb?: () => void): void; +} + +export interface Header { + name: string; + + value: string; +} + +export class Event { + constructor(type: any, subclass: any); + + headers: Header[]; + + addBody(value: any): any; + + addHeader(name: any, value: any): any; + + delHeader(name: any): any; + + firstHeader(): any; + + getBody(): any; + + getHeader(name: any): string; + + getType(): any; + + nextHeader(): any; + + serialize(format: any): any; + + setPriority(priority: any): void; + + static readonly PRIORITY: { + HIGH: string; + LOW: string; + NORMAL: string; + }; +} +export class Parser { + constructor(socket: any); +} +export class Server extends EventEmitter { + constructor(opts: any, readycb?: () => void); + + close(callback: any): void; +} +export function eslSetLogLevel(level: any): void; + +export function setLogLevel(level: any): void; + diff --git a/modesl/modesl-tests.ts b/modesl/modesl-tests.ts new file mode 100644 index 0000000000..c3788833d0 --- /dev/null +++ b/modesl/modesl-tests.ts @@ -0,0 +1,34 @@ +import * as modesl from 'modesl'; + +const freeswitchListener = new modesl.Server(() => { + // console.log('Server listening on localhost at port 8022'); +}); + + +const freeswitchConnection = new modesl.Connection("freeswitch-host", 8021, 'password', () => { + // console.log('connection initialized'); + + freeswitchConnection.api('conference', ['confname', 'dial', 'user/1006']); + + freeswitchConnection.bgapi('conference', ['confname', 'dial', 'user/1006'], 'job-id', () => { + // console.log('action queued'); + }); + + freeswitchConnection.events('json', 'all'); + + freeswitchConnection.subscribe('all'); + + freeswitchConnection.on('esl::event::*::*', (event: modesl.Event) => { + const headerValue = event.getHeader('header'); + + const body = event.getBody(); + + const headers = event.headers; + + headers.forEach((header: modesl.Header) => { + const headerName = header.name; + const headerValue = header.value; + }); + }); +}); + diff --git a/modesl/tsconfig.json b/modesl/tsconfig.json new file mode 100644 index 0000000000..bf010625e0 --- /dev/null +++ b/modesl/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "modesl-tests.ts" + ] +} diff --git a/modesl/tslint.json b/modesl/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/modesl/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/moment-round/index.d.ts b/moment-round/index.d.ts new file mode 100644 index 0000000000..441cec3f6f --- /dev/null +++ b/moment-round/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for moment-round 1.0 +// Project: https://github.com/WebDevTmas/moment-round +// Definitions by: Jacob Baskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as moment from 'moment'; + +export = moment; + +declare module 'moment' { + interface Moment { + round(precision: number, key: string, direction?: 'round' | 'ceil' | 'floor'): Moment; + ceil(precision: number, key: string): Moment; + floor(precision: number, key: string): Moment; + } +} diff --git a/moment-round/moment-round-tests.ts b/moment-round/moment-round-tests.ts new file mode 100644 index 0000000000..063e3cbea4 --- /dev/null +++ b/moment-round/moment-round-tests.ts @@ -0,0 +1,8 @@ +import * as moment from 'moment'; + +var m = moment(); +m.round(5, 'seconds'); +m.ceil(3, 'minutes'); +m.floor(16, 'hours'); +m.ceil(21, 'hours'); +m.ceil(20, 'hours'); diff --git a/moment-round/package.json b/moment-round/package.json new file mode 100644 index 0000000000..4c6d24a445 --- /dev/null +++ b/moment-round/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": ">=2.14.0" + } +} \ No newline at end of file diff --git a/moment-round/tsconfig.json b/moment-round/tsconfig.json new file mode 100644 index 0000000000..f0a73e2ecd --- /dev/null +++ b/moment-round/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", + "moment-round-tests.ts" + ] +} \ No newline at end of file diff --git a/moment-round/tslint.json b/moment-round/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/moment-round/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/moment-timezone/tslint.json b/moment-timezone/tslint.json index 012ccb0889..68d10d72a6 100644 --- a/moment-timezone/tslint.json +++ b/moment-timezone/tslint.json @@ -3,4 +3,4 @@ "rules": { "unified-signatures": false } -} \ No newline at end of file +} diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index bdf89c32f6..c37bac86cd 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -576,8 +576,10 @@ export interface Collection { // Get current index hint for collection. hint: any; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate - aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; - aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite bulkWrite(operations: Object[], callback: MongoCallback): void; bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise; @@ -616,15 +618,13 @@ export interface Collection { dropIndexes(): Promise; dropIndexes(callback?: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find - find(query?: Object): Cursor; + find(query?: Object): Cursor; + find(query?: Object): Cursor; /** @deprecated */ - find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; + find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne - /** @deprecated use find().limit(1).next(function(err, doc){}) */ findOne(filter: Object, callback: MongoCallback): void; - /** @deprecated use find().limit(1).next(function(err, doc){}) */ findOne(filter: Object, options?: FindOneOptions): Promise; - /** @deprecated use find().limit(1).next(function(err, doc){}) */ findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete findOneAndDelete(filter: Object, callback: MongoCallback): void; @@ -692,9 +692,9 @@ export interface Collection { options(): Promise; options(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#parallelCollectionScan - parallelCollectionScan(callback: MongoCallback): void; - parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise; - parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback): void; + parallelCollectionScan(callback: MongoCallback[]>): void; + parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise[]>; + parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback[]>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#reIndex reIndex(): Promise; reIndex(callback: MongoCallback): void; @@ -1119,24 +1119,24 @@ export interface WriteOpResult { export type CursorResult = any | void | boolean; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html -export interface Cursor extends Readable { +export class Cursor extends Readable { sortValue: string; timeout: boolean; readPreference: ReadPreference; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html - addCursorFlag(flag: string, value: boolean): Cursor; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addCursorFlag + addCursorFlag(flag: string, value: boolean): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#addQueryModifier - addQueryModifier(name: string, value: boolean): Cursor; + addQueryModifier(name: string, value: boolean): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#batchSize - batchSize(value: number): Cursor; + batchSize(value: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#clone - clone(): Cursor; + clone(): Cursor; // still returns the same type // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close close(): Promise; close(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#comment - comment(value: string): Cursor; + comment(value: string): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#count count(applySkipLimit: boolean, callback: MongoCallback): void; count(applySkipLimit: boolean, options?: CursorCommentOptions): Promise; @@ -1145,64 +1145,58 @@ export interface Cursor extends Readable { explain(): Promise; explain(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#filter - filter(filter: Object): Cursor; + filter(filter: Object): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#forEach - forEach(iterator: IteratorCallback, callback: EndCallback): void; + forEach(iterator: IteratorCallback, callback: EndCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#hasNext hasNext(): Promise; hasNext(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#hint - hint(hint: Object): Cursor; + hint(hint: Object): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#isClosed isClosed(): boolean; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#limit - limit(value: number): Cursor; + limit(value: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#map - map(transform: Function): Cursor; + map(transform: Function): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#max - max(max: number): Cursor; + max(max: number): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxAwaitTimeMS - maxAwaitTimeMS(value: number): Cursor; + maxAwaitTimeMS(value: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxScan - maxScan(maxScan: Object): Cursor; + maxScan(maxScan: Object): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxTimeMS - maxTimeMS(value: number): Cursor; + maxTimeMS(value: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#min - min(min: number): Cursor; + min(min: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe - pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project - project(value: Object): Cursor; + project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read read(size: number): string | Buffer | void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next - returnKey(returnKey: Object): Cursor; + returnKey(returnKey: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#rewind rewind(): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption - setCursorOption(field: string, value: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding - setEncoding(encoding: string): void; + setCursorOption(field: string, value: Object): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference - setReadPreference(readPreference: string | ReadPreference): Cursor; + setReadPreference(readPreference: string | ReadPreference): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId - showRecordId(showRecordId: Object): Cursor; + showRecordId(showRecordId: Object): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#skip - skip(value: number): Cursor; + skip(value: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#snapshot - snapshot(snapshot: Object): Cursor; + snapshot(snapshot: Object): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#sort - sort(keyOrList: string | Object[] | Object | Object, direction?: number): Cursor; + sort(keyOrList: string | Object[] | Object, direction?: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#stream - stream(options?: { transform?: Function }): Cursor; + stream(options?: { transform?: Function }): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#toArray - toArray(): Promise; - toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe - unpipe(destination?: Writable): void; + toArray(): Promise; + toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift unshift(stream: Buffer | string): void; } @@ -1217,8 +1211,8 @@ export interface CursorCommentOptions { } //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~iteratorCallback -export interface IteratorCallback { - (doc: any): void; +export interface IteratorCallback { + (doc: T): void; } //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~endCallback @@ -1228,13 +1222,12 @@ export interface EndCallback { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#~resultCallback export type AggregationCursorResult = any | void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html -export interface AggregationCursor extends Readable { +export class AggregationCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#batchSize - batchSize(value: number): AggregationCursor; + batchSize(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#clone - clone(): AggregationCursor; + clone(): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#close close(): Promise; close(callback: MongoCallback): void; @@ -1244,51 +1237,45 @@ export interface AggregationCursor extends Readable { explain(): Promise; explain(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#geoNear - geoNear(document: Object): AggregationCursor; + geoNear(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#group - group(document: Object): AggregationCursor; + group(document: Object): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#isClosed isClosed(): boolean; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#limit - limit(value: number): AggregationCursor; + limit(value: number): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#match - match(document: Object): AggregationCursor; + match(document: Object): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#maxTimeMS - maxTimeMS(value: number): AggregationCursor; + maxTimeMS(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#next next(): Promise; next(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out - out(destination: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe - pipe(destination: Writable, options?: Object): void; + out(destination: string): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project - project(document: Object): AggregationCursor; + project(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#redact - redact(document: Object): AggregationCursor; + redact(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind - rewind(): AggregationCursor; + rewind(): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding - setEncoding(encoding: string): void; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip - skip(value: number): AggregationCursor; + skip(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort - sort(document: Object): AggregationCursor; + sort(document: Object): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray - toArray(): Promise; - toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe - unpipe(destination?: Writable): void; + toArray(): Promise; + toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift unshift(stream: Buffer | string): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind - unwind(field: string): AggregationCursor; + unwind(field: string): AggregationCursor; } //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html -export interface CommandCursor extends Readable { +export class CommandCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#batchSize batchSize(value: number): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#clone @@ -1305,21 +1292,15 @@ export interface CommandCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe - pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind rewind(): CommandCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding - setEncoding(encoding: string): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe - unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift unshift(stream: Buffer | string): void; } @@ -1332,7 +1313,7 @@ export class GridFSBucket { // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#drop drop(callback?: GridFSBucketErrorCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#find - find(filter?: Object, options?: GridFSBucketFindOptions): Cursor; + find(filter?: Object, options?: GridFSBucketFindOptions): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#openDownloadStream openDownloadStream(id: ObjectID, options?: { start: number, end: number }): GridFSBucketReadStream; // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#openDownloadStreamByName diff --git a/mongodb/mongodb-tests.ts b/mongodb/mongodb-tests.ts index cea5175e69..cba7f9a212 100644 --- a/mongodb/mongodb-tests.ts +++ b/mongodb/mongodb-tests.ts @@ -25,4 +25,44 @@ MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err: mongodb.Mong console.log(stats.count + " documents"); }); }); + + { + let cursor: mongodb.Cursor; + cursor = collection.find(); + cursor = cursor.addCursorFlag('',true); + cursor = cursor.addQueryModifier('',true); + cursor = cursor.batchSize(1); + cursor = cursor.comment(''); + cursor = cursor.filter(1); + cursor = cursor.hint({}); + cursor = cursor.limit(1); + cursor = cursor.map(function (result) {}); + cursor = cursor.max(1); + cursor = cursor.min(1); + cursor = cursor.maxAwaitTimeMS(1); + cursor = cursor.maxScan({}); + cursor = cursor.maxTimeMS(1); + cursor = cursor.project({}); + cursor = cursor.returnKey({}); + cursor = cursor.setCursorOption('',{}); + cursor = cursor.setReadPreference(''); + cursor = cursor.showRecordId({}); + cursor = cursor.skip(1); + cursor = cursor.snapshot({}); + cursor = cursor.sort({}); + cursor = cursor.stream(); + } + // Collection .findM() & .agggregate() generic tests + { + let bag : {cost: number, color: string}; + type bag = typeof bag; + let cursor: mongodb.Cursor = collection.find({color: 'black'}) + cursor.toArray(function (err,r) { r[0].cost} ); + cursor.forEach(function (bag ) { bag.color }, () => {}); + } + { + let payment: {total: number}; + type payment = typeof payment; + let cursor: mongodb.AggregationCursor = collection.aggregate([{}]) + } }) diff --git a/mongoose/index.d.ts b/mongoose/index.d.ts index 56ad48e617..7ef5615436 100644 --- a/mongoose/index.d.ts +++ b/mongoose/index.d.ts @@ -1,11 +1,13 @@ // Type definitions for Mongoose 4.7.0 // Project: http://mongoosejs.com/ -// Definitions by: simonxca , horiuchi +// Definitions by: simonxca , horiuchi , sindrenm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// + /* * Guidelines for maintaining these definitions: * - If you spot an error here or there, please submit a PR. @@ -994,10 +996,12 @@ declare module "mongoose" { * call execPopulate(). Passing the same path a second time will overwrite * the previous path options. See Model.populate() for explaination of options. * @param path The path to populate or an options object + * @param names The properties to fetch from the populated document * @param callback When passed, population is invoked */ populate(callback: (err: any, res: this) => void): this; populate(path: string, callback?: (err: any, res: this) => void): this; + populate(path: string, names: string, callback?: (err: any, res: this) => void): this; populate(options: ModelPopulateOptions | ModelPopulateOptions[], callback?: (err: any, res: this) => void): this; /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ @@ -2159,6 +2163,11 @@ declare module "mongoose" { * @param fields the field(s) to unwind */ unwind(...fields: string[]): this; + /** + * Appends new custom $unwind operator(s) to this aggregate pipeline + * new in mongodb 3.2 + */ + unwind(...opts: { path: string, includeArrayIndex?: string, preserveNullAndEmptyArrays?: boolean }[]): this; } /* diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index c6dfe20fdc..dc170dccd9 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1016,7 +1016,41 @@ aggregate.sort('field -test'); aggregate.then(cb).catch(cb); aggregate.unwind("tags").unwind('tags'); aggregate.unwind("a", "b", "c").unwind('tag1', 'tag2'); - +aggregate.unwind( + { + path: "tags", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }) + .unwind({ + path: "tags", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }); +aggregate.unwind( + { + path: "a", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "b", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "c", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }) + .unwind({ + path: "tag1", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }, { + path: "tag2", + includeArrayIndex: "idx", + preserveNullAndEmptyArrays: true + }); + /* * section schematype.js * http://mongoosejs.com/docs/api.html#schematype-js diff --git a/mqtt/index.d.ts b/mqtt/index.d.ts index 256c0a5394..f52aede457 100644 --- a/mqtt/index.d.ts +++ b/mqtt/index.d.ts @@ -235,6 +235,10 @@ declare namespace mqtt { */ handleMessage(packet: Packet, callback: Function): Client; + /** + * get last message id. This is for sent messages only. + */ + getLastMessageId(): number; } /** diff --git a/msgpack-lite/index.d.ts b/msgpack-lite/index.d.ts index 400d22b2e7..e451267dbc 100644 --- a/msgpack-lite/index.d.ts +++ b/msgpack-lite/index.d.ts @@ -1,71 +1,153 @@ -// Type definitions for msgpack-lite 0.1.20 +// Type definitions for msgpack-lite 0.1 // Project: https://github.com/kawanet/msgpack-lite -// Definitions by: Endel Dreyer +// Definitions by: Endel Dreyer , Edmund Fokschaner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module "msgpack-lite" { - import { Transform } from "stream"; +import * as stream from 'stream'; - namespace MsgpackLite { - interface BufferOptions { codec: any; } +/** + * encode from JS Object to MessagePack + */ +export function encode(input: any, options?: EncoderOptions): Buffer; - interface Encoder { - bufferish: any; - maxBufferSize: number; - minBufferSize: number; - offset: number; - start: number; - write: (chunk: any) => void; - fetch: () => void; - flush: () => void; - push: (chunk: any) => void; - pull: () => number; - read: () => number; - reserve: (length: number) => number; - send: (buffer: Buffer) => void; - encode: (chunk: any) => void; - end: (chunk: any) => void; - } +/** + * decode from MessagePack to JS Object + */ +export function decode(input: Buffer | Uint8Array | number[], options?: DecoderOptions): any; - interface Decoder { - bufferish: any; - offset: number; - fetch: () => void; - flush: () => void; - pull: () => number; - read: () => number; - write: (chunk: any) => void; - reserve: (length: number) => number; - decode: (chunk: any) => void; - push: (chunk: any) => void; - end: (chunk: any) => void; - } +/** + * create a stream that encodes from JS Object to MessagePack + */ +export function createEncodeStream(options?: EncoderOptions & stream.TransformOptions ): EncodeStream; - interface EncodeStream extends Transform { - encoder: Encoder; - } - interface DecodeStream extends Transform { - decoder: Decoder; - } +/** + * create a stream that decodes from MessagePack (Buffer) to JS Object + */ +export function createDecodeStream(options?: DecoderOptions & stream.TransformOptions): DecodeStream; - interface Codec { - new (options?: any): Codec; - options: any; - init (): void; - addExtPacker (etype: number, Class: any, packer: (value: any) => any): void; - getExtPacker (value: any): (value: any) => any; - addExtUnpacker (etype: number, unpacker: (value: any) => any): void; - getExtUnpacker (etype: number): (value: any) => any; - } +/** + * Codecs allow for Custom Extension Types + * Register a custom extension type number to serialize/deserialize your own class instances. + * https://github.com/kawanet/msgpack-lite#custom-extension-types-codecs + * If you wish to modify the default built-in codec, you can access it at msgpack.codec.preset + */ +export function createCodec(options?: CodecOptions): Codec; - export function encode(input: any, options?: BufferOptions): any; - export function decode(input: Buffer | Uint8Array | Array, options?: BufferOptions): any; - export function createEncodeStream (): EncodeStream; - export function createDecodeStream (): DecodeStream; - export function createCodec (options?: any): Codec; - export function codec (): { preset: Codec }; - } +/** + * The default built-in codec + */ +export var codec: { + /** + * The default built-in codec + */ + preset: Codec; +}; - export = MsgpackLite; +export interface Codec { + /** + * Register a custom extension to serialize your own class instances + * + * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) + * @param Class the constructor of the type you wish to serialize + * @param packer a function that converts an instance of T to bytes + */ + addExtPacker( + etype: number, + Class: new(...args: any[]) => T, + packer: (t: T) => Buffer | Uint8Array): void; + + /** + * Register a custom extension to deserialize your own class instances + * + * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) + * @param unpacker a function that converts bytes to an instance of T + */ + addExtUnpacker(etype: number, unpacker: (data: Buffer | Uint8Array) => T): void; } + +export interface Encoder { + bufferish: any; + maxBufferSize: number; + minBufferSize: number; + offset: number; + start: number; + write: (chunk: any) => void; + fetch: () => void; + flush: () => void; + push: (chunk: any) => void; + pull: () => number; + read: () => number; + reserve: (length: number) => number; + send: (buffer: Buffer) => void; + encode: (chunk: any) => void; + end: (chunk: any) => void; +} + +export interface Decoder { + bufferish: any; + offset: number; + fetch: () => void; + flush: () => void; + pull: () => number; + read: () => number; + write: (chunk: any) => void; + reserve: (length: number) => number; + decode: (chunk: any) => void; + push: (chunk: any) => void; + end: (chunk: any) => void; +} + +export interface EncodeStream extends stream.Transform { + encoder: Encoder; +} + +export interface DecodeStream extends stream.Transform { + decoder: Decoder; +} + +export interface CodecOptions { + /** + * It includes the preset extensions for JavaScript native objects. + * @see https://github.com/kawanet/msgpack-lite#extension-types + * @default false + */ + preset?: boolean; + /** + * It runs a validation of the value before writing it into buffer. + * This is the default behavior for some old browsers which do not support ArrayBuffer object. + * @default varies + */ + safe?: boolean; + /** + * It uses raw formats instead of bin and str. + * Set true for compatibility with msgpack's old spec. + * @see https://github.com/kawanet/msgpack-lite#compatibility-mode + * @default false + */ + raw?: boolean; + /** + * It decodes msgpack's int64/uint64 formats with int64-buffer object. + * int64-buffer is a cutom integer type with 64 bits of precision instead + * of the built-in IEEE-754 53 bits. See https://github.com/kawanet/int64-buffer + * @default false + */ + int64?: boolean; + /** + * It ties msgpack's bin format with ArrayBuffer object, instead of Buffer object. + * @default false + */ + binarraybuffer?: boolean; + /** + * It returns Uint8Array object when encoding, instead of Buffer object. + */ + uint8array?: boolean; +} + +export interface EncoderOptions { + codec?: Codec; +} + +export interface DecoderOptions { + codec?: Codec; +} \ No newline at end of file diff --git a/msgpack-lite/msgpack-lite-tests.ts b/msgpack-lite/msgpack-lite-tests.ts index f6d8725754..a03d86b679 100644 --- a/msgpack-lite/msgpack-lite-tests.ts +++ b/msgpack-lite/msgpack-lite-tests.ts @@ -1,5 +1,74 @@ +import * as msgpack from 'msgpack-lite'; -import * as msgpack from "msgpack-lite"; +// https://github.com/kawanet/msgpack-lite#encoding-and-decoding-messagepack +function encodingAndDecoding() { + // encode from JS Object to MessagePack (Buffer) + var buffer = msgpack.encode({foo: "bar"}); -var encoded = msgpack.encode(""); -msgpack.decode(encoded); + // decode from MessagePack (Buffer) to JS Object + var data = msgpack.decode(buffer); // => {"foo": "bar"} +} + +// https://github.com/kawanet/msgpack-lite#writing-to-messagepack-stream +function writingToStream() { + var fs = require("fs"); + + var writeStream = fs.createWriteStream("test.msp"); + var encodeStream = msgpack.createEncodeStream(); + encodeStream.pipe(writeStream); + + // send multiple objects to stream + encodeStream.write({foo: "bar"}); + encodeStream.write({baz: "qux"}); + + // call this once you're done writing to the stream. + encodeStream.end(); +} + +// https://github.com/kawanet/msgpack-lite#reading-from-messagepack-stream +function readingFromStream() { + var fs = require("fs"); + + var readStream = fs.createReadStream("test.msp"); + var decodeStream = msgpack.createDecodeStream(); + + // show multiple objects decoded from stream + readStream.pipe(decodeStream).on("data", console.warn); +} + +// https://github.com/kawanet/msgpack-lite#decoding-messagepack-bytes-array +function decodingBytesArray() { + // decode() accepts Buffer instance per default + msgpack.decode(new Buffer([0x81, 0xA3, 0x66, 0x6F, 0x6F, 0xA3, 0x62, 0x61, 0x72])); + + // decode() also accepts Array instance + msgpack.decode([0x81, 0xA3, 0x66, 0x6F, 0x6F, 0xA3, 0x62, 0x61, 0x72]); + + // decode() accepts raw Uint8Array instance as well + msgpack.decode(new Uint8Array([0x81, 0xA3, 0x66, 0x6F, 0x6F, 0xA3, 0x62, 0x61, 0x72])); +} + +// https://github.com/kawanet/msgpack-lite#custom-extension-types-codecs +function customExtensionTypes() { + var codec = msgpack.createCodec(); + codec.addExtPacker(0x3F, MyVector, myVectorPacker); + codec.addExtUnpacker(0x3F, myVectorUnpacker); + + var data = new MyVector(1, 2); + var encoded = msgpack.encode(data, {codec}); + var decoded = msgpack.decode(encoded, {codec}); + + class MyVector { + constructor(public x: number, public y: number) {} + } + + function myVectorPacker(vector: MyVector) { + var array = [vector.x, vector.y]; + return msgpack.encode(array); // return Buffer serialized + } + + function myVectorUnpacker(buffer: Buffer | Uint8Array): MyVector { + var array = msgpack.decode(buffer); + return new MyVector(array[0], array[1]); // return Object deserialized + } +} diff --git a/msgpack-lite/tsconfig.json b/msgpack-lite/tsconfig.json index 9a06c485e9..2547929f61 100644 --- a/msgpack-lite/tsconfig.json +++ b/msgpack-lite/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/msgpack-lite/tslint.json b/msgpack-lite/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/msgpack-lite/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/multer/index.d.ts b/multer/index.d.ts index 2437f498db..53fdcd7add 100644 --- a/multer/index.d.ts +++ b/multer/index.d.ts @@ -48,22 +48,22 @@ declare namespace multer { /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ destination?: string | ((req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void); /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ - filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, filename: string) => void) => void; + filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error | null, filename: string) => void) => void; } interface Instance { - /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - single(): express.RequestHandler; - /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ - single(fieldame: string): express.RequestHandler; - /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - array(): express.RequestHandler; - /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ - array(fieldame: string, maxCount?: number): express.RequestHandler; - /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ - fields(fields: Field[]): express.RequestHandler; - /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - any(): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + single(): express.RequestHandler; + /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ + single(fieldame: string): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + array(): express.RequestHandler; + /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ + array(fieldame: string, maxCount?: number): express.RequestHandler; + /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ + fields(fields: Field[]): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + any(): express.RequestHandler; } } diff --git a/nanomsg/nanomsg-tests.ts b/nanomsg/nanomsg-tests.ts index a731312890..22b9836db0 100644 --- a/nanomsg/nanomsg-tests.ts +++ b/nanomsg/nanomsg-tests.ts @@ -2,16 +2,16 @@ import { Socket, socket } from "nanomsg"; const pub: Socket = socket("pub"); const sub: Socket = socket("sub"); -const addr: string = "tcp://127.0.0.1:7789" +const addr: string = "tcp://127.0.0.1:7789"; pub.bind(addr); sub.connect(addr); -sub.on('data', function (buf) { +sub.on('data', buf => { console.log(String(buf)); pub.close(); sub.close(); }); -setTimeout(function () { +setTimeout(() => { pub.send("Hello from nanomsg!"); }, 100); diff --git a/nanomsg/tslint.json b/nanomsg/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/nanomsg/tslint.json +++ b/nanomsg/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/navigation-react/index.d.ts b/navigation-react/index.d.ts index 131ce29735..32ee6570f3 100644 --- a/navigation-react/index.d.ts +++ b/navigation-react/index.d.ts @@ -2,6 +2,8 @@ // Project: http://grahammendick.github.io/navigation/ // Definitions by: Graham Mendick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + import { StateNavigator } from 'navigation'; import { Component, HTMLProps } from 'react'; diff --git a/navigation-react/navigation-react-tests.tsx b/navigation-react/navigation-react-tests.tsx index 83a0c5f40a..7f2454e8b6 100644 --- a/navigation-react/navigation-react-tests.tsx +++ b/navigation-react/navigation-react-tests.tsx @@ -8,11 +8,9 @@ var stateNavigator = new StateNavigator([ ]); // Refresh Link -var RefreshLinkTest = function() { - return People; -} +var RefreshLinkTest = () => People; -RefreshLinkTest = function() { +RefreshLinkTest = () => { return ( true} + navigating= {(e: MouseEvent, domId: string, link: string) => true} stateNavigator={stateNavigator} target="_blank" aria-label="Go to the second page of people"> People ); -} +}; // Navigation Link -var NavigationLinkTest = function() { - return Person; -} +var NavigationLinkTest = () => Person; -NavigationLinkTest = function() { +NavigationLinkTest = () => { return ( true} + navigating= {(e: MouseEvent, domId: string, link: string) => true} stateNavigator={stateNavigator} target="_blank" aria-label="View the person's details"> Person ); -} +}; // Navigation Back Link -var NavigationBackLinkTest = function() { - return People; -} +var NavigationBackLinkTest = () => People; -NavigationBackLinkTest = function() { +NavigationBackLinkTest = () => { return ( true} + navigating= {(e: MouseEvent, domId: string, link: string) => true} stateNavigator={stateNavigator} target="_blank" aria-label="Go back to the list of people"> People ); -} - +}; diff --git a/navigation-react/tslint.json b/navigation-react/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/navigation-react/tslint.json +++ b/navigation-react/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/nblas/nblas-tests.ts b/nblas/nblas-tests.ts index 754c47560c..478a9cff78 100644 --- a/nblas/nblas-tests.ts +++ b/nblas/nblas-tests.ts @@ -4,7 +4,7 @@ const a = new Float32Array(0); const n = 1; let res: number; -function test () { +function test() { // BLAS Level 1 Routines and Functions res = nblas.asum(a); nblas.axpy(a, a, n); @@ -18,7 +18,7 @@ function test () { nblas.scal(a, n); nblas.swap(a, a); res = nblas.iamax(a); - //nblas.iamin(a); + // nblas.iamin(a); // BLAS Level 2 Routines nblas.gbmv(a, a, a, n, n, n, n, nblas.Trans); diff --git a/needle/index.d.ts b/needle/index.d.ts index 7607fdfc78..8cc61f2a2f 100644 --- a/needle/index.d.ts +++ b/needle/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for needle 0.7.8 +// Type definitions for needle 1.4 // Project: https://github.com/tomas/needle -// Definitions by: San Chen +// Definitions by: San Chen , Niklas Mollenhauer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,85 +8,111 @@ declare module "needle" { import * as http from 'http'; import * as Buffer from 'buffer'; - module Needle { + import * as https from 'https'; + namespace Needle { interface NeedleResponse extends http.IncomingMessage { body: any; raw: Buffer; bytes: number; } - interface ReadableStream extends NodeJS.ReadableStream { + type ReadableStream = NodeJS.ReadableStream; + + type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void; + + interface Cookies { + [name: string]: any; } - interface Callback { - (error: Error, response: NeedleResponse, body: any): void; - } + type NeedleOptions = RequestOptions & ResponseOptions & RedirectOptions & https.RequestOptions; interface RequestOptions { + open_timeout?: number; + read_timeout?: number; + /** + * Alias for open_timeout + */ timeout?: number; - follow?: number; + follow_max?: number; + /** + * Alias for follow_max + */ + follow?: number; + multipart?: boolean; + agent?: http.Agent | boolean; proxy?: string; - agent?: string; - headers?: Object; - auth?: string; // auto | digest | basic (default) + headers?: {}; + auth?: "auto" | "digest" | "basic"; json?: boolean; // These properties are overwritten by those in the 'headers' field + cookies?: Cookies; compressed?: boolean; - cookies?: { [name: string]: any; }; // Overwritten if present in the URI username?: string; password?: string; + accept?: string; + connection?: string; + user_agent?: string; } interface ResponseOptions { + decode_response?: boolean; + /** + * Alias for decode_response + */ decode?: boolean; + parse_response?: boolean; + /** + * Alias for parse_response + */ parse?: boolean; - output?: any; + + parse_cookies?: boolean; + output?: string; } - interface TLSOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: any; - rejectUnauthorized?: boolean; - secureProtocol?: any; + interface RedirectOptions { + follow_set_cookie?: boolean; + follow_set_referer?: boolean; + follow_keep_method?: boolean; + follow_if_same_host?: boolean; + follow_if_same_protocol?: boolean; } + interface KeyValue { + [key: string]: any; + } + + type BodyData = Buffer | KeyValue | NodeJS.ReadableStream | string | null; + interface NeedleStatic { - defaults(options?: any): void; + defaults(options: NeedleOptions): void; - head(url: string): ReadableStream; - head(url: string, callback?: Callback): ReadableStream; - head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + head(url: string, callback?: NeedleCallback): ReadableStream; + head(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - get(url: string): ReadableStream; - get(url: string, callback?: Callback): ReadableStream; - get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + get(url: string, callback?: NeedleCallback): ReadableStream; + get(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - post(url: string, data: any): ReadableStream; - post(url: string, data: any, callback?: Callback): ReadableStream; - post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + post(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + post(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - put(url: string, data: any): ReadableStream; - put(url: string, data: any, callback?: Callback): ReadableStream; - put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + put(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + put(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - delete(url: string, data: any): ReadableStream; - delete(url: string, data: any, callback?: Callback): ReadableStream; - delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + patch(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + patch(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - request(method: string, url: string, data: any): ReadableStream; - request(method: string, url: string, data: any, callback?: Callback): ReadableStream; - request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + delete(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + delete(url: string, data: BodyData, options?: NeedleOptions, callback ?: NeedleCallback): ReadableStream; + + request(method: string, url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + request(method: string, url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; } } - - var needle: Needle.NeedleStatic; + const needle: Needle.NeedleStatic; export = needle; -} \ No newline at end of file +} diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 3df14952c3..1c5090027a 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -1,4 +1,5 @@ -import needle = require("needle"); +import * as needle from "needle"; +import * as fs from "fs"; function Usage() { // using callback @@ -14,7 +15,7 @@ function Usage() { function ResponsePipeline() { needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { - console.log(resp.body); // this little guy won't be a Gzipped binary blob + console.log(resp.body); // this little guy won't be a Gzipped binary blob // but a nice object containing all the latest entries }); @@ -24,21 +25,26 @@ function ResponsePipeline() { rejectUnauthorized: true }; - // in this case, we'll ask Needle to follow redirects (disabled by default), + // in this case, we'll ask Needle to follow redirects (disabled by default), // but also to verify their SSL certificates when connecting. var stream = needle.get('https://backend.server.com/everything.html', options); stream.on('readable', function () { var data: any; - while (data = this.read()) { + while (data = stream.read()) { console.log(data.toString()); } }); + + stream.on('end', function(err: any) { + // if our request had an error, our 'end' event will tell us. + if (!err) console.log('Great success!'); + }) } function API_head() { var options = { - timeout: 5000 // if we don't get a response in 5 seconds, boom. + open_timeout: 5000 // if we don't get a response in 5 seconds, boom. }; needle.head('https://my.backend.server.com', function (err, resp) { @@ -93,14 +99,131 @@ function API_delete() { } function API_request() { - var data = { + var params = { q: 'a very smart query', page: 2, - format: 'json' }; - needle.request('get', 'forum.com/search', data, function (err, resp) { + needle.request('get', 'forum.com/search', params, function (err, resp) { if (!err && resp.statusCode == 200) console.log(resp.body); // here you go, mister. }); + + needle.request('get', 'forum.com/search', params, { json: true }, function(err, resp) { + if (resp.statusCode == 200) console.log('It worked!'); + }); +} + +function HttpGetWithBasicAuth() { + needle.get('https://api.server.com', { username: 'you', password: 'secret' }, function(err, resp) { + // used HTTP auth + }); + needle.get('https://username:password@api.server.com', function(err, resp) { + // used HTTP auth from URL + }); +} + +function DigestAuth() { + needle.get('other.server.com', { username: 'you', password: 'secret', auth: 'digest' }, function(err, resp, body) { + // needle prepends 'http://' to your URL, if missing + }); +} + +function CustomAcceptHeaderDeflate() { + var options = { + compressed: true, + follow: 10, + accept: 'application/vnd.github.full+json' + } + + needle.get('api.github.com/users/tomas', options, function(err, resp, body) { + // body will contain a JSON.parse(d) object + // if parsing fails, you'll simply get the original body + }); + +} + +function Various() { + + needle.get('https://news.ycombinator.com/rss', function(err, resp, body) { + // if xml2js is installed, you'll get a nice object containing the nodes in the RSS + }); + needle.get('http://upload.server.com/tux.png', { output: '/tmp/tux.png' }, function(err, resp, body) { + // you can dump any response to a file, not only binaries. + }); + needle.get('http://search.npmjs.org', { proxy: 'http://localhost:1234' }, function(err, resp, body) { + // request passed through proxy + }); + const stream1 = needle.get('http://www.as35662.net/100.log'); + stream1.on('readable', function() { + let chunk: any; + while (chunk = stream1.read()) { + console.log('got data: ', chunk); + } + }); + const stream2 = needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }); + stream2.on('readable', function() { + let node: any; + + // our stream2 will only emit a single JSON root node. + while (node = stream2.read()) { + console.log('got data: ', node); + } + }); + + /* + // Sample omitted, no JSONStream + needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }) + .pipe(new JSONStream.parse('posts.*.title')) + .on('data', function (obj) { + console.log('got post title: %s', obj); + }); + */ +} + +function FileUpload() { + var data = { + foo: 'bar', + image: { file: '/home/tomas/linux.png', content_type: 'image/png' } + }; + + needle.post('http://my.other.app.com', data, { multipart: true }, function(err, resp, body) { + // needle will read the file and include it in the form-data as binary + }); + needle.put('https://api.app.com/v2', fs.createReadStream('myfile.txt'), function(err, resp, body) { + // stream content is uploaded verbatim + }); +} + +function Multipart() { + var buffer = fs.readFileSync('/path/to/package.zip'); + + var data = { + zip_file: { + buffer: buffer, + filename: 'mypackage.zip', + content_type: 'application/octet-stream' + } + } + + needle.post('http://somewhere.com/over/the/rainbow', data, { multipart: true }, function(err, resp, body) { + // if you see, when using buffers we need to pass the filename for the multipart body. + // you can also pass a filename when using the file path method, in case you want to override + // the default filename to be received on the other end. + }); +} + +function MultipartContentType() { + var data = { + token: 'verysecret', + payload: { + value: JSON.stringify({ title: 'test', version: 1 }), + content_type: 'application/json' + } + } + + needle.post('http://test.com/', data, { timeout: 5000, multipart: true }, function(err, resp, body) { + // in this case, if the request takes more than 5 seconds + // the callback will return a [Socket closed] error + }); } diff --git a/needle/tsconfig.json b/needle/tsconfig.json index 5af602dd4f..59f9b2b49e 100644 --- a/needle/tsconfig.json +++ b/needle/tsconfig.json @@ -5,8 +5,8 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "needle-tests.ts" ] -} \ No newline at end of file +} diff --git a/needle/v0/index.d.ts b/needle/v0/index.d.ts new file mode 100644 index 0000000000..28b5b8119f --- /dev/null +++ b/needle/v0/index.d.ts @@ -0,0 +1,83 @@ +// Type definitions for needle 0.7 +// Project: https://github.com/tomas/needle +// Definitions by: San Chen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "needle" { + import * as http from 'http'; + import * as Buffer from 'buffer'; + namespace Needle { + interface NeedleResponse extends http.IncomingMessage { + body: any; + raw: Buffer; + bytes: number; + } + + type ReadableStream = NodeJS.ReadableStream; + + type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void; + + interface RequestOptions { + timeout?: number; + follow?: number; + follow_max?: number; + multipart?: boolean; + proxy?: string; + agent?: string; + headers?: {}; + auth?: string; // auto | digest | basic (default) + json?: boolean; + + // These properties are overwritten by those in the 'headers' field + compressed?: boolean; + cookies?: { [name: string]: any; }; + // Overwritten if present in the URI + username?: string; + password?: string; + } + + interface ResponseOptions { + decode?: boolean; + parse?: boolean; + output?: any; + } + + interface TLSOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: any; + rejectUnauthorized?: boolean; + secureProtocol?: any; + } + + interface NeedleStatic { + defaults(options?: any): void; + + head(url: string, callback?: NeedleCallback): ReadableStream; + head(url: string, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + get(url: string, callback?: NeedleCallback): ReadableStream; + get(url: string, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + post(url: string, data: any, callback?: NeedleCallback): ReadableStream; + post(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + put(url: string, data: any, callback?: NeedleCallback): ReadableStream; + put(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + delete(url: string, data: any, callback?: NeedleCallback): ReadableStream; + delete(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + + request(method: string, url: string, data: any, callback?: NeedleCallback): ReadableStream; + request(method: string, url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; + } + } + + var needle: Needle.NeedleStatic; + export = needle; +} diff --git a/needle/v0/needle-tests.ts b/needle/v0/needle-tests.ts new file mode 100644 index 0000000000..5a849ec204 --- /dev/null +++ b/needle/v0/needle-tests.ts @@ -0,0 +1,106 @@ +import needle = require("needle"); + +function Usage() { + // using callback + needle.get('http://ifconfig.me/all.json', function (error, response) { + if (!error) + console.log(response.body.ip_addr); // JSON decoding magic. :) + }); + + // using streams + var out: any; // = fs.createWriteStream('logo.png'); + needle.get('https://google.com/images/logo.png').pipe(out); +} + +function ResponsePipeline() { + needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { + console.log(resp.body); // this little guy won't be a Gzipped binary blob + // but a nice object containing all the latest entries + }); + + var options = { + compressed: true, + follow: 5, + rejectUnauthorized: true + }; + + // in this case, we'll ask Needle to follow redirects (disabled by default), + // but also to verify their SSL certificates when connecting. + var stream = needle.get('https://backend.server.com/everything.html', options); + + stream.on('readable', function () { + var data: any; + while (data = stream.read()) { + console.log(data.toString()); + } + }); +} + +function API_head() { + var options = { + timeout: 5000 // if we don't get a response in 5 seconds, boom. + }; + + needle.head('https://my.backend.server.com', function (err, resp) { + if (err) { + console.log('Shoot! Something is wrong: ' + err.message); + } + else { + console.log('Yup, still alive.'); + } + }); +} + +function API_get() { + needle.get('google.com/search?q=syd+barrett', function (err, resp) { + // if no http:// is found, Needle will automagically prepend it. + }); +} + +function API_post() { + var options = { + headers: { 'X-Custom-Header': 'Bumbaway atuna' } + }; + + needle.post('https://my.app.com/endpoint', 'foo=bar', options, function (err, resp) { + // you can pass params as a string or as an object. + }); +} + +function API_put() { + var nested = { + params: { + are: { + also: 'supported' + } + } + }; + + needle.put('https://api.app.com/v2', nested, function (err, resp) { + console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella. + }); +} + +function API_delete() { + var options = { + username: 'fidelio', + password: 'x' + }; + + needle.delete('https://api.app.com/messages/123', null, options, function (err, resp) { + // in this case, data may be null, but you need to explicity pass it. + }); +} + +function API_request() { + var data = { + q: 'a very smart query', + page: 2, + format: 'json' + }; + + needle.request('get', 'forum.com/search', data, function (err, resp) { + if (!err && resp.statusCode == 200) + console.log(resp.body); // here you go, mister. + }); +} diff --git a/needle/v0/tsconfig.json b/needle/v0/tsconfig.json new file mode 100644 index 0000000000..44c8b59654 --- /dev/null +++ b/needle/v0/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../../" + ], + "paths": { + "needle": [ + "needle/v0" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "needle-tests.ts" + ] +} diff --git a/ng-file-upload/index.d.ts b/ng-file-upload/index.d.ts index 2455c8daf5..d9aadbd2d5 100644 --- a/ng-file-upload/index.d.ts +++ b/ng-file-upload/index.d.ts @@ -41,7 +41,11 @@ declare module 'angular' { * Validate error name: minDuration * @type {(number|string)} */ - ngfMinDuration: number | string; + ngfMinDuration?: number | string; + /** + * Validate error name: minSize + * @type {(number|string)} + */ ngfMinSize?: number | string; /** * Validate error name: minRatio diff --git a/ng-file-upload/ng-file-upload-tests.ts b/ng-file-upload/ng-file-upload-tests.ts index 7252231661..08fbafdb6b 100644 --- a/ng-file-upload/ng-file-upload-tests.ts +++ b/ng-file-upload/ng-file-upload-tests.ts @@ -26,7 +26,7 @@ class UploadController { ngfValidateForce: true }); } - + onFileSelect(files: Array) { this.Upload @@ -44,11 +44,11 @@ class UploadController { }).progress((evt: angular.angularFileUpload.IFileProgressEvent) => { let percent = parseInt((100.0 * evt.loaded / evt.total).toString(), 10); console.log("upload progress: " + percent + "% for " + evt.config.data.media[0]); - }).error((data: any, status: number, response: any, headers: any) => { - console.error(data, status, response, headers); - }).success((data: any, status: number, headers: any, config: angular.angularFileUpload.IFileUploadConfigFile) => { + }).catch((response: ng.IHttpPromiseCallbackArg) => { + console.error(response.data, response.status, response.statusText, response.headers); + }).then((response: ng.IHttpPromiseCallbackArg) => { // file is uploaded successfully - console.log("Success!", data, status, headers, config); + console.log("Success!", response.data, response.status, response.headers, response.config); }); this.Upload @@ -72,16 +72,16 @@ class UploadController { this.Upload.isResizeSupported(); this.Upload.isResumeSupported(); this.Upload.isUploadInProgress(); - + let json = this.Upload.json({ test: true }), jsonBlob = this.Upload.jsonBlob({ test: true }), fileWithNewName = this.Upload.rename(files[0], "newName.jpg"); this.Upload - .resize(files[0], { + .resize(files[0], { height: 1024, width: 1024, - quality: 0.7, + quality: 0.7, ratio: 0.9, centerCrop: true, restoreExif: true, diff --git a/ngreact/index.d.ts b/ngreact/index.d.ts index f9df0f694f..b20a35cad2 100644 --- a/ngreact/index.d.ts +++ b/ngreact/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ngReact/ngReact // Definitions by: Vicky Lai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// diff --git a/ngstorage/index.d.ts b/ngstorage/index.d.ts index b8fcf023c8..15fb3c0481 100644 --- a/ngstorage/index.d.ts +++ b/ngstorage/index.d.ts @@ -1,29 +1,25 @@ -// Type definitions for ngstorage 0.3.10 +// Type definitions for ngstorage 0.3.11 // Project: https://github.com/gsklee/ngStorage // Definitions by: Jakub Pistek // Definitions: https://github.com/kubiq/DefinitelyTyped -import * as angular from 'angular'; +declare module 'ngstorage' { -declare module 'angular' { - export namespace storage { + interface IStorageService { + $default(items: {}): IStorageService; + $reset(items?: {}): IStorageService; + $apply(): void; + $sync(): void; + get(key: string): T; + } - export interface IStorageService { - $default(items: {}): IStorageService; - $reset(items?: {}): IStorageService; - $apply(): void; - $sync(): void; - get(key: string): T; - } + interface IStorageProvider extends angular.IServiceProvider { - export interface IStorageProvider extends angular.IServiceProvider { + get(key: string): T; + set(key: string, value: T): T; - get(key: string): T; - set(key: string, value: T): T; - - setKeyPrefix(prefix: string): void; - setSerializer(serializer: (value: any) => string): void; - setDeserializer(deserializer: (value: string) => any): void; - } + setKeyPrefix(prefix: string): void; + setSerializer(serializer: (value: any) => string): void; + setDeserializer(deserializer: (value: string) => any): void; } } diff --git a/ngstorage/ngstorage-tests.ts b/ngstorage/ngstorage-tests.ts index 924d017a66..abddf19bb7 100644 --- a/ngstorage/ngstorage-tests.ts +++ b/ngstorage/ngstorage-tests.ts @@ -1,9 +1,9 @@ -/// +/// +import {IStorageService, IStorageProvider} from "ngstorage"; var app: any; - -app.controller('LocalCtrl', function ($localStorage: angular.storage.IStorageService) { +app.controller('LocalCtrl', function ($localStorage: IStorageService) { $localStorage.$default({ counter: 1 @@ -12,15 +12,15 @@ app.controller('LocalCtrl', function ($localStorage: angular.storage.IStorageSer $localStorage.$reset({ counter: 1 }); - + $localStorage.$reset(); $localStorage.$apply(); - + $localStorage.$sync(); }); -app.controller('SessionCtrl', function ($sessionStorage: angular.storage.IStorageService) { +app.controller('SessionCtrl', function ($sessionStorage: IStorageService) { $sessionStorage.$default({ counter: 1 @@ -29,50 +29,50 @@ app.controller('SessionCtrl', function ($sessionStorage: angular.storage.IStorag $sessionStorage.$reset({ counter: 1 }); - + $sessionStorage.$reset(); $sessionStorage.$apply(); - + $sessionStorage.$sync(); }); -app.config(['$localStorageProvider', function ($localStorageProvider: angular.storage.IStorageProvider) { +app.config(['$localStorageProvider', function ($localStorageProvider: IStorageProvider) { - $localStorageProvider.setKeyPrefix('NewPrefix'); + $localStorageProvider.setKeyPrefix('NewPrefix'); - $localStorageProvider.get('MyKey'); + $localStorageProvider.get('MyKey'); - $localStorageProvider.set('MyKey', { counter: 'value' }); + $localStorageProvider.set('MyKey', {counter: 'value'}); - var mySerializer = function (value:any):string { - return value.toString(); - }; + var mySerializer = function (value: any): string { + return value.toString(); + }; - var myDeserializer = function (value:string):any { - return value; - }; + var myDeserializer = function (value: string): any { + return value; + }; - $localStorageProvider.setSerializer(mySerializer); - $localStorageProvider.setDeserializer(myDeserializer); - } -]).config(['$sessionStorageProvider', function ($sessionStorageProvider: angular.storage.IStorageProvider) { + $localStorageProvider.setSerializer(mySerializer); + $localStorageProvider.setDeserializer(myDeserializer); +} +]).config(['$sessionStorageProvider', function ($sessionStorageProvider: IStorageProvider) { - $sessionStorageProvider.setKeyPrefix('NewPrefix'); + $sessionStorageProvider.setKeyPrefix('NewPrefix'); - $sessionStorageProvider.get('MyKey'); + $sessionStorageProvider.get('MyKey'); - $sessionStorageProvider.set('MyKey', { counter: 'value' }); + $sessionStorageProvider.set('MyKey', {counter: 'value'}); - var mySerializer = function (value:any):string { - return value.toString(); - }; + var mySerializer = function (value: any): string { + return value.toString(); + }; - var myDeserializer = function (value:string):any { - return value; - }; + var myDeserializer = function (value: string): any { + return value; + }; - $sessionStorageProvider.setSerializer(mySerializer); - $sessionStorageProvider.setDeserializer(myDeserializer); - } + $sessionStorageProvider.setSerializer(mySerializer); + $sessionStorageProvider.setDeserializer(myDeserializer); +} ]); diff --git a/ngstorage/tsconfig.json b/ngstorage/tsconfig.json index 691875db20..a3cdb4a204 100644 --- a/ngstorage/tsconfig.json +++ b/ngstorage/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "ngstorage-tests.ts" ] -} \ No newline at end of file +} diff --git a/nock/index.d.ts b/nock/index.d.ts index 447c591803..180100a33f 100644 --- a/nock/index.d.ts +++ b/nock/index.d.ts @@ -34,7 +34,8 @@ declare namespace nock { type HttpHeaders = { [key: string]: string | { (req: any, res: any, body: string): any; }; }; type InterceptFunction = ( uri: string | RegExp | { (uri: string): boolean; }, - requestBody?: string | RegExp | { (body: any): boolean; } | any + requestBody?: string | RegExp | { (body: any): boolean; } | any, + interceptorOptions?: Options ) => Interceptor; export type ReplyCallback = (err: any, result: ReplyCallbackResult) => void; type ReplyCallbackResult = string | [number, string | any] | [number, string | any, HttpHeaders] | any; @@ -48,6 +49,7 @@ declare namespace nock { patch: InterceptFunction; merge: InterceptFunction; delete: InterceptFunction; + options: InterceptFunction; intercept: ( uri: string | RegExp | { (uri: string): boolean; }, diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts index 0d1b11159f..8c2d48e736 100644 --- a/nock/nock-tests.ts +++ b/nock/nock-tests.ts @@ -21,29 +21,39 @@ inst = scope.head(str); inst = scope.get(str); inst = scope.get(str, data); +inst = scope.get(str, data, options); + +inst = scope.options(str); +inst = scope.options(str, data); +inst = scope.options(str, data, options); inst = scope.patch(str); inst = scope.patch(str, str); inst = scope.patch(str, obj); +inst = scope.patch(str, obj, options); inst = scope.patch(str, regex); inst = scope.post(str); inst = scope.post(str, data); +inst = scope.post(str, data, options); inst = scope.post(str, obj); inst = scope.post(str, regex); inst = scope.put(str); inst = scope.put(str, data); +inst = scope.put(str, data, options); inst = scope.put(str, obj); inst = scope.put(str, regex); inst = scope.delete(str); inst = scope.delete(str, data); +inst = scope.delete(str, data, options); inst = scope.delete(str, obj); inst = scope.delete(str, regex); inst = scope.merge(str); inst = scope.merge(str, data); +inst = scope.merge(str, data, options); inst = scope.merge(str, obj); inst = scope.merge(str, regex); diff --git a/node-emoji/node-emoji-tests.ts b/node-emoji/node-emoji-tests.ts index ebd71391fd..3bc883c6a4 100644 --- a/node-emoji/node-emoji-tests.ts +++ b/node-emoji/node-emoji-tests.ts @@ -1,12 +1,12 @@ import emoji = require('node-emoji'); -let coffee: string = emoji.get('coffee'); -let result: string = emoji.random(); +const coffee: string = emoji.get('coffee'); +const result: string = emoji.random(); -let cofee_name: string = emoji.which('☕️'); +const cofee_name: string = emoji.which('☕️'); -let emoji_string: string = emoji.emojify('I :heart: :coffee:! - :hushed::star::heart_eyes: ::: test : : :+1:+'); +const emoji_string: string = emoji.emojify('I :heart: :coffee:! - :hushed::star::heart_eyes: ::: test : : :+1:+'); -let emoji_string2: string = emoji.emojify('I :unknown_emoji: :star: :another_one:', (name: string) => name); +const emoji_string2: string = emoji.emojify('I :unknown_emoji: :star: :another_one:', (name: string) => name); -let emoji_direct: string = emoji.emoji.coffee; +const emoji_direct: string = emoji.emoji.coffee; diff --git a/node-hid/node-hid-tests.ts b/node-hid/node-hid-tests.ts index 15bc71b7d1..ef1f0c7e03 100644 --- a/node-hid/node-hid-tests.ts +++ b/node-hid/node-hid-tests.ts @@ -1,13 +1,13 @@ import HID = require('node-hid'); -var devices = HID.devices() +var devices = HID.devices(); var device = new HID.HID("path"); var device = new HID.HID(12, 22); -device.on("data", function (data) { }); -device.on("error", function (err) { }); +device.on("data", data => {}); +device.on("error", err => {}); device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]); \ No newline at end of file diff --git a/node-waves/index.d.ts b/node-waves/index.d.ts new file mode 100644 index 0000000000..ce5c63da2e --- /dev/null +++ b/node-waves/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for node-waves 0.7 +// Project: http://fian.my.id/Waves +// Definitions by: Stephen Lautier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type ElementTarget = string | Element | Element[]; + +export interface WavesConfig { + /** + * Determines how long the waves effect duration (in milliseconds). + * + */ + duration?: number; + + /** + * Delay amount to show waves effect on touch and hide the effect if user scrolls. + * Set to 0 to disable delay (in milliseconds). + * + */ + delay?: number; +} + +export interface RippleOptions { + + /** + * Specify how long to wait between starting and stopping the ripple. + * + */ + wait?: number | null; + + /** + * Specify the position inside the element. + * + */ + position?: { + x: number; + y: number; + } | null; +} + +/** + * Initializes waves with an optional config. + */ +export function init(config?: WavesConfig): void; + +/** + * Attach ripple effect by adding `.waves-effect` to HTML element. + * Make sure you call `init` to activate the ripple. + * + * @param {ElementTarget} elements elements to target. + * @param {(string | string[])} [classes] classes to add. + */ +export function attach(elements: ElementTarget, classes?: string | string[]): void; + +/** + * Creates a ripple effect in HTML element programmatically. + * @param {ElementTarget} elements elements to target (must have `.waves-effect` already applied, ideally via `attach`). + * @param {RippleOptions} [options] specify how long to wait between starting and stopping the ripple, and it's position inside the element. + */ +export function ripple(elements: ElementTarget, options?: RippleOptions): void; + +/** + * Removes all ripples from inside an element immediately. + * + * @param {ElementTarget} elements elements to remove ripples from. + */ +export function calm(elements: ElementTarget): void; diff --git a/node-waves/node-waves-tests.ts b/node-waves/node-waves-tests.ts new file mode 100644 index 0000000000..adfb59703a --- /dev/null +++ b/node-waves/node-waves-tests.ts @@ -0,0 +1,10 @@ + +import { init, ripple, attach, calm } from "node-waves"; + +init({ delay: 300 }); + +attach("button", "waves-light"); + +ripple(".box", { wait: null }); + +calm(".box"); diff --git a/node-waves/tsconfig.json b/node-waves/tsconfig.json new file mode 100644 index 0000000000..793f2d8de3 --- /dev/null +++ b/node-waves/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", + "node-waves-tests.ts" + ] +} \ No newline at end of file diff --git a/node-waves/tslint.json b/node-waves/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/node-waves/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/node-wit/index.d.ts b/node-wit/index.d.ts index 33f0bd8cb9..decfebe3aa 100644 --- a/node-wit/index.d.ts +++ b/node-wit/index.d.ts @@ -51,14 +51,15 @@ export interface WitOption { } export interface MessageResponseEntity { - confidence: number; - value: string; + confidence?: number; + value?: string; + type?: string; } export interface MessageResponse { msg_id: string; _text: string; - entities: MessageResponseEntity[]; + entities: any; } export declare class Wit { diff --git a/node-wit/node-wit-tests.ts b/node-wit/node-wit-tests.ts index d71c1d0cad..362595c4a9 100644 --- a/node-wit/node-wit-tests.ts +++ b/node-wit/node-wit-tests.ts @@ -4,7 +4,7 @@ var wit = new Wit({ accessToken: "", actions: { send(request: WitRequest, response: WitResponse) { - return new Promise(function(resolve, reject) { + return new Promise((resolve, reject) => { console.log(response.text); console.log(request.entities); return resolve(); @@ -23,9 +23,7 @@ var wit = new Wit({ wit.message("what is the weather in London?", {}).then((res) => { console.log(res._text); - for (let entity of res.entities) { - console.log(entity.value + ": " + entity.confidence * 100 + "%"); - } + console.log(res.entities); }).catch((err) => { console.log(err); diff --git a/node-xmpp-client/index.d.ts b/node-xmpp-client/index.d.ts new file mode 100644 index 0000000000..874df37de7 --- /dev/null +++ b/node-xmpp-client/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for node-xmpp-client 3.1 +// Project: https://github.com/node-xmpp/node-xmpp/tree/master/packages/node-xmpp-client/ +// Definitions by: PJakcson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export declare class Client { + static Stanza: Stanza; + + constructor(options: XmppOptions); + + connect(): void; + + disconnect(): void; + + on(event: string, c: (e: any, d: any) => any): void; + + send(stanza: any): void; +} + +interface Stanza extends Element { + // This has to be used for the static class initializer new Client.Stanza(..). If there is a better way feel free to + // contribute. + // tslint:disable-next-line + new(name: string, attr: any): Stanza; + from: string; + to: string; + id: string; + type: string; +} + +interface Element { + is(name: string, xmlns: string): boolean; + getName(): string; + getNS(): string; + findNS(prefix: string): string; + getXmlns(): string; + setAttrs(attrs: any): void; + getAttrs(): any; + + up(): Element; + c(name: string, attrs?: any): Element; + cnode(child: Element): Element; + t(text: string): Element; + remove(el: Element, xmnls: string): Element; + attr(attr: any, val: any): any; + + toString(): string; + toJSON(): any; +} + +interface XmppOptions { + jid: string; + password: string; + host?: string; + port?: number; + reconnect?: boolean; + autostart?: boolean; // if we start connecting to a given port + register?: boolean; // register account before authentication + legacySSL?: boolean; // connect to the legacy SSL port, requires at least the host to be specified + credentials?: any; // Dictionary (optional) - TLS or SSL key and certificate credentials + actAs?: string; // if admin user act on behalf of another user (just user) + disallowTLS?: boolean; // prevent upgrading the connection to a secure one via TLS + preferred?: string; // Preferred SASL mechanism to use + bosh?: Bosh; +} + +interface Bosh { + url?: string; + prebind?: (error: any, data: any) => void; +} diff --git a/node-xmpp-client/node-xmpp-client-tests.ts b/node-xmpp-client/node-xmpp-client-tests.ts new file mode 100644 index 0000000000..734067738e --- /dev/null +++ b/node-xmpp-client/node-xmpp-client-tests.ts @@ -0,0 +1,21 @@ +import {Client} from './index'; + +let client = new Client({ + jid: 'user@example.com', + password: 'password' +}); + +client.connect(); + +client.on('online', () => {}); + +client.on('stanza', stanza => { + let _ = stanza; +}); + +let stanza = new Client.Stanza('chat', {}) + .c('show').t('chat').up() + .c('status').t('message'); +client.send(stanza); + +client.disconnect(); diff --git a/node-xmpp-client/tsconfig.json b/node-xmpp-client/tsconfig.json new file mode 100644 index 0000000000..c76db9a985 --- /dev/null +++ b/node-xmpp-client/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", + "node-xmpp-client-tests.ts" + ] +} diff --git a/node-xmpp-client/tslint.json b/node-xmpp-client/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/node-xmpp-client/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/node-zookeeper-client/index.d.ts b/node-zookeeper-client/index.d.ts new file mode 100644 index 0000000000..d88eab9fa5 --- /dev/null +++ b/node-zookeeper-client/index.d.ts @@ -0,0 +1,179 @@ +// Type definitions for node-zookeeper-client 0.2 +// Project: https://github.com/alexguan/node-zookeeper-client +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import * as EventEmitter from "events"; + +export class Id { + scheme: string; + id: string; + constructor(scheme: string, id: string); +} + +export class ACL { + perms: number; + id: Id; + constructor(perms: number, id: Id); +} + +export const Permission: { + READ: number, + WRITE: number, + CREATE: number, + DELETE: number, + ADMIN: number, + ALL: number, +}; + +export interface Stat { + czxid: number; + mzxid: number; + ctime: number; + mtime: number; + version: number; + cversion: number; + aversion: number; + ephemeralOwner: number; + dataLength: number; + numChildren: number; + pzxid: number; +} + +export class State { + static DISCONNECTED: State; + static SYNC_CONNECTED: State; + static AUTH_FAILED: State; + static CONNECTED_READ_ONLY: State; + static SASL_AUTHENTICATED: State; + static EXPIRED: State; + + name: string; + code: number; + constructor(name: string, code: number); + toString(): string; +} + +export class Event { + static NODE_CREATED: number; + static NODE_DELETED: number; + static NODE_DATA_CHANGED: number; + static NODE_CHILDREN_CHANGED: number; + type: string; + name: string; + path: string; + constructor(type: string, name: string, path: string); + toString(): string; + getType(): string; + getName(): string; + getPath(): string; +} + +interface Transaction { + create(path: string, dataOrAclsOrmode1?: Buffer | ACL[] | number, dataOrAclsOrmode2?: Buffer | ACL[] | number, dataOrAclsOrmode3?: Buffer | ACL[] | number): this; + setData(path: string, data: Buffer | null, version?: number): this; + check(path: string, version?: number): this; + remove(path: string, version?: number): this; + commit(callback: (error: Error | Exception, results: any) => void): void; +} + +interface Client extends EventEmitter { + connect(): void; + close(): void; + create(path: string, callback: (error: Error | Exception, path: string) => void): void; + create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + create( + path: string, + dataOrAclsOrmode1: Buffer | ACL[] | number, + dataOrAclsOrmode2: Buffer | ACL[] | number, + dataOrAclsOrmode3: Buffer | ACL[] | number, + callback: (error: Error | Exception, path: string) => void): void; + remove(path: string, callback: (error: Error | Exception) => void): void; + remove(path: string, version: number, callback: (error: Error | Exception) => void): void; + exists(path: string, callback: (error: Error | Exception, stat: Stat) => void): void; + exists(path: string, watcher: (event: Event) => void, callback: (error: Error | Exception, stat: Stat) => void): void; + getChildren(path: string, callback: (error: Error | Exception, children: string[], stat: Stat) => void): void; + getChildren(path: string, watcher: (event: Event) => void, callback: (error: Error | Exception, children: string[], stat: Stat) => void): void; + getData(path: string, callback: (error: Error | Exception, data: Buffer, stat: Stat) => void): void; + getData(path: string, watcher: (event: Event) => void, callback: (error: Error | Exception, data: Buffer, stat: Stat) => void): void; + setData(path: string, data: Buffer | null, callback: (error: Error | Exception, stat: Stat) => void): void; + setData(path: string, data: Buffer | null, version: number, callback: (error: Error | Exception, stat: Stat) => void): void; + getACL(path: string, callback: (error: Error | Exception, acls: ACL[], stat: Stat) => void): void; + setACL(path: string, acls: ACL[], callback: (error: Error | Exception, stat: Stat) => void): void; + setACL(path: string, acls: ACL[], version: number, callback: (error: Error | Exception, stat: Stat) => void): void; + transaction(): Transaction; + mkdirp(path: string, callback: (error: Error | Exception, path: string) => void): void; + mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + mkdirp( + path: string, + dataOrAclsOrmode1: Buffer | ACL[] | number, + dataOrAclsOrmode2: Buffer | ACL[] | number, + dataOrAclsOrmode3: Buffer | ACL[] | number, + callback: (error: Error | Exception, path: string) => void): void; + addAuthInfo(scheme: string, auth: Buffer): void; + getState(): State; + getSessionId(): Buffer; + getSessionPassword(): Buffer; + getSessionTimeout(): number; + + on(event: "state", cb: (state: State) => void): this; + on(event: "connected" | "connectedReadOnly" | "disconnected" | "expired" | "authenticationFailed" | string, cb: () => void): this; + + once(event: "state", cb: (state: State) => void): this; + once(event: "connected" | "connectedReadOnly" | "disconnected" | "expired" | "authenticationFailed" | string, cb: () => void): this; + + addListener(event: "state", cb: (state: State) => void): this; + addListener(event: "connected" | "connectedReadOnly" | "disconnected" | "expired" | "authenticationFailed" | string, cb: () => void): this; +} + +export interface Option { + sessionTimeout: number; + spinDelay: number; + retries: number; +} + +export function createClient(connectionString: string, options?: Partial
+
; } } interface DashboardProps { - router: InjectedRouter -}; + router: InjectedRouter; +} class Dashboard extends React.Component { @@ -58,30 +95,32 @@ class Dashboard extends React.Component { render() { return
This is a dashboard -
+
; } } -const DashboardWithRouter = withRouter(Dashboard) +const DashboardWithRouter = withRouter(Dashboard); class NotFound extends React.Component<{}, {}> { render() { return
This path does not exists -
+
; } } +type UsersProps = RouteComponentProps<{}, {}>; -class Users extends React.Component<{}, {}> { +class Users extends React.Component { render() { + const { location, params, route, routes, router, routeParams } = this.props; return
This is a user list -
+
; } } @@ -95,8 +134,19 @@ ReactDOM.render(( -), document.body) +), document.body); +ReactDOM.render(( + + + +), document.body); + +ReactDOM.render(( + + + +), document.body); const history = createMemoryHistory("baseurl"); const routes = ( @@ -106,7 +156,11 @@ const routes = ( ); -match({history, routes, location: "baseurl"}, (error, redirectLocation, renderProps) => { +match({ routes, location: "baseurl" }, (error, redirectLocation, renderProps) => { + renderToString(); +}); + +match({ history, routes }, (error, redirectLocation, renderProps) => { renderToString(); }); diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index 69c7baf8e5..301ed3f651 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "react-router-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -14,14 +10,35 @@ "strictNullChecks": false, "jsx": "react", "baseUrl": "../", + "typeRoots": ["../"], "paths": { - "history": ["history/v2"] + "history": ["history/v3"], + "history/*": ["history/v3/*"] }, - "typeRoots": [ - "../" - ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "lib/applyRouterMiddleware.d.ts", + "lib/browserHistory.d.ts", + "lib/createMemoryHistory.d.ts", + "lib/hashHistory.d.ts", + "lib/IndexLink.d.ts", + "lib/IndexRedirect.d.ts", + "lib/IndexRoute.d.ts", + "lib/Link.d.ts", + "lib/match.d.ts", + "lib/PatternUtils.d.ts", + "lib/PropTypes.d.ts", + "lib/Redirect.d.ts", + "lib/Route.d.ts", + "lib/Router.d.ts", + "lib/RouterContext.d.ts", + "lib/RouteUtils.d.ts", + "lib/useRouterHistory.d.ts", + "lib/withRouter.d.ts", + "react-router-tests.tsx" + ] } diff --git a/react-router/tslint.json b/react-router/tslint.json index e050abdce9..377cc837d4 100644 --- a/react-router/tslint.json +++ b/react-router/tslint.json @@ -1,7 +1 @@ -{ - "extends": "../tslint.json", - "rules": { - "forbidden-types": false, - "no-empty-interface": false - } -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/react-router/v2/index.d.ts b/react-router/v2/index.d.ts new file mode 100644 index 0000000000..67994b6710 --- /dev/null +++ b/react-router/v2/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for react-router 2.0 +// Project: https://github.com/rackt/react-router +// Definitions by: Sergey Buturlakin +// Yuichi Murata +// Václav Ostrožlík +// Nathan Brown +// Alex Wendland +// Kostya Esmukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace ReactRouter; + +import * as React from 'react'; + +export const routerShape: React.Requireable; + +export const locationShape: React.Requireable; + +import Router from "./lib/Router"; +import Link from "./lib/Link"; +import IndexLink from "./lib/IndexLink"; +import IndexRedirect from "./lib/IndexRedirect"; +import IndexRoute from "./lib/IndexRoute"; +import Redirect from "./lib/Redirect"; +import Route from "./lib/Route"; +import * as History from "./lib/routerHistory"; +import Lifecycle from "./lib/Lifecycle"; +import RouteContext from "./lib/RouteContext"; +import browserHistory from "./lib/browserHistory"; +import hashHistory from "./lib/hashHistory"; +import useRoutes from "./lib/useRoutes"; +import { createRoutes } from "./lib/RouteUtils"; +import { formatPattern } from "./lib/PatternUtils"; +import RouterContext from "./lib/RouterContext"; +import PropTypes from "./lib/PropTypes"; +import match from "./lib/match"; +import useRouterHistory from "./lib/useRouterHistory"; +import createMemoryHistory from "./lib/createMemoryHistory"; +import withRouter from "./lib/withRouter"; +import applyRouterMiddleware from "./lib/applyRouterMiddleware"; + +// PlainRoute is defined in the API documented at: +// https://github.com/rackt/react-router/blob/master/docs/API.md +// but not included in any of the .../lib modules above. +export type PlainRoute = Router.PlainRoute; + +// The following definitions are also very useful to export +// because by using these types lots of potential type errors +// can be exposed: +export type EnterHook = Router.EnterHook; +export type LeaveHook = Router.LeaveHook; +export type ParseQueryString = Router.ParseQueryString; +export type LocationDescriptor = Router.LocationDescriptor; +export type RedirectFunction = Router.RedirectFunction; +export type RouteComponent = Router.RouteComponent; +export type RouteComponentProps = Router.RouteComponentProps; +export type RouteConfig = Router.RouteConfig; +export type RouteHook = Router.RouteHook; +export type StringifyQuery = Router.StringifyQuery; +export type RouterListener = Router.RouterListener; +export type RouterState = Router.RouterState; +export type InjectedRouter = Router.InjectedRouter; + +export type HistoryBase = History.HistoryBase; +export type RouterOnContext = Router.RouterOnContext; +export type RouteProps = Route.RouteProps; +export type LinkProps = Link.LinkProps; + +export { + Router, + Link, + IndexLink, + IndexRedirect, + IndexRoute, + Redirect, + Route, + History, + browserHistory, + hashHistory, + Lifecycle, + RouteContext, + useRoutes, + createRoutes, + formatPattern, + RouterContext, + PropTypes, + match, + useRouterHistory, + createMemoryHistory, + withRouter, + applyRouterMiddleware +}; + +export default Router; diff --git a/react-router/v2/lib/IndexLink.d.ts b/react-router/v2/lib/IndexLink.d.ts new file mode 100644 index 0000000000..56ecf82c1d --- /dev/null +++ b/react-router/v2/lib/IndexLink.d.ts @@ -0,0 +1,5 @@ +import Link from './Link'; + +declare const IndexLink: Link; +export default IndexLink; + diff --git a/react-router/v2/lib/IndexRedirect.d.ts b/react-router/v2/lib/IndexRedirect.d.ts new file mode 100644 index 0000000000..41dab299c8 --- /dev/null +++ b/react-router/v2/lib/IndexRedirect.d.ts @@ -0,0 +1,17 @@ +import Router from './Router'; +import * as React from 'react'; +import * as H from 'history'; + +declare const self: self.IndexRedirect; +type self = self.IndexRedirect; +export default self; + +declare namespace self { + interface IndexRedirectProps extends React.Props { + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface IndexRedirectElement extends React.ReactElement { } + interface IndexRedirect extends React.ComponentClass { } +} diff --git a/react-router/v2/lib/IndexRoute.d.ts b/react-router/v2/lib/IndexRoute.d.ts new file mode 100644 index 0000000000..b11b16d0e2 --- /dev/null +++ b/react-router/v2/lib/IndexRoute.d.ts @@ -0,0 +1,20 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.IndexRoute; +type self = self.IndexRoute; +export default self; + +declare namespace self { + interface IndexRouteProps extends React.Props { + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (location: H.Location, cb: (error: any, component?: Router.RouteComponent) => void) => void; + getComponents?: (location: H.Location, cb: (error: any, components?: Router.RouteComponents) => void) => void; + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + } + interface IndexRoute extends React.ComponentClass { } + interface IndexRouteElement extends React.ReactElement { } +} \ No newline at end of file diff --git a/react-router/lib/Lifecycle.d.ts b/react-router/v2/lib/Lifecycle.d.ts similarity index 100% rename from react-router/lib/Lifecycle.d.ts rename to react-router/v2/lib/Lifecycle.d.ts diff --git a/react-router/v2/lib/Link.d.ts b/react-router/v2/lib/Link.d.ts new file mode 100644 index 0000000000..d90578b9f9 --- /dev/null +++ b/react-router/v2/lib/Link.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; + +declare const Link: Link; +type Link = Link.Link; + +export default Link; + +declare namespace Link { + interface LinkProps extends React.HTMLAttributes { + activeStyle?: React.CSSProperties; + activeClassName?: string; + onlyActiveOnIndex?: boolean; + to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); + } + + interface Link extends React.ComponentClass {} + interface LinkElement extends React.ReactElement {} +} diff --git a/react-router/v2/lib/PatternUtils.d.ts b/react-router/v2/lib/PatternUtils.d.ts new file mode 100644 index 0000000000..50e90f6e49 --- /dev/null +++ b/react-router/v2/lib/PatternUtils.d.ts @@ -0,0 +1 @@ +export function formatPattern(pattern: string, params: {}): string; diff --git a/react-router/v2/lib/PropTypes.d.ts b/react-router/v2/lib/PropTypes.d.ts new file mode 100644 index 0000000000..bbd6431070 --- /dev/null +++ b/react-router/v2/lib/PropTypes.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; + +export function falsy(props: any, propName: string, componentName: string): Error; +export const history: React.Requireable; +export const location: React.Requireable; +export const component: React.Requireable; +export const components: React.Requireable; +export const route: React.Requireable; +export const routes: React.Requireable; + +export default { + falsy, + history, + location, + component, + components, + route +}; + diff --git a/react-router/v2/lib/Redirect.d.ts b/react-router/v2/lib/Redirect.d.ts new file mode 100644 index 0000000000..e09b576d53 --- /dev/null +++ b/react-router/v2/lib/Redirect.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.Redirect; +type self = typeof self; +export default self; + +declare namespace self { + interface RedirectProps extends React.Props { + path?: Router.RoutePattern; + from?: Router.RoutePattern; // alias for path + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface Redirect extends React.ComponentClass { } + interface RedirectElement extends React.ReactElement { } +} diff --git a/react-router/v2/lib/Route.d.ts b/react-router/v2/lib/Route.d.ts new file mode 100644 index 0000000000..7e4b548a21 --- /dev/null +++ b/react-router/v2/lib/Route.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import Router from './Router'; +import { Location } from 'history'; + +declare const self: self.Route; +type self = self.Route; +export default self; + +declare namespace self { + + interface RouteProps extends React.Props { + path?: Router.RoutePattern; + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void; + getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void; + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + onChange?: Router.ChangeHook; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; + } + interface Route extends React.ComponentClass {} + interface RouteElement extends React.ReactElement {} +} diff --git a/react-router/lib/RouteContext.d.ts b/react-router/v2/lib/RouteContext.d.ts similarity index 100% rename from react-router/lib/RouteContext.d.ts rename to react-router/v2/lib/RouteContext.d.ts diff --git a/react-router/v2/lib/RouteUtils.d.ts b/react-router/v2/lib/RouteUtils.d.ts new file mode 100644 index 0000000000..7065056ff5 --- /dev/null +++ b/react-router/v2/lib/RouteUtils.d.ts @@ -0,0 +1,8 @@ +import * as React from 'react'; +import Router from './Router'; + +type E = React.ReactElement; +export function isReactChildren(object: E | E[]): boolean; +export function createRouteFromReactElement(element: E): Router.PlainRoute; +export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[]; +export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[]; diff --git a/react-router/v2/lib/Router.d.ts b/react-router/v2/lib/Router.d.ts new file mode 100644 index 0000000000..a7dff58369 --- /dev/null +++ b/react-router/v2/lib/Router.d.ts @@ -0,0 +1,116 @@ +import * as React from 'react'; +import RouterContext from './RouterContext'; +import { + QueryString, Query, + Location, LocationDescriptor, LocationState as HLocationState, + History, Href, + Pathname, Path } from 'history'; + +declare const Router: Router; +interface Router extends React.ComponentClass { } + +export default Router; + +// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md + +declare namespace Router { + type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; + type RoutePattern = string; + interface RouteComponents { [key: string]: RouteComponent; } + + type ParseQueryString = (queryString: QueryString) => Query; + type StringifyQuery = (queryObject: Query) => QueryString; + + type Component = React.ReactType; + type RouteComponent = Component; + + type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; + type LeaveHook = () => void; + type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; + type RouteHook = (nextLocation?: Location) => any; + + interface Params { [param: string]: string; } + + type RouterListener = (error: Error, nextState: RouterState) => void; + + interface LocationDescriptor { + pathname?: Pathname; + query?: Query; + hash?: Href; + state?: HLocationState; + } + + interface RedirectFunction { + (location: LocationDescriptor): void; + /** + * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated + */ + (state: HLocationState, pathname: Pathname | Path, query?: Query): void; + } + + interface RouterState { + location: Location; + routes: PlainRoute[]; + params: Params; + components: RouteComponent[]; + } + + interface RouterProps extends React.Props { + history?: History; + routes?: RouteConfig; // alias for children + createElement?: (component: RouteComponent, props: Object) => any; + onError?: (error: any) => any; + onUpdate?: () => any; + parseQueryString?: ParseQueryString; + stringifyQuery?: StringifyQuery; + basename?: string; + render?: (renderProps: React.Props<{}>) => RouterContext; + } + + interface PlainRoute { + path?: RoutePattern; + component?: RouteComponent; + components?: RouteComponents; + getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; + getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; + onEnter?: EnterHook; + onLeave?: LeaveHook; + indexRoute?: PlainRoute; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; + childRoutes?: PlainRoute[]; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; + } + + interface RouteComponentProps { + history?: History; + location?: Location; + params?: P; + route?: PlainRoute; + routeParams?: R; + routes?: PlainRoute[]; + children?: React.ReactElement; + } + + interface RouterOnContext extends History { + setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; + isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; + } + + // Wrap a component using withRouter(Component) to provide a router object + // to the Component's props, allowing the Component to programmatically call + // push and other functions. + // + // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md + + interface InjectedRouter { + push: (pathOrLoc: Path | LocationDescriptor) => void; + replace: (pathOrLoc: Path | LocationDescriptor) => void; + go: (n: number) => void; + goBack: () => void; + goForward: () => void; + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void; + createPath(path: History.Path, query?: History.Query): History.Path; + createHref(path: History.Path, query?: History.Query): History.Href; + isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean; + } +} diff --git a/react-router/v2/lib/RouterContext.d.ts b/react-router/v2/lib/RouterContext.d.ts new file mode 100644 index 0000000000..b6eab5831c --- /dev/null +++ b/react-router/v2/lib/RouterContext.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import * as H from 'history'; +import Router from './Router'; + +declare const self: self.RouterContext; +type self = self.RouterContext; +export default self; + +declare namespace self { + interface RouterContextProps extends React.Props { + history?: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; + location: H.Location; + routes: Router.RouteConfig; + params: Router.Params; + components?: Router.RouteComponent[]; + } + interface RouterContext extends React.ComponentClass {} + interface RouterContextElement extends React.ReactElement { + history?: H.History; + location: H.Location; + router?: Router; + } +} \ No newline at end of file diff --git a/react-router/v2/lib/applyRouterMiddleware.d.ts b/react-router/v2/lib/applyRouterMiddleware.d.ts new file mode 100644 index 0000000000..ed87d815db --- /dev/null +++ b/react-router/v2/lib/applyRouterMiddleware.d.ts @@ -0,0 +1,9 @@ +import * as React from 'react'; +import Router from './Router'; +import RouterContext from './RouterContext'; + +export interface Middleware { + renderRouterContext?: (previous: RouterContext, props: React.Props<{}>) => RouterContext; + renderRouteComponent?: (previous: Router.RouteComponent, props: React.Props<{}>) => Router.RouteComponent; +} +export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => RouterContext; diff --git a/react-router/v2/lib/browserHistory.d.ts b/react-router/v2/lib/browserHistory.d.ts new file mode 100644 index 0000000000..aabbdc23f9 --- /dev/null +++ b/react-router/v2/lib/browserHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const browserHistory: History; +export default browserHistory; diff --git a/react-router/v2/lib/createMemoryHistory.d.ts b/react-router/v2/lib/createMemoryHistory.d.ts new file mode 100644 index 0000000000..5df481bfa1 --- /dev/null +++ b/react-router/v2/lib/createMemoryHistory.d.ts @@ -0,0 +1,3 @@ +import * as H from 'history'; + +export default function createMemoryHistory(options?: H.HistoryOptions): H.History; \ No newline at end of file diff --git a/react-router/v2/lib/hashHistory.d.ts b/react-router/v2/lib/hashHistory.d.ts new file mode 100644 index 0000000000..79f89c2f1a --- /dev/null +++ b/react-router/v2/lib/hashHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const hashHistory: History; +export default hashHistory; diff --git a/react-router/v2/lib/match.d.ts b/react-router/v2/lib/match.d.ts new file mode 100644 index 0000000000..e311ea69df --- /dev/null +++ b/react-router/v2/lib/match.d.ts @@ -0,0 +1,17 @@ +import * as H from 'history'; +import Router from './Router'; + +interface MatchArgs { + routes?: Router.RouteConfig; + history?: H.History; + location?: H.Location | string; + parseQueryString?: Router.ParseQueryString; + stringifyQuery?: Router.StringifyQuery; +} +interface MatchState extends Router.RouterState { + history: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; +} +export default function match(args: MatchArgs, cb: (error: any, nextLocation: H.Location, nextState: MatchState) => void): void; + diff --git a/react-router/lib/routerHistory.d.ts b/react-router/v2/lib/routerHistory.d.ts similarity index 100% rename from react-router/lib/routerHistory.d.ts rename to react-router/v2/lib/routerHistory.d.ts diff --git a/react-router/v2/lib/useRouterHistory.d.ts b/react-router/v2/lib/useRouterHistory.d.ts new file mode 100644 index 0000000000..160375d2f0 --- /dev/null +++ b/react-router/v2/lib/useRouterHistory.d.ts @@ -0,0 +1,3 @@ +import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; + +export default function useRouterHistory(createHistory: CreateHistory): (options?: HistoryOptions) => History & HistoryQueries; diff --git a/react-router/lib/useRoutes.d.ts b/react-router/v2/lib/useRoutes.d.ts similarity index 100% rename from react-router/lib/useRoutes.d.ts rename to react-router/v2/lib/useRoutes.d.ts diff --git a/react-router/v2/lib/withRouter.d.ts b/react-router/v2/lib/withRouter.d.ts new file mode 100644 index 0000000000..71330bbb21 --- /dev/null +++ b/react-router/v2/lib/withRouter.d.ts @@ -0,0 +1,4 @@ +import * as React from 'react'; + +declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C; +export default withRouter; diff --git a/react-router/v2/tsconfig.json b/react-router/v2/tsconfig.json new file mode 100644 index 0000000000..d9c384bdcf --- /dev/null +++ b/react-router/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "history": ["history/v2"], + "react-router": ["react-router/v2"], + "react-router/*": ["react-router/v2/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} diff --git a/react-router/v2/tslint.json b/react-router/v2/tslint.json new file mode 100644 index 0000000000..d032145676 --- /dev/null +++ b/react-router/v2/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-empty-interface": false + } +} diff --git a/react-scroll/index.d.ts b/react-scroll/index.d.ts index 93e09acc2b..1f31f5f4c3 100644 --- a/react-scroll/index.d.ts +++ b/react-scroll/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/fisshy/react-scroll // Definitions by: Ioannis Kokkinidis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; diff --git a/react-scrollbar/index.d.ts b/react-scrollbar/index.d.ts index dcfc90d02e..8d5628f4a5 100644 --- a/react-scrollbar/index.d.ts +++ b/react-scrollbar/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/souhe/reactScrollbar // Definitions by: Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/react-select/index.d.ts b/react-select/index.d.ts index 336eb5460b..5393888f3b 100644 --- a/react-select/index.d.ts +++ b/react-select/index.d.ts @@ -1,7 +1,8 @@ // Type definitions for react-select v1.0.0 // Project: https://github.com/JedWatson/react-select -// Definitions by: ESQUIBET Hugo , Gilad Gray , Izaak Baker , Tadas Dailyda , Mark Vujevits +// Definitions by: ESQUIBET Hugo , Gilad Gray , Izaak Baker , Tadas Dailyda , Mark Vujevits , Mike Deverell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; @@ -28,6 +29,11 @@ declare namespace ReactSelectClass { * @default true */ clearableValue?: boolean; + /** + * Do not allow this option to be selected + * @default false + */ + disabled?: boolean; } export interface MenuRendererProps { @@ -245,6 +251,10 @@ declare namespace ReactSelectClass { * onInputChange handler: function (inputValue) {} */ onInputChange?: (inputValue: string) => void; + /** + * onInputKeyDown handler: function (keyboardEvent) {} + */ + onInputKeyDown?: (event: KeyboardEvent) => void; /** * fires when the menu is scrolled to the bottom; can be used to paginate options */ @@ -267,6 +277,10 @@ declare namespace ReactSelectClass { * @default false */ openOnFocus?: boolean; + /** + * className to add to each option component + */ + optionClassName?: string; /** * option component to render in dropdown */ diff --git a/react-select/react-select-tests.tsx b/react-select/react-select-tests.tsx index d2704878d9..10a3f51833 100644 --- a/react-select/react-select-tests.tsx +++ b/react-select/react-select-tests.tsx @@ -99,6 +99,7 @@ class SelectTest extends React.Component, {}> { className: "test-select", key: "1", options: options, + optionClassName: 'test-select-option', optionRenderer: optionRenderer, autofocus: true, autosize: true, @@ -139,7 +140,15 @@ class SelectTest extends React.Component, {}> { class SelectWithStringValueTest extends React.Component, {}> { render() { - const options: Option[] = [{ label: "Foo", value: "bar" }]; + const options: Option[] = [{ + label: "Foo", + value: "bar", + }, { + label: "Foo2", + value: "bar2", + clearableValue: false, + disabled: true + }]; const onChange = (value: any) => console.log(value); const selectProps: ReactSelectProps = { diff --git a/react-side-effect/index.d.ts b/react-side-effect/index.d.ts index ed76d56af4..10f25ae1e3 100644 --- a/react-side-effect/index.d.ts +++ b/react-side-effect/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gaearon/react-side-effect // Definitions by: Remo H. Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import React = require("react"); diff --git a/react-sidebar/react-sidebar-tests.tsx b/react-sidebar/react-sidebar-tests.tsx index 8e08d85599..4b6dfd593e 100644 --- a/react-sidebar/react-sidebar-tests.tsx +++ b/react-sidebar/react-sidebar-tests.tsx @@ -7,6 +7,6 @@ const sidebarStyle: SidebarStyles = { content: { width: "300px" } }; -let sidebar1 = +const sidebar1 =

Content

; diff --git a/react-slick/index.d.ts b/react-slick/index.d.ts index 9bd267cad1..513fc0d440 100644 --- a/react-slick/index.d.ts +++ b/react-slick/index.d.ts @@ -2,10 +2,15 @@ // Project: https://github.com/akiran/react-slick // Definitions by: Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// interface __config { + accessibility?: boolean + nextArrow?: HTMLElement | any + prevArrow?: HTMLElement | any + pauseOnHover?: boolean className?: string adaptiveHeight?: boolean arrows?: boolean diff --git a/react-slick/react-slick-tests.tsx b/react-slick/react-slick-tests.tsx index 7b51dbdf3a..2d26b0dcf1 100644 --- a/react-slick/react-slick-tests.tsx +++ b/react-slick/react-slick-tests.tsx @@ -10,7 +10,8 @@ class SliderTest extends React.Component, {}> { slidesToShow: 8, slidesToScroll: 1, draggable: false, - infinite: false + infinite: false, + prevArrow: link }; return ( diff --git a/react-smooth-scrollbar/index.d.ts b/react-smooth-scrollbar/index.d.ts index df5746f9d4..6aea289136 100644 --- a/react-smooth-scrollbar/index.d.ts +++ b/react-smooth-scrollbar/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/idiotWu/react-smooth-scrollbar // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from "react"; import SmoothScrollbar, { ScrollbarOptions, ScrollStatusObject } from "smooth-scrollbar"; diff --git a/react-sortable-hoc/index.d.ts b/react-sortable-hoc/index.d.ts index b65bae7641..64a17f4800 100644 --- a/react-sortable-hoc/index.d.ts +++ b/react-sortable-hoc/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/clauderic/react-sortable-hoc // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare module 'react-sortable-hoc' { import React = require('react'); diff --git a/react-spinkit/index.d.ts b/react-spinkit/index.d.ts index 13c3542af6..05955e3f53 100644 --- a/react-spinkit/index.d.ts +++ b/react-spinkit/index.d.ts @@ -1,17 +1,19 @@ // Type definitions for react-spinkit 1.1.4 // Project: https://github.com/KyleAMathews/react-spinkit -// Definitions by: Qubo +// Definitions by: Qubo , Mleko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// +declare namespace spinner { + export interface SpinnerProps { + spinnerName?: string; + } -import { Component } from 'react'; - -interface Props { - spinnerName?: string; + export interface Spinner extends React.ComponentClass { + } } -declare class Spinner extends Component { } - -export default Spinner; +declare const spinner: spinner.Spinner; +export = spinner; diff --git a/react-spinkit/react-spinkit-tests.tsx b/react-spinkit/react-spinkit-tests.tsx index e8467a95da..a163400601 100644 --- a/react-spinkit/react-spinkit-tests.tsx +++ b/react-spinkit/react-spinkit-tests.tsx @@ -1,7 +1,7 @@ /// -import Spinner from 'react-spinkit'; +import * as Spinner from 'react-spinkit'; import * as React from 'react'; let spinner = ; diff --git a/react-split-pane/index.d.ts b/react-split-pane/index.d.ts index 3a6bc7bc6e..cdbb05d4c1 100644 --- a/react-split-pane/index.d.ts +++ b/react-split-pane/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/tomkp/react-split-pane // Definitions by: Roger Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/react-sticky/index.d.ts b/react-sticky/index.d.ts new file mode 100644 index 0000000000..2126d582ef --- /dev/null +++ b/react-sticky/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for react-sticky 5.0 +// Project: https://github.com/captivationsoftware/react-sticky +// Definitions by: Matej Lednicky , Curtis Warren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import * as React from "react"; + +declare module "react-sticky" { + + export var StickyContainer: React.ComponentClass>; + + export interface StickyProps { + isActive?: boolean; + className?: string; + style?: any; + stickyClassName?: string; + stickyStyle?: any; + topOffset?: number; + bottomOffset?: number; + onStickyStateChange?: (isSticky: boolean) => void; + } + + export var Sticky: React.ComponentClass; + +} + diff --git a/react-sticky/react-sticky-tests.tsx b/react-sticky/react-sticky-tests.tsx new file mode 100644 index 0000000000..6eb9d0e0d0 --- /dev/null +++ b/react-sticky/react-sticky-tests.tsx @@ -0,0 +1,16 @@ +import {Sticky, StickyContainer} from "react-sticky"; +import * as React from "react"; + +const StickyAllOptions: JSX.Element = + + undefined}> +
+ + ; + +const StickyNoOptions: JSX.Element = + + +
+ + ; diff --git a/react-sticky/tsconfig.json b/react-sticky/tsconfig.json new file mode 100644 index 0000000000..e2ea2938d1 --- /dev/null +++ b/react-sticky/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "jsx": "react", + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-sticky-tests.tsx" + ] +} + diff --git a/react-sticky/tslint.json b/react-sticky/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-sticky/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-swf/index.d.ts b/react-swf/index.d.ts index ba300908ba..c03f2748b2 100644 --- a/react-swf/index.d.ts +++ b/react-swf/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/syranide/react-swf // Definitions by: Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; export as namespace ReactSWF; diff --git a/react-swipeable-views/index.d.ts b/react-swipeable-views/index.d.ts index 745ebb4582..91b0cfa45b 100644 --- a/react-swipeable-views/index.d.ts +++ b/react-swipeable-views/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/oliviertassinari/react-swipeable-views // Definitions by: Michael Ledin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; diff --git a/react-swipeable/index.d.ts b/react-swipeable/index.d.ts index 52d0e9c178..fadf0f057f 100644 --- a/react-swipeable/index.d.ts +++ b/react-swipeable/index.d.ts @@ -2,6 +2,7 @@ // Project: https://www.npmjs.com/package/react-swipeable // Definitions by: Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/react-syntax-highlighter/index.d.ts b/react-syntax-highlighter/index.d.ts index 35019a7b7e..57d81c9d6d 100644 --- a/react-syntax-highlighter/index.d.ts +++ b/react-syntax-highlighter/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/conorhastings/react-syntax-highlighter // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare module 'react-syntax-highlighter' { import SyntaxHighlighter from 'react-syntax-highlighter/dist/light'; diff --git a/react-tabs/index.d.ts b/react-tabs/index.d.ts index ebb5ae644b..9e8abce3cb 100644 --- a/react-tabs/index.d.ts +++ b/react-tabs/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/reactjs/react-tabs/ // Definitions by: Yuu Igarashi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; diff --git a/react-tagcloud/index.d.ts b/react-tagcloud/index.d.ts index 9759e99094..c1e8990bf6 100644 --- a/react-tagcloud/index.d.ts +++ b/react-tagcloud/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/madox2/react-tagcloud // Definitions by: wassname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/react-test-renderer/index.d.ts b/react-test-renderer/index.d.ts index e3c27a057a..9908394888 100644 --- a/react-test-renderer/index.d.ts +++ b/react-test-renderer/index.d.ts @@ -2,6 +2,7 @@ // Project: https://facebook.github.io/react/ // Definitions by: Arvitaly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { ReactElement } from "react"; diff --git a/react-textarea-autosize/index.d.ts b/react-textarea-autosize/index.d.ts index ebf589f873..647d19c6ac 100644 --- a/react-textarea-autosize/index.d.ts +++ b/react-textarea-autosize/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/andreypopp/react-textarea-autosize // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare module "react-textarea-autosize" { import * as React from "react"; diff --git a/react-toggle/index.d.ts b/react-toggle/index.d.ts index af00deac09..29b3a547fd 100644 --- a/react-toggle/index.d.ts +++ b/react-toggle/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/aaronshaf/react-toggle // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { Component, HTMLAttributes, ReactNode } from "react"; diff --git a/react-toggle/react-toggle-tests.tsx b/react-toggle/react-toggle-tests.tsx index 9bec568663..f138268174 100644 --- a/react-toggle/react-toggle-tests.tsx +++ b/react-toggle/react-toggle-tests.tsx @@ -1,8 +1,8 @@ -import * as React from "react" -import Toggle from "react-toggle" +import * as React from "react"; +import Toggle from "react-toggle"; class Test extends React.Component<{}, {}> { - public render() { + render() { return ( ); diff --git a/react-user-tour/index.d.ts b/react-user-tour/index.d.ts index f1a0de4d46..2753a6f8b6 100644 --- a/react-user-tour/index.d.ts +++ b/react-user-tour/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/socialtables/react-user-tour // Definitions by: Carlo Cancellieri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/react-virtualized/index.d.ts b/react-virtualized/index.d.ts index ab43deb8b7..963af32a27 100644 --- a/react-virtualized/index.d.ts +++ b/react-virtualized/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bvaughn/react-virtualized // Definitions by: Andrew de Waal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -71,6 +72,69 @@ declare module "react-virtualized" { } export class List extends React.Component { } + // https://github.com/bvaughn/react-virtualized/blob/master/docs/Column.md + interface ColumnProps { + cellDataGetter?: (info: { columnData: any, dataKey: string, rowData: any }) => any; + cellRenderer?: (info: { cellData: any, columnData: any, dataKey: string, isScrolling: boolean, rowData: any, rowIndex: number }) => any; + className?: string; + columnData?: any; + dataKey: any; + disableSort?: boolean; + flexGrow?: number; + flexShrink?: number; + headerClassName?: string; + headerRenderer?: (info: { columnData: any, dataKey: string, disableSort: boolean, label: string, sortBy: string, sortDirection: string }) => any; + label?: string; + maxWidth?: number; + minWidth?: number; + style?: React.CSSProperties; + width: number; + } + + export class Column extends React.Component { } + + // ref: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md + interface TableProps { + autoHeight?: boolean; + children?: React.ReactNode; + className?: string; + disableHeader?: boolean; + estimatedRowSize?: number; + gridClassName?: string; + gridStyle?: any; + headerClassName?: string; + headerHeight: number; + headerStyle?: any; + height: number; + id?: string; + noRowsRender?: () => void; + onHeaderClick?: (dataKey: string, columnData: any) => void; + onRowClick?: (info: { index: number }) => void; + onRowDoubleClick?: (info: { index: number }) => void; + onRowMouseOut?: (info: { index: number }) => void; + onRowMouseOver?: (info: { index: number }) => void; + onRowsRendered?: (info: { index: number }) => void; + overscanRowCount?: number; + onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; + rowClassName?: string | ((info: { index: number }) => string); + rowCount: number; + rowGetter?: (info: { index: number }) => any; + rowHeight: number | ((info: { index: number }) => number); + rowRenderer?: (info: { index: number, isScrolling: boolean }) => React.ReactNode; + rowStyle?: React.CSSProperties | ((info: { index: number }) => React.CSSProperties); + scrollToAlignment?: string; + scrollToIndex?: number; + scrollTop?: number; + sort?: (info: { sortBy: string, sortDirection: 'ASC' | 'DESC' }) => void; + sortBy?: string; + sortDirection?: 'ASC' | 'DESC'; + style?: React.CSSProperties; + tabIndex?: number; + width: number; + } + + export class Table extends React.Component { } + /* * Higher-Order Components */ diff --git a/react-virtualized/react-virtualized-tests.tsx b/react-virtualized/react-virtualized-tests.tsx index 791e4df9a0..7da7e26c88 100644 --- a/react-virtualized/react-virtualized-tests.tsx +++ b/react-virtualized/react-virtualized-tests.tsx @@ -19,7 +19,9 @@ import { InfiniteLoader, ScrollSync, WindowScroller, - List + List, + Column, + Table, } from "react-virtualized"; /* @@ -128,6 +130,35 @@ function ListTest() { ); } +function TableTest() { + const list = [ + { name: 'Brian Vaughn', description: 'Software engineer' } + // And so on... + ]; + ReactDOM.render( + list[index]} + > + + +
, + document.getElementById('example') + ); +} + function VirtualScrollTest() { // List data as an array of strings const list = [ diff --git a/react-widgets/index.d.ts b/react-widgets/index.d.ts index 04b63d8a95..9db30eb706 100644 --- a/react-widgets/index.d.ts +++ b/react-widgets/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jquense/react-widgets // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; diff --git a/react-widgets/lib/DateTimePicker.d.ts b/react-widgets/lib/DateTimePicker.d.ts index 37e1474416..0760648984 100644 --- a/react-widgets/lib/DateTimePicker.d.ts +++ b/react-widgets/lib/DateTimePicker.d.ts @@ -31,6 +31,10 @@ interface DateTimePickerProps extends React.Props { * @default Date() */ currentDate?: Date; + /* + * Default value for current date. Useful for suggesting a date when the caldenar opens without keep forcing it once 'value' is set. + */ + defaultCurrentDate?: Date; /** * Change event Handler that is called when the currentDate is changed. The handler is * called with the currentDate object. @@ -93,11 +97,16 @@ interface DateTimePickerProps extends React.Props { onSelect?: (date?: Date) => void; /** * Whether or not the DateTimePicker is open. When unset (undefined) the DateTimePicker will - * handle the opening and closing internally. The defaultOpen prop can be used to set an - * initialization value for uncontrolled widgets. + * handle the opening and closing internally. * @enum false "calendar" "time" */ open?: boolean | "calendar" | "time"; + /** + * The defaultOpen prop can be used to set an + * initialization value for uncontrolled widgets. + * @enum false "calendar" "time" + */ + defaultOpen?: boolean | "calendar" | "time"; /** * Called when the DateTimePicker is about to open or close. onToggle should be used when * the open prop is set otherwise the widget will never open or close. diff --git a/react-widgets/lib/DropdownList.d.ts b/react-widgets/lib/DropdownList.d.ts index f8ac6d6579..52a8e83a99 100644 --- a/react-widgets/lib/DropdownList.d.ts +++ b/react-widgets/lib/DropdownList.d.ts @@ -87,10 +87,14 @@ interface DropdownListProps extends React.Props { onSearch?: (searchTerm: string) => void; /** * Whether or not the DropdownList is open. When unset (undefined) the DropdownList will - * handle the opening and closing internally. The defaultOpen prop can be used to set an - * initialization value for uncontrolled widgets. + * handle the opening and closing internally. */ open?: boolean; + /** + * The defaultOpen prop can be used to set an + * initialization value for uncontrolled widgets. + */ + defaultOpen?: boolean; /** * Called when the DropdownList is about to open or close. onToggle should be used when the * open prop is set otherwise the widget open buttons won't work. diff --git a/react/README.md b/react/README.md index 7d2b3d80ab..c09dc060c2 100644 --- a/react/README.md +++ b/react/README.md @@ -1,8 +1,31 @@ ## Known Problems & Workarounds -### **The type of `setState` is incorrect.** -The `setState(state)` method on `React.Component` takes an object with a subset of the properties on `S`, but there's no way to express this in TypeScript currently. The workaround is simple: make all properties on `S` optional. There are a number of [proposals](https://github.com/Microsoft/TypeScript/issues/2710) on [ways](https://github.com/Microsoft/TypeScript/issues/4889) to [solve](https://github.com/Microsoft/TypeScript/issues/7355) this problem, but nothing seems to have been approved yet. +### **The type of `setState` is will be overly strict prior to TS 2.1.5** +Starting with TypeScript 2.1, its more correct than it used to be, with a caveat: optional parameters on state interfaces are no longer valid. This issue is corrected in 2.1.5 (and beyond) and thus `Pick` becomes ideal. +```ts +interface FooState { + bar: string; + foo?: string; +} + +const defaultFooState: FooState = { + bar: "Hi", + foo: undefined, +}; + +class Foo extends React.Component<{}, FooState> { + public doStuff() { + this.setState(defaultFooState); + } +} +``` + +Prior to 2.1.5, this code will produce an error. The other way the types could be written (using `Partial<>` instead of `Pick<>`) would allow for you to set `undefined` to a parameter that is not allowed +to be `undefined`, which could lead to bugs. Users who want to keep optional state parameters should continue to use the hack of `setState({...} as any);` in versions prior to 2.1.5. + +(This caveat should be dropped after no later than March 2017, maybe sooner.) + ### **The type of `cloneElement` is incorrect.** This is similar to the `setState` problem, in that `cloneElement(element, props)` should should accept a `props` object with a subset of the properties on `element.props`. There is an additional complication, however—React attributes, such as `key` and `ref`, should also be accepted in `props`, but should not exist on `element.props`. The "correct" way to model this, then, is with ```ts diff --git a/react/index.d.ts b/react/index.d.ts index e59234ae6c..a3b778ad48 100644 --- a/react/index.d.ts +++ b/react/index.d.ts @@ -1,7 +1,8 @@ // Type definitions for React v15.0 // Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign , Microsoft , John Reilly +// Definitions by: Asana , AssureSign , Microsoft , John Reilly , Benoit Benezech , Patricio Zavolinsky , Digiguru // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 export = React; export as namespace React; @@ -80,6 +81,9 @@ declare namespace React { interface HTMLFactory extends DOMFactory, T> { } + interface ChangeTargetHTMLFactory extends DOMFactory, T> { + } + interface SVGFactory extends DOMFactory, SVGElement> { } @@ -164,9 +168,8 @@ declare namespace React { // Base component for plain JS classes class Component implements ComponentLifecycle { constructor(props?: P, context?: any); - constructor(...args: any[]); - setState(f: (prevState: S, props: P) => S, callback?: () => any): void; - setState(state: S, callback?: () => any): void; + setState(f: (prevState: S, props: P) => Pick, callback?: () => any): void; + setState(state: Pick, callback?: () => any): void; forceUpdate(callBack?: () => any): void; render(): JSX.Element | null; @@ -175,8 +178,8 @@ declare namespace React { // always pass children as variadic arguments to `createElement`. // In the future, if we can define its call signature conditionally // on the existence of `children` in `P`, then we should remove this. - props: { children?: ReactNode } & P; - state: S; + props: Readonly<{ children?: ReactNode }> & Readonly

; + state: Readonly; context: any; refs: { [key: string]: ReactInstance @@ -204,7 +207,7 @@ declare namespace React { (props: P & { children?: ReactNode }, context?: any): ReactElement; propTypes?: ValidationMap

; contextTypes?: ValidationMap; - defaultProps?: P; + defaultProps?: Partial

; displayName?: string; } @@ -213,7 +216,7 @@ declare namespace React { propTypes?: ValidationMap

; contextTypes?: ValidationMap; childContextTypes?: ValidationMap; - defaultProps?: P; + defaultProps?: Partial

; displayName?: string; } @@ -229,8 +232,8 @@ declare namespace React { */ type ClassType, C extends ComponentClass

> = C & - (new () => T) & - (new () => { props: P }); + (new (props?: P, context?: any) => T) & + (new (props?: P, context?: any) => { props: P }); // // Component Specs and Lifecycle @@ -270,9 +273,10 @@ declare namespace React { // // Event System // ---------------------------------------------------------------------- - interface SyntheticEventBase { + + interface SyntheticEvent { bubbles: boolean; - currentTarget: EventTarget & CURRENT; + currentTarget: EventTarget & T; cancelable: boolean; defaultPrevented: boolean; eventPhase: number; @@ -283,16 +287,12 @@ declare namespace React { stopPropagation(): void; isPropagationStopped(): boolean; persist(): void; - target: EventTarget & TARGET; + // If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239 + target: EventTarget; timeStamp: Date; type: string; } - interface SyntheticEvent extends SyntheticEventBase { - // If you thought target should be `EventTarget & T`, - // see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239 - } - interface ClipboardEvent extends SyntheticEvent { clipboardData: DataTransfer; } @@ -312,7 +312,8 @@ declare namespace React { interface FormEvent extends SyntheticEvent { } - interface ChangeEvent extends SyntheticEventBase { + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; } interface KeyboardEvent extends SyntheticEvent { @@ -370,13 +371,13 @@ declare namespace React { deltaZ: number; } - interface AnimationEvent extends SyntheticEvent<{}> { + interface AnimationEvent extends SyntheticEvent { animationName: string; pseudoElement: string; elapsedTime: number; } - interface TransitionEvent extends SyntheticEvent<{}> { + interface TransitionEvent extends SyntheticEvent { propertyName: string; pseudoElement: string; elapsedTime: number; @@ -403,8 +404,8 @@ declare namespace React { type TouchEventHandler = EventHandler>; type UIEventHandler = EventHandler>; type WheelEventHandler = EventHandler>; - type AnimationEventHandler = EventHandler; - type TransitionEventHandler = EventHandler; + type AnimationEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; // // Props / DOM Attributes @@ -433,6 +434,9 @@ declare namespace React { interface HTMLProps extends HTMLAttributes, ClassAttributes { } + interface ChangeTargetHTMLProps extends ChangeTargetHTMLAttributes, ClassAttributes { + } + interface SVGProps extends SVGAttributes, ClassAttributes { } @@ -465,7 +469,7 @@ declare namespace React { onBlurCapture?: FocusEventHandler; // Form Events - onChange?: ChangeEventHandler; + onChange?: FormEventHandler; onChangeCapture?: FormEventHandler; onInput?: FormEventHandler; onInputCapture?: FormEventHandler; @@ -593,18 +597,29 @@ declare namespace React { onWheelCapture?: WheelEventHandler; // Animation Events - onAnimationStart?: AnimationEventHandler; - onAnimationStartCapture?: AnimationEventHandler; - onAnimationEnd?: AnimationEventHandler; - onAnimationEndCapture?: AnimationEventHandler; - onAnimationIteration?: AnimationEventHandler; - onAnimationIterationCapture?: AnimationEventHandler; + onAnimationStart?: AnimationEventHandler; + onAnimationStartCapture?: AnimationEventHandler; + onAnimationEnd?: AnimationEventHandler; + onAnimationEndCapture?: AnimationEventHandler; + onAnimationIteration?: AnimationEventHandler; + onAnimationIterationCapture?: AnimationEventHandler; // Transition Events - onTransitionEnd?: TransitionEventHandler; - onTransitionEndCapture?: TransitionEventHandler; + onTransitionEnd?: TransitionEventHandler; + onTransitionEndCapture?: TransitionEventHandler; } + // See CSS 3 CSS-wide keywords https://www.w3.org/TR/css3-values/#common-keywords + // See CSS 3 Explicit Defaulting https://www.w3.org/TR/css-cascade-3/#defaulting-keywords + // "all CSS properties can accept these values" + type CSSWideKeyword = "initial" | "inherit" | "unset"; + + // See CSS 3 type https://drafts.csswg.org/css-values-3/#percentages + type CSSPercentage = string; + + // See CSS 3 type https://drafts.csswg.org/css-values-3/#lengths + type CSSLength = number | string; + // This interface is not complete. Only properties accepting // unitless numbers are listed here (see CSSProperty.js in React) interface CSSProperties { @@ -612,59 +627,59 @@ declare namespace React { /** * Aligns a flex container's lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. */ - alignContent?: any; + alignContent?: CSSWideKeyword | any; /** * Sets the default alignment in the cross axis for all of the flex container's items, including anonymous flex items, similarly to how justify-content aligns items along the main axis. */ - alignItems?: any; + alignItems?: CSSWideKeyword | any; /** * Allows the default alignment to be overridden for individual flex items. */ - alignSelf?: any; + alignSelf?: CSSWideKeyword | any; /** * This property allows precise alignment of elements, such as graphics, that do not have a baseline-table or lack the desired baseline in their baseline-table. With the alignment-adjust property, the position of the baseline identified by the alignment-baseline can be explicitly determined. It also determines precisely the alignment point for each glyph within a textual element. */ - alignmentAdjust?: any; + alignmentAdjust?: CSSWideKeyword | any; - alignmentBaseline?: any; + alignmentBaseline?: CSSWideKeyword | any; /** * Defines a length of time to elapse before an animation starts, allowing an animation to begin execution some time after it is applied. */ - animationDelay?: any; + animationDelay?: CSSWideKeyword | any; /** * Defines whether an animation should run in reverse on some or all cycles. */ - animationDirection?: any; + animationDirection?: CSSWideKeyword | any; /** * Specifies how many times an animation cycle should play. */ - animationIterationCount?: any; + animationIterationCount?: CSSWideKeyword | any; /** * Defines the list of animations that apply to the element. */ - animationName?: any; + animationName?: CSSWideKeyword | any; /** * Defines whether an animation is running or paused. */ - animationPlayState?: any; + animationPlayState?: CSSWideKeyword | any; /** * Allows changing the style of any element to platform-based interface elements or vice versa. */ - appearance?: any; + appearance?: CSSWideKeyword | any; /** * Determines whether or not the “back” side of a transformed element is visible when facing the viewer. */ - backfaceVisibility?: any; + backfaceVisibility?: CSSWideKeyword | any; /** * Shorthand property to set the values for one or more of: @@ -672,1326 +687,1353 @@ declare namespace React { * background-origin, background-position, background-repeat, * background-size, and background-attachment. */ - background?: any; + background?: CSSWideKeyword | any; /** * If a background-image is specified, this property determines * whether that image's position is fixed within the viewport, * or scrolls along with its containing block. + * See CSS 3 background-attachment property https://drafts.csswg.org/css-backgrounds-3/#the-background-attachment */ - backgroundAttachment?: "scroll" | "fixed" | "local"; + backgroundAttachment?: CSSWideKeyword | "scroll" | "fixed" | "local"; /** * This property describes how the element's background images should blend with each other and the element's background color. * The value is a list of blend modes that corresponds to each background image. Each element in the list will apply to the corresponding element of background-image. If a property doesn’t have enough comma-separated values to match the number of layers, the UA must calculate its used value by repeating the list of values until there are enough. */ - backgroundBlendMode?: any; + backgroundBlendMode?: CSSWideKeyword | any; /** * Sets the background color of an element. */ - backgroundColor?: any; + backgroundColor?: CSSWideKeyword | any; - backgroundComposite?: any; + backgroundComposite?: CSSWideKeyword | any; /** * Applies one or more background images to an element. These can be any valid CSS image, including url() paths to image files or CSS gradients. */ - backgroundImage?: any; + backgroundImage?: CSSWideKeyword | any; /** * Specifies what the background-position property is relative to. */ - backgroundOrigin?: any; + backgroundOrigin?: CSSWideKeyword | any; /** * Sets the position of a background image. */ - backgroundPosition?: any; + backgroundPosition?: CSSWideKeyword | any; /** * Background-repeat defines if and how background images will be repeated after they have been sized and positioned */ - backgroundRepeat?: any; + backgroundRepeat?: CSSWideKeyword | any; /** * Obsolete - spec retired, not implemented. */ - baselineShift?: any; + baselineShift?: CSSWideKeyword | any; /** * Non standard. Sets or retrieves the location of the Dynamic HTML (DHTML) behavior. */ - behavior?: any; + behavior?: CSSWideKeyword | any; /** * Shorthand property that defines the different properties of all four sides of an element's border in a single declaration. It can be used to set border-width, border-style and border-color, or a subset of these. */ - border?: any; + border?: CSSWideKeyword | any; /** * Shorthand that sets the values of border-bottom-color, * border-bottom-style, and border-bottom-width. */ - borderBottom?: any; + borderBottom?: CSSWideKeyword | any; /** * Sets the color of the bottom border of an element. */ - borderBottomColor?: any; + borderBottomColor?: CSSWideKeyword | any; /** * Defines the shape of the border of the bottom-left corner. */ - borderBottomLeftRadius?: any; + borderBottomLeftRadius?: CSSWideKeyword | any; /** * Defines the shape of the border of the bottom-right corner. */ - borderBottomRightRadius?: any; + borderBottomRightRadius?: CSSWideKeyword | any; /** * Sets the line style of the bottom border of a box. */ - borderBottomStyle?: any; + borderBottomStyle?: CSSWideKeyword | any; /** * Sets the width of an element's bottom border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ - borderBottomWidth?: any; + borderBottomWidth?: CSSWideKeyword | any; /** * Border-collapse can be used for collapsing the borders between table cells */ - borderCollapse?: any; + borderCollapse?: CSSWideKeyword | any; /** - * The CSS border-color property sets the color of an element's four borders. This property can have from one to four values, made up of the elementary properties: • border-top-color + * The CSS border-color property sets the color of an element's four borders. This property can have from one to four values, made up of the elementary properties: + * • border-top-color * • border-right-color * • border-bottom-color * • border-left-color The default color is the currentColor of each of these values. * If you provide one value, it sets the color for the element. Two values set the horizontal and vertical values, respectively. Providing three values sets the top, vertical, and bottom values, in that order. Four values set all for sides: top, right, bottom, and left, in that order. */ - borderColor?: any; + borderColor?: CSSWideKeyword | any; /** * Specifies different corner clipping effects, such as scoop (inner curves), bevel (straight cuts) or notch (cut-off rectangles). Works along with border-radius to specify the size of each corner effect. */ - borderCornerShape?: any; + borderCornerShape?: CSSWideKeyword | any; /** * The property border-image-source is used to set the image to be used instead of the border style. If this is set to none the border-style is used instead. */ - borderImageSource?: any; + borderImageSource?: CSSWideKeyword | any; /** * The border-image-width CSS property defines the offset to use for dividing the border image in nine parts, the top-left corner, central top edge, top-right-corner, central right edge, bottom-right corner, central bottom edge, bottom-left corner, and central right edge. They represent inward distance from the top, right, bottom, and left edges. */ - borderImageWidth?: any; + borderImageWidth?: CSSWideKeyword | any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's left border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the left border — border-left-width, border-left-style and border-left-color. */ - borderLeft?: any; + borderLeft?: CSSWideKeyword | any; /** * The CSS border-left-color property sets the color of an element's left border. This page explains the border-left-color value, but often you will find it more convenient to fix the border's left color as part of a shorthand set, either border-left or border-color. * Colors can be defined several ways. For more information, see Usage. */ - borderLeftColor?: any; + borderLeftColor?: CSSWideKeyword | any; /** * Sets the style of an element's left border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ - borderLeftStyle?: any; + borderLeftStyle?: CSSWideKeyword | any; /** * Sets the width of an element's left border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ - borderLeftWidth?: any; + borderLeftWidth?: CSSWideKeyword | any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's right border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the right border — border-right-width, border-right-style and border-right-color. */ - borderRight?: any; + borderRight?: CSSWideKeyword | any; /** * Sets the color of an element's right border. This page explains the border-right-color value, but often you will find it more convenient to fix the border's right color as part of a shorthand set, either border-right or border-color. * Colors can be defined several ways. For more information, see Usage. */ - borderRightColor?: any; + borderRightColor?: CSSWideKeyword | any; /** * Sets the style of an element's right border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ - borderRightStyle?: any; + borderRightStyle?: CSSWideKeyword | any; /** * Sets the width of an element's right border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ - borderRightWidth?: any; + borderRightWidth?: CSSWideKeyword | any; /** * Specifies the distance between the borders of adjacent cells. */ - borderSpacing?: any; + borderSpacing?: CSSWideKeyword | any; /** * Sets the style of an element's four borders. This property can have from one to four values. With only one value, the value will be applied to all four borders; otherwise, this works as a shorthand property for each of border-top-style, border-right-style, border-bottom-style, border-left-style, where each border style may be assigned a separate value. */ - borderStyle?: any; + borderStyle?: CSSWideKeyword | any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's top border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the top border — border-top-width, border-top-style and border-top-color. */ - borderTop?: any; + borderTop?: CSSWideKeyword | any; /** * Sets the color of an element's top border. This page explains the border-top-color value, but often you will find it more convenient to fix the border's top color as part of a shorthand set, either border-top or border-color. * Colors can be defined several ways. For more information, see Usage. */ - borderTopColor?: any; + borderTopColor?: CSSWideKeyword | any; /** * Sets the rounding of the top-left corner of the element. */ - borderTopLeftRadius?: any; + borderTopLeftRadius?: CSSWideKeyword | any; /** * Sets the rounding of the top-right corner of the element. */ - borderTopRightRadius?: any; + borderTopRightRadius?: CSSWideKeyword | any; /** * Sets the style of an element's top border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ - borderTopStyle?: any; + borderTopStyle?: CSSWideKeyword | any; /** * Sets the width of an element's top border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ - borderTopWidth?: any; + borderTopWidth?: CSSWideKeyword | any; /** * Sets the width of an element's four borders. This property can have from one to four values. This is a shorthand property for setting values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ - borderWidth?: any; + borderWidth?: CSSWideKeyword | any; /** * This property specifies how far an absolutely positioned box's bottom margin edge is offset above the bottom edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the bottom edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties). */ - bottom?: any; + bottom?: CSSWideKeyword | any; /** * Obsolete. */ - boxAlign?: any; + boxAlign?: CSSWideKeyword | any; /** * Breaks a box into fragments creating new borders, padding and repeating backgrounds or lets it stay as a continuous box on a page break, column break, or, for inline elements, at a line break. */ - boxDecorationBreak?: any; + boxDecorationBreak?: CSSWideKeyword | any; /** * Deprecated */ - boxDirection?: any; + boxDirection?: CSSWideKeyword | any; /** * Do not use. This property has been replaced by the flex-wrap property. * Gets or sets a value that specifies the direction to add successive rows or columns when the value of box-lines is set to multiple. */ - boxLineProgression?: any; + boxLineProgression?: CSSWideKeyword | any; /** * Do not use. This property has been replaced by the flex-wrap property. * Gets or sets a value that specifies whether child elements wrap onto multiple lines or columns based on the space available in the object. */ - boxLines?: any; + boxLines?: CSSWideKeyword | any; /** * Do not use. This property has been replaced by flex-order. * Specifies the ordinal group that a child element of the object belongs to. This ordinal value identifies the display order (along the axis defined by the box-orient property) for the group. */ - boxOrdinalGroup?: any; + boxOrdinalGroup?: CSSWideKeyword | any; /** * Deprecated. */ - boxFlex?: number; + boxFlex?: CSSWideKeyword | number; /** * Deprecated. */ - boxFlexGroup?: number; + boxFlexGroup?: CSSWideKeyword | number; /** * The CSS break-after property allows you to force a break on multi-column layouts. More specifically, it allows you to force a break after an element. It allows you to determine if a break should occur, and what type of break it should be. The break-after CSS property describes how the page, column or region break behaves after the generated box. If there is no generated box, the property is ignored. */ - breakAfter?: any; + breakAfter?: CSSWideKeyword | any; /** * Control page/column/region breaks that fall above a block of content */ - breakBefore?: any; + breakBefore?: CSSWideKeyword | any; /** * Control page/column/region breaks that fall within a block of content */ - breakInside?: any; + breakInside?: CSSWideKeyword | any; /** * The clear CSS property specifies if an element can be positioned next to or must be positioned below the floating elements that precede it in the markup. */ - clear?: any; + clear?: CSSWideKeyword | any; /** * Deprecated; see clip-path. * Lets you specify the dimensions of an absolutely positioned element that should be visible, and the element is clipped into this shape, and displayed. */ - clip?: any; + clip?: CSSWideKeyword | any; /** * Clipping crops an graphic, so that only a portion of the graphic is rendered, or filled. This clip-rule property, when used with the clip-path property, defines which clip rule, or algorithm, to use when filling the different parts of a graphics. */ - clipRule?: any; + clipRule?: CSSWideKeyword | any; /** * The color property sets the color of an element's foreground content (usually text), accepting any standard CSS color from keywords and hex values to RGB(a) and HSL(a). */ - color?: any; + color?: CSSWideKeyword | any; /** * Describes the number of columns of the element. + * See CSS 3 column-count property https://www.w3.org/TR/css3-multicol/#cc */ - columnCount?: number; + columnCount?: CSSWideKeyword | number | "auto"; /** * Specifies how to fill columns (balanced or sequential). */ - columnFill?: any; + columnFill?: CSSWideKeyword | any; /** * The column-gap property controls the width of the gap between columns in multi-column elements. */ - columnGap?: any; + columnGap?: CSSWideKeyword | any; /** * Sets the width, style, and color of the rule between columns. */ - columnRule?: any; + columnRule?: CSSWideKeyword | any; /** * Specifies the color of the rule between columns. */ - columnRuleColor?: any; + columnRuleColor?: CSSWideKeyword | any; /** * Specifies the width of the rule between columns. */ - columnRuleWidth?: any; + columnRuleWidth?: CSSWideKeyword | any; /** * The column-span CSS property makes it possible for an element to span across all columns when its value is set to all. An element that spans more than one column is called a spanning element. */ - columnSpan?: any; + columnSpan?: CSSWideKeyword | any; /** * Specifies the width of columns in multi-column elements. */ - columnWidth?: any; + columnWidth?: CSSWideKeyword | any; /** * This property is a shorthand property for setting column-width and/or column-count. */ - columns?: any; + columns?: CSSWideKeyword | any; /** * The counter-increment property accepts one or more names of counters (identifiers), each one optionally followed by an integer which specifies the value by which the counter should be incremented (e.g. if the value is 2, the counter increases by 2 each time it is invoked). */ - counterIncrement?: any; + counterIncrement?: CSSWideKeyword | any; /** * The counter-reset property contains a list of one or more names of counters, each one optionally followed by an integer (otherwise, the integer defaults to 0.) Each time the given element is invoked, the counters specified by the property are set to the given integer. */ - counterReset?: any; + counterReset?: CSSWideKeyword | any; /** * The cue property specifies sound files (known as an "auditory icon") to be played by speech media agents before and after presenting an element's content; if only one file is specified, it is played both before and after. The volume at which the file(s) should be played, relative to the volume of the main element, may also be specified. The icon files may also be set separately with the cue-before and cue-after properties. */ - cue?: any; + cue?: CSSWideKeyword | any; /** * The cue-after property specifies a sound file (known as an "auditory icon") to be played by speech media agents after presenting an element's content; the volume at which the file should be played may also be specified. The shorthand property cue sets cue sounds for both before and after the element is presented. */ - cueAfter?: any; + cueAfter?: CSSWideKeyword | any; /** * Specifies the mouse cursor displayed when the mouse pointer is over an element. */ - cursor?: any; + cursor?: CSSWideKeyword | any; /** * The direction CSS property specifies the text direction/writing direction. The rtl is used for Hebrew or Arabic text, the ltr is for other languages. */ - direction?: any; + direction?: CSSWideKeyword | any; /** * This property specifies the type of rendering box used for an element. It is a shorthand property for many other display properties. */ - display?: any; + display?: CSSWideKeyword | any; /** * The ‘fill’ property paints the interior of the given graphical element. The area to be painted consists of any areas inside the outline of the shape. To determine the inside of the shape, all subpaths are considered, and the interior is determined according to the rules associated with the current value of the ‘fill-rule’ property. The zero-width geometric outline of a shape is included in the area to be painted. */ - fill?: any; + fill?: CSSWideKeyword | any; /** * SVG: Specifies the opacity of the color or the content the current object is filled with. + * See SVG 1.1 https://www.w3.org/TR/SVG/painting.html#FillOpacityProperty */ - fillOpacity?: number; + fillOpacity?: CSSWideKeyword | number; /** * The ‘fill-rule’ property indicates the algorithm which is to be used to determine what parts of the canvas are included inside the shape. For a simple, non-intersecting path, it is intuitively clear what region lies "inside"; however, for a more complex path, such as a path that intersects itself or where one subpath encloses another, the interpretation of "inside" is not so obvious. * The ‘fill-rule’ property provides two options for how the inside of a shape is determined: */ - fillRule?: any; + fillRule?: CSSWideKeyword | any; /** * Applies various image processing effects. This property is largely unsupported. See Compatibility section for more information. */ - filter?: any; + filter?: CSSWideKeyword | any; /** * Shorthand for `flex-grow`, `flex-shrink`, and `flex-basis`. */ - flex?: number | string; + flex?: CSSWideKeyword | number | string; /** * Obsolete, do not use. This property has been renamed to align-items. * Specifies the alignment (perpendicular to the layout axis defined by the flex-direction property) of child elements of the object. */ - flexAlign?: any; + flexAlign?: CSSWideKeyword | any; /** * The flex-basis CSS property describes the initial main size of the flex item before any free space is distributed according to the flex factors described in the flex property (flex-grow and flex-shrink). */ - flexBasis?: any; + flexBasis?: CSSWideKeyword | any; /** * The flex-direction CSS property describes how flex items are placed in the flex container, by setting the direction of the flex container's main axis. */ - flexDirection?: any; + flexDirection?: CSSWideKeyword | any; /** * The flex-flow CSS property defines the flex container's main and cross axis. It is a shorthand property for the flex-direction and flex-wrap properties. */ - flexFlow?: any; + flexFlow?: CSSWideKeyword | any; /** * Specifies the flex grow factor of a flex item. + * See CSS flex-grow property https://drafts.csswg.org/css-flexbox-1/#flex-grow-property */ - flexGrow?: number; + flexGrow?: CSSWideKeyword | number; /** * Do not use. This property has been renamed to align-self * Specifies the alignment (perpendicular to the layout axis defined by flex-direction) of child elements of the object. */ - flexItemAlign?: any; + flexItemAlign?: CSSWideKeyword | any; /** * Do not use. This property has been renamed to align-content. * Specifies how a flexbox's lines align within the flexbox when there is extra space along the axis that is perpendicular to the axis defined by the flex-direction property. */ - flexLinePack?: any; + flexLinePack?: CSSWideKeyword | any; /** * Gets or sets a value that specifies the ordinal group that a flexbox element belongs to. This ordinal value identifies the display order for the group. */ - flexOrder?: any; + flexOrder?: CSSWideKeyword | any; /** * Specifies the flex shrink factor of a flex item. + * See CSS flex-shrink property https://drafts.csswg.org/css-flexbox-1/#flex-shrink-property */ - flexShrink?: number; + flexShrink?: CSSWideKeyword | number; /** * Elements which have the style float are floated horizontally. These elements can move as far to the left or right of the containing element. All elements after the floating element will flow around it, but elements before the floating element are not impacted. If several floating elements are placed after each other, they will float next to each other as long as there is room. */ - float?: any; + float?: CSSWideKeyword | any; /** * Flows content from a named flow (specified by a corresponding flow-into) through selected elements to form a dynamic chain of layout regions. */ - flowFrom?: any; + flowFrom?: CSSWideKeyword | any; /** * The font property is shorthand that allows you to do one of two things: you can either set up six of the most mature font properties in one line, or you can set one of a choice of keywords to adopt a system font setting. */ - font?: any; + font?: CSSWideKeyword | any; /** * The font-family property allows one or more font family names and/or generic family names to be specified for usage on the selected element(s)' text. The browser then goes through the list; for each character in the selection it applies the first font family that has an available glyph for that character. */ - fontFamily?: any; + fontFamily?: CSSWideKeyword | any; /** * The font-kerning property allows contextual adjustment of inter-glyph spacing, i.e. the spaces between the characters in text. This property controls metric kerning - that utilizes adjustment data contained in the font. Optical Kerning is not supported as yet. */ - fontKerning?: any; + fontKerning?: CSSWideKeyword | any; /** * Specifies the size of the font. Used to compute em and ex units. + * See CSS 3 font-size property https://www.w3.org/TR/css-fonts-3/#propdef-font-size */ - fontSize?: number | string; + fontSize?: CSSWideKeyword | + "xx-small" | "x-small" | "small" | "medium" | "large" | "x-large" | "xx-large" | + "larger" | "smaller" | + CSSLength | CSSPercentage; /** * The font-size-adjust property adjusts the font-size of the fallback fonts defined with font-family, so that the x-height is the same no matter what font is used. This preserves the readability of the text when fallback happens. + * See CSS 3 font-size-adjust property https://www.w3.org/TR/css-fonts-3/#propdef-font-size-adjust */ - fontSizeAdjust?: any; + fontSizeAdjust?: CSSWideKeyword | "none" | number; /** * Allows you to expand or condense the widths for a normal, condensed, or expanded font face. + * See CSS 3 font-stretch property https://drafts.csswg.org/css-fonts-3/#propdef-font-stretch */ - fontStretch?: any; + fontStretch?: CSSWideKeyword | + "normal" | "ultra-condensed" | "extra-condensed" | "condensed" | "semi-condensed" | + "semi-expanded" | "expanded" | "extra-expanded" | "ultra-expanded"; /** * The font-style property allows normal, italic, or oblique faces to be selected. Italic forms are generally cursive in nature while oblique faces are typically sloped versions of the regular face. Oblique faces can be simulated by artificially sloping the glyphs of the regular face. + * See CSS 3 font-style property https://www.w3.org/TR/css-fonts-3/#propdef-font-style */ - fontStyle?: any; + fontStyle?: CSSWideKeyword | "normal" | "italic" | "oblique"; /** * This value specifies whether the user agent is allowed to synthesize bold or oblique font faces when a font family lacks bold or italic faces. */ - fontSynthesis?: any; + fontSynthesis?: CSSWideKeyword | any; /** * The font-variant property enables you to select the small-caps font within a font family. */ - fontVariant?: any; + fontVariant?: CSSWideKeyword | any; /** * Fonts can provide alternate glyphs in addition to default glyph for a character. This property provides control over the selection of these alternate glyphs. */ - fontVariantAlternates?: any; + fontVariantAlternates?: CSSWideKeyword | any; /** * Specifies the weight or boldness of the font. + * See CSS 3 'font-weight' property https://www.w3.org/TR/css-fonts-3/#propdef-font-weight */ - fontWeight?: "normal" | "bold" | "lighter" | "bolder" | number; + fontWeight?: CSSWideKeyword | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; /** * Lays out one or more grid items bound by 4 grid lines. Shorthand for setting grid-column-start, grid-column-end, grid-row-start, and grid-row-end in a single declaration. */ - gridArea?: any; + gridArea?: CSSWideKeyword | any; /** * Controls a grid item's placement in a grid area, particularly grid position and a grid span. Shorthand for setting grid-column-start and grid-column-end in a single declaration. */ - gridColumn?: any; + gridColumn?: CSSWideKeyword | any; /** * Controls a grid item's placement in a grid area as well as grid position and a grid span. The grid-column-end property (with grid-row-start, grid-row-end, and grid-column-start) determines a grid item's placement by specifying the grid lines of a grid item's grid area. */ - gridColumnEnd?: any; + gridColumnEnd?: CSSWideKeyword | any; /** * Determines a grid item's placement by specifying the starting grid lines of a grid item's grid area . A grid item's placement in a grid area consists of a grid position and a grid span. See also ( grid-row-start, grid-row-end, and grid-column-end) */ - gridColumnStart?: any; + gridColumnStart?: CSSWideKeyword | any; /** * Gets or sets a value that indicates which row an element within a Grid should appear in. Shorthand for setting grid-row-start and grid-row-end in a single declaration. */ - gridRow?: any; + gridRow?: CSSWideKeyword | any; /** * Determines a grid item’s placement by specifying the block-end. A grid item's placement in a grid area consists of a grid position and a grid span. The grid-row-end property (with grid-row-start, grid-column-start, and grid-column-end) determines a grid item's placement by specifying the grid lines of a grid item's grid area. */ - gridRowEnd?: any; + gridRowEnd?: CSSWideKeyword | any; /** * Specifies a row position based upon an integer location, string value, or desired row size. * css/properties/grid-row is used as short-hand for grid-row-position and grid-row-position */ - gridRowPosition?: any; + gridRowPosition?: CSSWideKeyword | any; - gridRowSpan?: any; + gridRowSpan?: CSSWideKeyword | any; /** * Specifies named grid areas which are not associated with any particular grid item, but can be referenced from the grid-placement properties. The syntax of the grid-template-areas property also provides a visualization of the structure of the grid, making the overall layout of the grid container easier to understand. */ - gridTemplateAreas?: any; + gridTemplateAreas?: CSSWideKeyword | any; /** * Specifies (with grid-template-rows) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. */ - gridTemplateColumns?: any; + gridTemplateColumns?: CSSWideKeyword | any; /** * Specifies (with grid-template-columns) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. */ - gridTemplateRows?: any; + gridTemplateRows?: CSSWideKeyword | any; /** * Sets the height of an element. The content area of the element height does not include the padding, border, and margin of the element. */ - height?: any; + height?: CSSWideKeyword | any; /** * Specifies the minimum number of characters in a hyphenated word */ - hyphenateLimitChars?: any; + hyphenateLimitChars?: CSSWideKeyword | any; /** * Indicates the maximum number of successive hyphenated lines in an element. The ‘no-limit’ value means that there is no limit. */ - hyphenateLimitLines?: any; + hyphenateLimitLines?: CSSWideKeyword | any; /** * Specifies the maximum amount of trailing whitespace (before justification) that may be left in a line before hyphenation is triggered to pull part of a word from the next line back up into the current one. */ - hyphenateLimitZone?: any; + hyphenateLimitZone?: CSSWideKeyword | any; /** * Specifies whether or not words in a sentence can be split by the use of a manual or automatic hyphenation mechanism. */ - hyphens?: any; + hyphens?: CSSWideKeyword | any; - imeMode?: any; + imeMode?: CSSWideKeyword | any; /** * Defines how the browser distributes space between and around flex items * along the main-axis of their container. + * See CSS justify-content property https://www.w3.org/TR/css-flexbox-1/#justify-content-property */ - justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; + justifyContent?: CSSWideKeyword | "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; - layoutGrid?: any; + layoutGrid?: CSSWideKeyword | any; - layoutGridChar?: any; + layoutGridChar?: CSSWideKeyword | any; - layoutGridLine?: any; + layoutGridLine?: CSSWideKeyword | any; - layoutGridMode?: any; + layoutGridMode?: CSSWideKeyword | any; - layoutGridType?: any; + layoutGridType?: CSSWideKeyword | any; /** * Sets the left edge of an element */ - left?: any; + left?: CSSWideKeyword | any; /** * The letter-spacing CSS property specifies the spacing behavior between text characters. */ - letterSpacing?: any; + letterSpacing?: CSSWideKeyword | any; /** * Deprecated. Gets or sets line-breaking rules for text in selected languages such as Japanese, Chinese, and Korean. */ - lineBreak?: any; + lineBreak?: CSSWideKeyword | any; - lineClamp?: number; + lineClamp?: CSSWideKeyword | number; /** * Specifies the height of an inline block level element. + * See CSS 2.1 line-height property https://www.w3.org/TR/CSS21/visudet.html#propdef-line-height */ - lineHeight?: number | string; + lineHeight?: CSSWideKeyword | "normal" | number | CSSLength | CSSPercentage; /** * Shorthand property that sets the list-style-type, list-style-position and list-style-image properties in one declaration. */ - listStyle?: any; + listStyle?: CSSWideKeyword | any; /** * This property sets the image that will be used as the list item marker. When the image is available, it will replace the marker set with the 'list-style-type' marker. That also means that if the image is not available, it will show the style specified by list-style-property */ - listStyleImage?: any; + listStyleImage?: CSSWideKeyword | any; /** * Specifies if the list-item markers should appear inside or outside the content flow. */ - listStylePosition?: any; + listStylePosition?: CSSWideKeyword | any; /** * Specifies the type of list-item marker in a list. */ - listStyleType?: any; + listStyleType?: CSSWideKeyword | any; /** * The margin property is shorthand to allow you to set all four margins of an element at once. Its equivalent longhand properties are margin-top, margin-right, margin-bottom and margin-left. Negative values are also allowed. */ - margin?: any; + margin?: CSSWideKeyword | any; /** * margin-bottom sets the bottom margin of an element. */ - marginBottom?: any; + marginBottom?: CSSWideKeyword | any; /** * margin-left sets the left margin of an element. */ - marginLeft?: any; + marginLeft?: CSSWideKeyword | any; /** * margin-right sets the right margin of an element. */ - marginRight?: any; + marginRight?: CSSWideKeyword | any; /** * margin-top sets the top margin of an element. */ - marginTop?: any; + marginTop?: CSSWideKeyword | any; /** * The marquee-direction determines the initial direction in which the marquee content moves. */ - marqueeDirection?: any; + marqueeDirection?: CSSWideKeyword | any; /** * The 'marquee-style' property determines a marquee's scrolling behavior. */ - marqueeStyle?: any; + marqueeStyle?: CSSWideKeyword | any; /** * This property is shorthand for setting mask-image, mask-mode, mask-repeat, mask-position, mask-clip, mask-origin, mask-composite and mask-size. Omitted values are set to their original properties' initial values. */ - mask?: any; + mask?: CSSWideKeyword | any; /** * This property is shorthand for setting mask-border-source, mask-border-slice, mask-border-width, mask-border-outset, and mask-border-repeat. Omitted values are set to their original properties' initial values. */ - maskBorder?: any; + maskBorder?: CSSWideKeyword | any; /** * This property specifies how the images for the sides and the middle part of the mask image are scaled and tiled. The first keyword applies to the horizontal sides, the second one applies to the vertical ones. If the second keyword is absent, it is assumed to be the same as the first, similar to the CSS border-image-repeat property. */ - maskBorderRepeat?: any; + maskBorderRepeat?: CSSWideKeyword | any; /** * This property specifies inward offsets from the top, right, bottom, and left edges of the mask image, dividing it into nine regions: four corners, four edges, and a middle. The middle image part is discarded and treated as fully transparent black unless the fill keyword is present. The four values set the top, right, bottom and left offsets in that order, similar to the CSS border-image-slice property. */ - maskBorderSlice?: any; + maskBorderSlice?: CSSWideKeyword | any; /** * Specifies an image to be used as a mask. An image that is empty, fails to download, is non-existent, or cannot be displayed is ignored and does not mask the element. */ - maskBorderSource?: any; + maskBorderSource?: CSSWideKeyword | any; /** * This property sets the width of the mask box image, similar to the CSS border-image-width property. */ - maskBorderWidth?: any; + maskBorderWidth?: CSSWideKeyword | any; /** * Determines the mask painting area, which defines the area that is affected by the mask. The painted content of an element may be restricted to this area. */ - maskClip?: any; + maskClip?: CSSWideKeyword | any; /** * For elements rendered as a single box, specifies the mask positioning area. For elements rendered as multiple boxes (e.g., inline boxes on several lines, boxes on several pages) specifies which boxes box-decoration-break operates on to determine the mask positioning area(s). */ - maskOrigin?: any; + maskOrigin?: CSSWideKeyword | any; /** * This property must not be used. It is no longer included in any standard or standard track specification, nor is it implemented in any browser. It is only used when the text-align-last property is set to size. It controls allowed adjustments of font-size to fit line content. */ - maxFontSize?: any; + maxFontSize?: CSSWideKeyword | any; /** * Sets the maximum height for an element. It prevents the height of the element to exceed the specified value. If min-height is specified and is greater than max-height, max-height is overridden. */ - maxHeight?: any; + maxHeight?: CSSWideKeyword | any; /** * Sets the maximum width for an element. It limits the width property to be larger than the value specified in max-width. */ - maxWidth?: any; + maxWidth?: CSSWideKeyword | any; /** * Sets the minimum height for an element. It prevents the height of the element to be smaller than the specified value. The value of min-height overrides both max-height and height. */ - minHeight?: any; + minHeight?: CSSWideKeyword | any; /** * Sets the minimum width of an element. It limits the width property to be not smaller than the value specified in min-width. */ - minWidth?: any; + minWidth?: CSSWideKeyword | any; /** * Specifies the transparency of an element. + * See CSS 3 opacity property https://drafts.csswg.org/css-color-3/#opacity */ - opacity?: number; + opacity?: CSSWideKeyword | number; /** * Specifies the order used to lay out flex items in their flex container. * Elements are laid out in the ascending order of the order value. + * See CSS order property https://drafts.csswg.org/css-flexbox-1/#order-property */ - order?: number; + order?: CSSWideKeyword | number; /** * In paged media, this property defines the minimum number of lines in * a block container that must be left at the bottom of the page. + * See CSS 3 orphans, widows properties https://drafts.csswg.org/css-break-3/#widows-orphans */ - orphans?: number; + orphans?: CSSWideKeyword | number; /** * The CSS outline property is a shorthand property for setting one or more of the individual outline properties outline-style, outline-width and outline-color in a single rule. In most cases the use of this shortcut is preferable and more convenient. - * Outlines differ from borders in the following ways: • Outlines do not take up space, they are drawn above the content. + * Outlines differ from borders in the following ways: + * • Outlines do not take up space, they are drawn above the content. * • Outlines may be non-rectangular. They are rectangular in Gecko/Firefox. Internet Explorer attempts to place the smallest contiguous outline around all elements or shapes that are indicated to have an outline. Opera draws a non-rectangular shape around a construct. */ - outline?: any; + outline?: CSSWideKeyword | any; /** * The outline-color property sets the color of the outline of an element. An outline is a line that is drawn around elements, outside the border edge, to make the element stand out. */ - outlineColor?: any; + outlineColor?: CSSWideKeyword | any; /** * The outline-offset property offsets the outline and draw it beyond the border edge. */ - outlineOffset?: any; + outlineOffset?: CSSWideKeyword | any; /** * The overflow property controls how extra content exceeding the bounding box of an element is rendered. It can be used in conjunction with an element that has a fixed width and height, to eliminate text-induced page distortion. */ - overflow?: any; + overflow?: CSSWideKeyword | any; /** * Specifies the preferred scrolling methods for elements that overflow. */ - overflowStyle?: any; + overflowStyle?: CSSWideKeyword | any; /** * Controls how extra content exceeding the x-axis of the bounding box of an element is rendered. */ - overflowX?: any; + overflowX?: CSSWideKeyword | any; /** * Controls how extra content exceeding the y-axis of the bounding box of an element is rendered. */ - overflowY?: any; + overflowY?: CSSWideKeyword | any; /** * The padding optional CSS property sets the required padding space on one to four sides of an element. The padding area is the space between an element and its border. Negative values are not allowed but decimal values are permitted. The element size is treated as fixed, and the content of the element shifts toward the center as padding is increased. * The padding property is a shorthand to avoid setting each side separately (padding-top, padding-right, padding-bottom, padding-left). */ - padding?: any; + padding?: CSSWideKeyword | any; /** * The padding-bottom CSS property of an element sets the padding space required on the bottom of an element. The padding area is the space between the content of the element and its border. Contrary to margin-bottom values, negative values of padding-bottom are invalid. */ - paddingBottom?: any; + paddingBottom?: CSSWideKeyword | any; /** * The padding-left CSS property of an element sets the padding space required on the left side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-left values, negative values of padding-left are invalid. */ - paddingLeft?: any; + paddingLeft?: CSSWideKeyword | any; /** * The padding-right CSS property of an element sets the padding space required on the right side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-right values, negative values of padding-right are invalid. */ - paddingRight?: any; + paddingRight?: CSSWideKeyword | any; /** * The padding-top CSS property of an element sets the padding space required on the top of an element. The padding area is the space between the content of the element and its border. Contrary to margin-top values, negative values of padding-top are invalid. */ - paddingTop?: any; + paddingTop?: CSSWideKeyword | any; /** * The page-break-after property is supported in all major browsers. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ - pageBreakAfter?: any; + pageBreakAfter?: CSSWideKeyword | any; /** * The page-break-before property sets the page-breaking behavior before an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ - pageBreakBefore?: any; + pageBreakBefore?: CSSWideKeyword | any; /** * Sets the page-breaking behavior inside an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ - pageBreakInside?: any; + pageBreakInside?: CSSWideKeyword | any; /** * The pause property determines how long a speech media agent should pause before and after presenting an element. It is a shorthand for the pause-before and pause-after properties. */ - pause?: any; + pause?: CSSWideKeyword | any; /** * The pause-after property determines how long a speech media agent should pause after presenting an element. It may be replaced by the shorthand property pause, which sets pause time before and after. */ - pauseAfter?: any; + pauseAfter?: CSSWideKeyword | any; /** * The pause-before property determines how long a speech media agent should pause before presenting an element. It may be replaced by the shorthand property pause, which sets pause time before and after. */ - pauseBefore?: any; + pauseBefore?: CSSWideKeyword | any; /** * The perspective property defines how far an element is placed from the view on the z-axis, from the screen to the viewer. * Perspective defines how an object is viewed. In graphic arts, perspective is the representation on a flat surface of what the viewer's eye would see in a 3D space. (See Wikipedia for more information about graphical perspective and for related illustrations.) * The illusion of perspective on a flat surface, such as a computer screen, is created by projecting points on the flat surface as they would appear if the flat surface were a window through which the viewer was looking at the object. In discussion of virtual environments, this flat surface is called a projection plane. */ - perspective?: any; + perspective?: CSSWideKeyword | any; /** * The perspective-origin property establishes the origin for the perspective property. It effectively sets the X and Y position at which the viewer appears to be looking at the children of the element. * When used with perspective, perspective-origin changes the appearance of an object, as if a viewer were looking at it from a different origin. An object appears differently if a viewer is looking directly at it versus looking at it from below, above, or from the side. Thus, the perspective-origin is like a vanishing point. * The default value of perspective-origin is 50% 50%. This displays an object as if the viewer's eye were positioned directly at the center of the screen, both top-to-bottom and left-to-right. A value of 0% 0% changes the object as if the viewer was looking toward the top left angle. A value of 100% 100% changes the appearance as if viewed toward the bottom right angle. */ - perspectiveOrigin?: any; + perspectiveOrigin?: CSSWideKeyword | any; /** * The pointer-events property allows you to control whether an element can be the target for the pointing device (e.g, mouse, pen) events. */ - pointerEvents?: any; + pointerEvents?: CSSWideKeyword | any; /** * The position property controls the type of positioning used by an element within its parent elements. The effect of the position property depends on a lot of factors, for example the position property of parent elements. */ - position?: any; + position?: CSSWideKeyword | any; /** * Obsolete: unsupported. * This property determines whether or not a full-width punctuation mark character should be trimmed if it appears at the beginning of a line, so that its "ink" lines up with the first glyph in the line above and below. */ - punctuationTrim?: any; + punctuationTrim?: CSSWideKeyword | any; /** * Sets the type of quotation marks for embedded quotations. */ - quotes?: any; + quotes?: CSSWideKeyword | any; /** * Controls whether the last region in a chain displays additional 'overset' content according its default overflow property, or if it displays a fragment of content as if it were flowing into a subsequent region. */ - regionFragment?: any; + regionFragment?: CSSWideKeyword | any; /** * The rest-after property determines how long a speech media agent should pause after presenting an element's main content, before presenting that element's exit cue sound. It may be replaced by the shorthand property rest, which sets rest time before and after. */ - restAfter?: any; + restAfter?: CSSWideKeyword | any; /** * The rest-before property determines how long a speech media agent should pause after presenting an intro cue sound for an element, before presenting that element's main content. It may be replaced by the shorthand property rest, which sets rest time before and after. */ - restBefore?: any; + restBefore?: CSSWideKeyword | any; /** * Specifies the position an element in relation to the right side of the containing element. */ - right?: any; + right?: CSSWideKeyword | any; - rubyAlign?: any; + rubyAlign?: CSSWideKeyword | any; - rubyPosition?: any; + rubyPosition?: CSSWideKeyword | any; /** * Defines the alpha channel threshold used to extract a shape from an image. Can be thought of as a "minimum opacity" threshold; that is, a value of 0.5 means that the shape will enclose all the pixels that are more than 50% opaque. */ - shapeImageThreshold?: any; + shapeImageThreshold?: CSSWideKeyword | any; /** * A future level of CSS Shapes will define a shape-inside property, which will define a shape to wrap content within the element. See Editor's Draft and CSSWG wiki page on next-level plans */ - shapeInside?: any; + shapeInside?: CSSWideKeyword | any; /** * Adds a margin to a shape-outside. In effect, defines a new shape that is the smallest contour around all the points that are the shape-margin distance outward perpendicular to each point on the underlying shape. For points where a perpendicular direction is not defined (e.g., a triangle corner), takes all points on a circle centered at the point and with a radius of the shape-margin distance. This property accepts only non-negative values. */ - shapeMargin?: any; + shapeMargin?: CSSWideKeyword | any; /** * Declares a shape around which text should be wrapped, with possible modifications from the shape-margin property. The shape defined by shape-outside and shape-margin changes the geometry of a float element's float area. */ - shapeOutside?: any; + shapeOutside?: CSSWideKeyword | any; /** * The speak property determines whether or not a speech synthesizer will read aloud the contents of an element. */ - speak?: any; + speak?: CSSWideKeyword | any; /** * The speak-as property determines how the speech synthesizer interprets the content: words as whole words or as a sequence of letters, numbers as a numerical value or a sequence of digits, punctuation as pauses in speech or named punctuation characters. */ - speakAs?: any; + speakAs?: CSSWideKeyword | any; /** * SVG: Specifies the opacity of the outline on the current object. + * See SVG 1.1 https://www.w3.org/TR/SVG/painting.html#StrokeOpacityProperty */ - strokeOpacity?: number; + strokeOpacity?: CSSWideKeyword | number; /** * SVG: Specifies the width of the outline on the current object. + * See SVG 1.1 https://www.w3.org/TR/SVG/painting.html#StrokeWidthProperty */ - strokeWidth?: number; + strokeWidth?: CSSWideKeyword | CSSPercentage | CSSLength; /** * The tab-size CSS property is used to customise the width of a tab (U+0009) character. */ - tabSize?: any; + tabSize?: CSSWideKeyword | any; /** * The 'table-layout' property controls the algorithm used to lay out the table cells, rows, and columns. */ - tableLayout?: any; + tableLayout?: CSSWideKeyword | any; /** * The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content. */ - textAlign?: any; + textAlign?: CSSWideKeyword | any; /** * The text-align-last CSS property describes how the last line of a block element or a line before line break is aligned in its parent block element. */ - textAlignLast?: any; + textAlignLast?: CSSWideKeyword | any; /** * The text-decoration CSS property is used to set the text formatting to underline, overline, line-through or blink. * underline and overline decorations are positioned under the text, line-through over it. */ - textDecoration?: any; + textDecoration?: CSSWideKeyword | any; /** * Sets the color of any text decoration, such as underlines, overlines, and strike throughs. */ - textDecorationColor?: any; + textDecorationColor?: CSSWideKeyword | any; /** * Sets what kind of line decorations are added to an element, such as underlines, overlines, etc. */ - textDecorationLine?: any; + textDecorationLine?: CSSWideKeyword | any; - textDecorationLineThrough?: any; + textDecorationLineThrough?: CSSWideKeyword | any; - textDecorationNone?: any; + textDecorationNone?: CSSWideKeyword | any; - textDecorationOverline?: any; + textDecorationOverline?: CSSWideKeyword | any; /** * Specifies what parts of an element’s content are skipped over when applying any text decoration. */ - textDecorationSkip?: any; + textDecorationSkip?: CSSWideKeyword | any; /** * This property specifies the style of the text decoration line drawn on the specified element. The intended meaning for the values are the same as those of the border-style-properties. */ - textDecorationStyle?: any; + textDecorationStyle?: CSSWideKeyword | any; - textDecorationUnderline?: any; + textDecorationUnderline?: CSSWideKeyword | any; /** * The text-emphasis property will apply special emphasis marks to the elements text. Slightly similar to the text-decoration property only that this property can have affect on the line-height. It also is noted that this is shorthand for text-emphasis-style and for text-emphasis-color. */ - textEmphasis?: any; + textEmphasis?: CSSWideKeyword | any; /** * The text-emphasis-color property specifies the foreground color of the emphasis marks. */ - textEmphasisColor?: any; + textEmphasisColor?: CSSWideKeyword | any; /** * The text-emphasis-style property applies special emphasis marks to an element's text. */ - textEmphasisStyle?: any; + textEmphasisStyle?: CSSWideKeyword | any; /** * This property helps determine an inline box's block-progression dimension, derived from the text-height and font-size properties for non-replaced elements, the height or the width for replaced elements, and the stacked block-progression dimension for inline-block elements. The block-progression dimension determines the position of the padding, border and margin for the element. */ - textHeight?: any; + textHeight?: CSSWideKeyword | any; /** * Specifies the amount of space horizontally that should be left on the first line of the text of an element. This horizontal spacing is at the beginning of the first line and is in respect to the left edge of the containing block box. */ - textIndent?: any; + textIndent?: CSSWideKeyword | any; - textJustifyTrim?: any; + textJustifyTrim?: CSSWideKeyword | any; - textKashidaSpace?: any; + textKashidaSpace?: CSSWideKeyword | any; /** * The text-line-through property is a shorthand property for text-line-through-style, text-line-through-color and text-line-through-mode. (Considered obsolete; use text-decoration instead.) */ - textLineThrough?: any; + textLineThrough?: CSSWideKeyword | any; /** * Specifies the line colors for the line-through text decoration. * (Considered obsolete; use text-decoration-color instead.) */ - textLineThroughColor?: any; + textLineThroughColor?: CSSWideKeyword | any; /** * Sets the mode for the line-through text decoration, determining whether the text decoration affects the space characters or not. * (Considered obsolete; use text-decoration-skip instead.) */ - textLineThroughMode?: any; + textLineThroughMode?: CSSWideKeyword | any; /** * Specifies the line style for line-through text decoration. * (Considered obsolete; use text-decoration-style instead.) */ - textLineThroughStyle?: any; + textLineThroughStyle?: CSSWideKeyword | any; /** * Specifies the line width for the line-through text decoration. */ - textLineThroughWidth?: any; + textLineThroughWidth?: CSSWideKeyword | any; /** * The text-overflow shorthand CSS property determines how overflowed content that is not displayed is signaled to the users. It can be clipped, display an ellipsis ('…', U+2026 HORIZONTAL ELLIPSIS) or a Web author-defined string. It covers the two long-hand properties text-overflow-mode and text-overflow-ellipsis */ - textOverflow?: any; + textOverflow?: CSSWideKeyword | any; /** * The text-overline property is the shorthand for the text-overline-style, text-overline-width, text-overline-color, and text-overline-mode properties. */ - textOverline?: any; + textOverline?: CSSWideKeyword | any; /** * Specifies the line color for the overline text decoration. */ - textOverlineColor?: any; + textOverlineColor?: CSSWideKeyword | any; /** * Sets the mode for the overline text decoration, determining whether the text decoration affects the space characters or not. */ - textOverlineMode?: any; + textOverlineMode?: CSSWideKeyword | any; /** * Specifies the line style for overline text decoration. */ - textOverlineStyle?: any; + textOverlineStyle?: CSSWideKeyword | any; /** * Specifies the line width for the overline text decoration. */ - textOverlineWidth?: any; + textOverlineWidth?: CSSWideKeyword | any; /** * The text-rendering CSS property provides information to the browser about how to optimize when rendering text. Options are: legibility, speed or geometric precision. */ - textRendering?: any; + textRendering?: CSSWideKeyword | any; /** * Obsolete: unsupported. */ - textScript?: any; + textScript?: CSSWideKeyword | any; /** * The CSS text-shadow property applies one or more drop shadows to the text and of an element. Each shadow is specified as an offset from the text, along with optional color and blur radius values. */ - textShadow?: any; + textShadow?: CSSWideKeyword | any; /** * This property transforms text for styling purposes. (It has no effect on the underlying content.) */ - textTransform?: any; + textTransform?: CSSWideKeyword | any; /** * Unsupported. * This property will add a underline position value to the element that has an underline defined. */ - textUnderlinePosition?: any; + textUnderlinePosition?: CSSWideKeyword | any; /** * After review this should be replaced by text-decoration should it not? * This property will set the underline style for text with a line value for underline, overline, and line-through. */ - textUnderlineStyle?: any; + textUnderlineStyle?: CSSWideKeyword | any; /** * This property specifies how far an absolutely positioned box's top margin edge is offset below the top edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the top edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties). */ - top?: any; + top?: CSSWideKeyword | any; /** * Determines whether touch input may trigger default behavior supplied by the user agent, such as panning or zooming. */ - touchAction?: any; + touchAction?: CSSWideKeyword | any; /** * CSS transforms allow elements styled with CSS to be transformed in two-dimensional or three-dimensional space. Using this property, elements can be translated, rotated, scaled, and skewed. The value list may consist of 2D and/or 3D transform values. */ - transform?: any; + transform?: CSSWideKeyword | any; /** * This property defines the origin of the transformation axes relative to the element to which the transformation is applied. */ - transformOrigin?: any; + transformOrigin?: CSSWideKeyword | any; /** * This property allows you to define the relative position of the origin of the transformation grid along the z-axis. */ - transformOriginZ?: any; + transformOriginZ?: CSSWideKeyword | any; /** * This property specifies how nested elements are rendered in 3D space relative to their parent. */ - transformStyle?: any; + transformStyle?: CSSWideKeyword | any; /** * The transition CSS property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay. It allows to define the transition between two states of an element. */ - transition?: any; + transition?: CSSWideKeyword | any; /** * Defines when the transition will start. A value of ‘0s’ means the transition will execute as soon as the property is changed. Otherwise, the value specifies an offset from the moment the property is changed, and the transition will delay execution by that offset. */ - transitionDelay?: any; + transitionDelay?: CSSWideKeyword | any; /** * The 'transition-duration' property specifies the length of time a transition animation takes to complete. */ - transitionDuration?: any; + transitionDuration?: CSSWideKeyword | any; /** * The 'transition-property' property specifies the name of the CSS property to which the transition is applied. */ - transitionProperty?: any; + transitionProperty?: CSSWideKeyword | any; /** * Sets the pace of action within a transition */ - transitionTimingFunction?: any; + transitionTimingFunction?: CSSWideKeyword | any; /** * The unicode-bidi CSS property specifies the level of embedding with respect to the bidirectional algorithm. */ - unicodeBidi?: any; + unicodeBidi?: CSSWideKeyword | any; /** * unicode-range allows you to set a specific range of characters to be downloaded from a font (embedded using @font-face) and made available for use on the current page. */ - unicodeRange?: any; + unicodeRange?: CSSWideKeyword | any; /** * This is for all the high level UX stuff. */ - userFocus?: any; + userFocus?: CSSWideKeyword | any; /** * For inputing user content */ - userInput?: any; + userInput?: CSSWideKeyword | any; /** * The vertical-align property controls how inline elements or text are vertically aligned compared to the baseline. If this property is used on table-cells it controls the vertical alignment of content of the table cell. */ - verticalAlign?: any; + verticalAlign?: CSSWideKeyword | any; /** * The visibility property specifies whether the boxes generated by an element are rendered. */ - visibility?: any; + visibility?: CSSWideKeyword | any; /** * The voice-balance property sets the apparent position (in stereo sound) of the synthesized voice for spoken media. */ - voiceBalance?: any; + voiceBalance?: CSSWideKeyword | any; /** * The voice-duration property allows the author to explicitly set the amount of time it should take a speech synthesizer to read an element's content, for example to allow the speech to be synchronized with other media. With a value of auto (the default) the length of time it takes to read the content is determined by the content itself and the voice-rate property. */ - voiceDuration?: any; + voiceDuration?: CSSWideKeyword | any; /** * The voice-family property sets the speaker's voice used by a speech media agent to read an element. The speaker may be specified as a named character (to match a voice option in the speech reading software) or as a generic description of the age and gender of the voice. Similar to the font-family property for visual media, a comma-separated list of fallback options may be given in case the speech reader does not recognize the character name or cannot synthesize the requested combination of generic properties. */ - voiceFamily?: any; + voiceFamily?: CSSWideKeyword | any; /** * The voice-pitch property sets pitch or tone (high or low) for the synthesized speech when reading an element; the pitch may be specified absolutely or relative to the normal pitch for the voice-family used to read the text. */ - voicePitch?: any; + voicePitch?: CSSWideKeyword | any; /** * The voice-range property determines how much variation in pitch or tone will be created by the speech synthesize when reading an element. Emphasized text, grammatical structures and punctuation may all be rendered as changes in pitch, this property determines how strong or obvious those changes are; large ranges are associated with enthusiastic or emotional speech, while small ranges are associated with flat or mechanical speech. */ - voiceRange?: any; + voiceRange?: CSSWideKeyword | any; /** * The voice-rate property sets the speed at which the voice synthesized by a speech media agent will read content. */ - voiceRate?: any; + voiceRate?: CSSWideKeyword | any; /** * The voice-stress property sets the level of vocal emphasis to be used for synthesized speech reading the element. */ - voiceStress?: any; + voiceStress?: CSSWideKeyword | any; /** * The voice-volume property sets the volume for spoken content in speech media. It replaces the deprecated volume property. */ - voiceVolume?: any; + voiceVolume?: CSSWideKeyword | any; /** * The white-space property controls whether and how white space inside the element is collapsed, and whether lines may wrap at unforced "soft wrap" opportunities. */ - whiteSpace?: any; + whiteSpace?: CSSWideKeyword | any; /** * Obsolete: unsupported. */ - whiteSpaceTreatment?: any; + whiteSpaceTreatment?: CSSWideKeyword | any; /** * In paged media, this property defines the mimimum number of lines * that must be left at the top of the second page. + * See CSS 3 orphans, widows properties https://drafts.csswg.org/css-break-3/#widows-orphans */ - widows?: number; + widows?: CSSWideKeyword | number; /** * Specifies the width of the content area of an element. The content area of the element width does not include the padding, border, and margin of the element. */ - width?: any; + width?: CSSWideKeyword | any; /** * The word-break property is often used when there is long generated content that is strung together without and spaces or hyphens to beak apart. A common case of this is when there is a long URL that does not have any hyphens. This case could potentially cause the breaking of the layout as it could extend past the parent element. */ - wordBreak?: any; + wordBreak?: CSSWideKeyword | any; /** * The word-spacing CSS property specifies the spacing behavior between "words". */ - wordSpacing?: any; + wordSpacing?: CSSWideKeyword | any; /** * An alias of css/properties/overflow-wrap, word-wrap defines whether to break words when the content exceeds the boundaries of its container. */ - wordWrap?: any; + wordWrap?: CSSWideKeyword | any; /** * Specifies how exclusions affect inline content within block-level elements. Elements lay out their inline content in their content area but wrap around exclusion areas. */ - wrapFlow?: any; + wrapFlow?: CSSWideKeyword | any; /** * Set the value that is used to offset the inner wrap shape from other shapes. Inline content that intersects a shape with this property will be pushed by this shape's margin. */ - wrapMargin?: any; + wrapMargin?: CSSWideKeyword | any; /** * Obsolete and unsupported. Do not use. * This CSS property controls the text when it reaches the end of the block in which it is enclosed. */ - wrapOption?: any; + wrapOption?: CSSWideKeyword | any; /** * writing-mode specifies if lines of text are laid out horizontally or vertically, and the direction which lines of text and blocks progress. */ - writingMode?: any; + writingMode?: CSSWideKeyword | any; /** * The z-index property specifies the z-order of an element and its descendants. * When elements overlap, z-order determines which one covers the other. + * See CSS 2 z-index property https://www.w3.org/TR/CSS2/visuren.html#z-index */ - zIndex?: "auto" | number; + zIndex?: CSSWideKeyword | "auto" | number; /** * Sets the initial zoom factor of a document defined by @viewport. + * See CSS zoom descriptor https://drafts.csswg.org/css-device-adapt/#zoom-desc */ - zoom?: "auto" | number; + zoom?: CSSWideKeyword | "auto" | number | CSSPercentage; [propertyName: string]: any; } @@ -2104,6 +2146,7 @@ declare namespace React { shape?: string; size?: number; sizes?: string; + slot?: string; span?: number; spellCheck?: boolean; src?: string; @@ -2149,6 +2192,10 @@ declare namespace React { unselectable?: boolean; } + interface ChangeTargetHTMLAttributes extends HTMLAttributes { + onChange?: ChangeEventHandler; + } + // 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 @@ -2322,7 +2369,7 @@ declare namespace React { speed?: number | string; spreadMethod?: string; startOffset?: number | string; - stdDeviation?: number | string + stdDeviation?: number | string; stemh?: number | string; stemv?: number | string; stitchTiles?: number | string; @@ -2459,7 +2506,7 @@ declare namespace React { i: HTMLFactory; iframe: HTMLFactory; img: HTMLFactory; - input: HTMLFactory; + input: ChangeTargetHTMLFactory; ins: HTMLFactory; kbd: HTMLFactory; keygen: HTMLFactory; @@ -2494,7 +2541,7 @@ declare namespace React { samp: HTMLFactory; script: HTMLFactory; section: HTMLFactory; - select: HTMLFactory; + select: ChangeTargetHTMLFactory; small: HTMLFactory; source: HTMLFactory; span: HTMLFactory; @@ -2506,7 +2553,7 @@ declare namespace React { table: HTMLFactory; tbody: HTMLFactory; td: HTMLFactory; - textarea: HTMLFactory; + textarea: ChangeTargetHTMLFactory; tfoot: HTMLFactory; th: HTMLFactory; thead: HTMLFactory; @@ -2522,6 +2569,7 @@ declare namespace React { // SVG svg: SVGFactory; + animate: SVGFactory; circle: SVGFactory; defs: SVGFactory; ellipse: SVGFactory; @@ -2684,7 +2732,7 @@ declare global { i: React.HTMLProps; iframe: React.HTMLProps; img: React.HTMLProps; - input: React.HTMLProps; + input: React.ChangeTargetHTMLProps; ins: React.HTMLProps; kbd: React.HTMLProps; keygen: React.HTMLProps; @@ -2720,7 +2768,7 @@ declare global { samp: React.HTMLProps; script: React.HTMLProps; section: React.HTMLProps; - select: React.HTMLProps; + select: React.ChangeTargetHTMLProps; small: React.HTMLProps; source: React.HTMLProps; span: React.HTMLProps; @@ -2732,7 +2780,7 @@ declare global { table: React.HTMLProps; tbody: React.HTMLProps; td: React.HTMLProps; - textarea: React.HTMLProps; + textarea: React.ChangeTargetHTMLProps; tfoot: React.HTMLProps; th: React.HTMLProps; thead: React.HTMLProps; @@ -2749,6 +2797,7 @@ declare global { // SVG svg: React.SVGProps; + animate: React.SVGProps; circle: React.SVGProps; clipPath: React.SVGProps; defs: React.SVGProps; diff --git a/react/test/cssProperties.tsx b/react/test/cssProperties.tsx new file mode 100644 index 0000000000..f037c43eb4 --- /dev/null +++ b/react/test/cssProperties.tsx @@ -0,0 +1,37 @@ +import * as React from 'react'; + +const initialStyle: React.CSSProperties = { fontWeight: 'initial' }; +const initialStyleTest =

; + +const backgroundAttachmentStyle: React.CSSProperties = { backgroundAttachment: 'fixed' }; +const backgroundAttachmentStyleTest =
; + +const columnCountStyle: React.CSSProperties = { columnCount: 'auto' }; +const columnCountStyleTest =
; + +const fontSizeAdjustStyle: React.CSSProperties = { fontSizeAdjust: 'none' }; +const fontSizeAdjustStyleTest =
; + +const fontStretchStyle: React.CSSProperties = { fontStretch: 'condensed' }; +const fontStretchStyleTest =
; + +const fontStyleStyle: React.CSSProperties = { fontStyle: 'italic' }; +const fontStyleStyleTest =
; + +const fontWeightStyle: React.CSSProperties = { fontWeight: 400 }; +const fontWeightStyleTest =
; + +const justifyContentStyle: React.CSSProperties = { justifyContent: 'space-around' }; +const justifyContentStyleTest =
; + + +// SVG specific style attribute declarations + +const fillOpacityStyle: React.CSSProperties = { fillOpacity: 0.3 }; +const fillOpacityStyleTest = ; + +const strokeOpacityStyle: React.CSSProperties = { strokeOpacity: 0.3 }; +const strokeOpacityStyleTest = ; + +const strokeWidthStyle: React.CSSProperties = { strokeWidth: '10px' }; +const strokeWidthStyleTest = ; diff --git a/react/test/index.ts b/react/test/index.ts index 0900926cf6..1bf6c8dcc2 100644 --- a/react/test/index.ts +++ b/react/test/index.ts @@ -317,6 +317,7 @@ var htmlAttr: React.HTMLProps = { children: children, className: "test-attr", style: divStyle, + slot: "HTMLComponent", onClick: (event: React.MouseEvent<{}>) => { event.preventDefault(); event.stopPropagation(); @@ -325,6 +326,9 @@ var htmlAttr: React.HTMLProps = { event.preventDefault(); event.stopPropagation(); }, + onAnimationStart: event => { + console.log(event.currentTarget.className); + }, dangerouslySetInnerHTML: { __html: "STRONG" } @@ -659,20 +663,6 @@ React.createFactory(TransitionGroup)({ component: "div" }); let newObjShallow = update(obj, { $merge: { b: 6, c: 7 } }); // => {a: 5, b: 6, c: 7} } -// -// React Component classes super spread arguments -// -------------------------------------------------------------------------- -class ConstructorSpreadArgsComponent extends React.Component<{}, {}> { - constructor(...args: any[]) { - super(...args); - } -} -class ConstructorSpreadArgsPureComponent extends React.PureComponent<{}, {}> { - constructor(...args: any[]) { - super(...args); - } -} - // // The SyntheticEvent.target.value should be accessible for onChange // -------------------------------------------------------------------------- @@ -688,3 +678,33 @@ class SyntheticEventTargetValue extends React.Component<{}, { value: string }> { }); } } + +React.DOM.input({ + onChange: event => { + // `event.target` is guaranteed to be HTMLInputElement + event.target.value; + } +}); + +// A ChangeEvent is a valid FormEvent (maintain compatibility with existing +// event handlers) + +type InputChangeEvent = React.ChangeEvent; +type InputFormEvent = React.FormEvent; +const changeEvent:InputChangeEvent = undefined as any; +const formEvent:InputFormEvent = changeEvent; + +// defaultProps should be optional of props +{ + interface ComponentProps { + prop1: string; + prop2: string; + prop3?: string; + } + class ComponentWithDefaultProps extends React.Component { + static defaultProps = { + prop3: "default value", + }; + } + const VariableWithAClass: React.ComponentClass = ComponentWithDefaultProps; +} diff --git a/react/test/tsx.tsx b/react/test/tsx.tsx index 0531cb52c0..540c712596 100644 --- a/react/test/tsx.tsx +++ b/react/test/tsx.tsx @@ -30,5 +30,6 @@ StatelessComponent2.defaultProps = { Hello, world! +
Hello again!
; diff --git a/react/tsconfig.json b/react/tsconfig.json index 18a4fb19fb..d2c4600811 100644 --- a/react/tsconfig.json +++ b/react/tsconfig.json @@ -2,7 +2,8 @@ "files": [ "index.d.ts", "test/index.ts", - "test/tsx.tsx" + "test/tsx.tsx", + "test/cssProperties.tsx" ], "compilerOptions": { "module": "commonjs", @@ -22,4 +23,4 @@ "forceConsistentCasingInFileNames": true, "jsx": "preserve" } -} \ No newline at end of file +} diff --git a/reactcss/index.d.ts b/reactcss/index.d.ts index 19faf7e9fa..2d571674f7 100644 --- a/reactcss/index.d.ts +++ b/reactcss/index.d.ts @@ -2,6 +2,7 @@ // Project: http://reactcss.com/ // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from "react" diff --git a/readline-sync/readline-sync-tests.ts b/readline-sync/readline-sync-tests.ts index 02c8d8e952..7800fda39a 100644 --- a/readline-sync/readline-sync-tests.ts +++ b/readline-sync/readline-sync-tests.ts @@ -1,16 +1,14 @@ - - import readlineSync = require('readline-sync'); -let result:string = readlineSync.question('Which program starts do you want? ', { +const result: string = readlineSync.question('Which program starts do you want? ', { defaultInput: 'firefox' }); -let result2:string = readlineSync.prompt({prompt: '$$'}); +const result2: string = readlineSync.prompt({prompt: '$$'}); -let result3:string = readlineSync.keyIn('Press a key', { limit: '$<1-5>' }); +const result3: string = readlineSync.keyIn('Press a key', { limit: '$<1-5>' }); -let result4:{} = readlineSync.setDefaultOptions({ +const result4: {} = readlineSync.setDefaultOptions({ prompt: '$$', hideEchoBack: true, mask: '*', @@ -18,12 +16,12 @@ let result4:{} = readlineSync.setDefaultOptions({ limitMessage: 'Limit reached', defaultInput: 'English', trueValue: 2, - falseValue: (value:string) => { return true; }, + falseValue: (value: string) => true, caseSensitive: true, keepWhitespace: true, encoding: 'utf-8', bufferSize: 12, - print: (display:string, encoding:string) => { console.log(display)}, + print: (display: string, encoding: string) => { console.log(display); }, history: false, cd: true, charlist: 'abc', @@ -34,26 +32,26 @@ let result4:{} = readlineSync.setDefaultOptions({ exists: false, isFile: true, isDirectory: false, - validate: (path:string) => { return (path === '/usr/local/bin'); }, + validate: (path: string) => path === '/usr/local/bin', create: true, guide: false, }); -let result5:string = readlineSync.questionEMail('Enter email'); +const result5: string = readlineSync.questionEMail('Enter email'); -let result6:string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); +const result6: string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); -let result7:number = readlineSync.questionInt('Enter an integer', { limitMessage: 'Enter a valid integer' }); +const result7: number = readlineSync.questionInt('Enter an integer', { limitMessage: 'Enter a valid integer' }); -let result8:number = readlineSync.questionFloat('Enter a float', { limitMessage: 'Enter a valid float' }); +const result8: number = readlineSync.questionFloat('Enter a float', { limitMessage: 'Enter a valid float' }); -let result9:string = readlineSync.questionPath('Save to: ', { +const result9: string = readlineSync.questionPath('Save to: ', { isDirectory: true, exists: null, create: true }); -readlineSync.promptCL((command:string, arg1:string, arg2:string) => { +readlineSync.promptCL((command: string, arg1: string, arg2: string) => { if (command === 'add') { console.log(arg1 + ' is added.'); } else if (command === 'copy') { @@ -62,43 +60,43 @@ readlineSync.promptCL((command:string, arg1:string, arg2:string) => { }); readlineSync.promptCL({ - add: (element:string) => { // It's called by also "ADD", "Add", "aDd", etc.. + add: (element: string) => { // It's called by also "ADD", "Add", "aDd", etc.. console.log(element + ' is added.'); }, - copy: (from:string, to:string) => { + copy: (from: string, to: string) => { console.log(from + ' is copied to ' + to + '.'); } }); -readlineSync.promptLoop((input:string) => { +readlineSync.promptLoop((input: string) => { console.log('-- You said "' + input + '"'); return input === 'bye'; }); readlineSync.promptCLLoop({ - add: (element:string) => { + add: (element: string) => { console.log(element + ' is added.'); }, - copy: (from:string, to:string) => { + copy: (from: string, to: string) => { console.log(from + ' is copied to ' + to + '.'); }, - bye: () => { return true; } + bye: () => true }); -let result10:string = readlineSync.promptSimShell(); +const result10: string = readlineSync.promptSimShell(); -let result11:(boolean | string) = readlineSync.keyInYN('Do you want to install this?'); +const result11: (boolean | string) = readlineSync.keyInYN('Do you want to install this?'); -let result12:boolean = readlineSync.keyInYNStrict('Do you want to install this?', { guide: true }); +const result12: boolean = readlineSync.keyInYNStrict('Do you want to install this?', { guide: true }); -readlineSync.keyInPause({ guide:true }); +readlineSync.keyInPause({ guide: true }); -let frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; -let result13:number = readlineSync.keyInSelect(frameworks, 'Which framework?'); +const frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; +const result13: number = readlineSync.keyInSelect(frameworks, 'Which framework?'); -let result14:string = readlineSync.getRawInput(); +const result14: string = readlineSync.getRawInput(); -readlineSync.setPrint((display:string, encoding:string) => { console.log(display) }); +readlineSync.setPrint((display: string, encoding: string) => { console.log(display); }); readlineSync.setPrompt(new Date()); diff --git a/realm/index.d.ts b/realm/index.d.ts index ad77dc5598..974f2a4ed1 100644 --- a/realm/index.d.ts +++ b/realm/index.d.ts @@ -1,18 +1,19 @@ -// Type definitions for realm-js 0.14.3 +// Type definitions for realm-js 1.0 // Project: https://github.com/realm/realm-js // Definitions by: Akim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare namespace Realm { /** * PropertyType - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.html#~PropertyType } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~PropertyType } */ export type PropertyType = string | 'bool' | 'int' | 'float' | 'double' | 'string' | 'data' | 'date' | 'list'; /** * ObjectSchemaProperty - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.html#~ObjectSchemaProperty } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectSchemaProperty } */ export interface ObjectSchemaProperty { type: PropertyType; @@ -29,7 +30,7 @@ declare namespace Realm { /** * ObjectSchema - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.html#~ObjectSchema } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectSchema } */ export interface ObjectSchema { name: string; @@ -39,7 +40,7 @@ declare namespace Realm { /** * ObjectClass - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.html#~ObjectClass } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectClass } */ export interface ObjectClass { schema: ObjectSchema; @@ -47,15 +48,20 @@ declare namespace Realm { /** * ObjectType - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.html#~ObjectType } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectType } */ export interface ObjectType { type: ObjectClass; } + interface SyncConfiguration { + user: User; + url: string; + } + /** * realm configuration - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.html#~Configuration } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~Configuration } */ export interface Configuration { encryptionKey?: any; @@ -64,6 +70,7 @@ declare namespace Realm { readOnly?: boolean; schema?: ObjectClass[] | ObjectSchema[]; schemaVersion?: number; + sync?: SyncConfiguration; } // object props type @@ -73,13 +80,13 @@ declare namespace Realm { /** * SortDescriptor - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Collection.html#~SortDescriptor } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Collection.html#~SortDescriptor } */ export type SortDescriptor = string | [string, boolean] | any[]; /** * Iterator - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Collection.html#~Iterator } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Collection.html#~Iterator } */ export interface IteratorResult { done: boolean; @@ -87,14 +94,15 @@ declare namespace Realm { } export interface Iterator { - next(value?: any): IteratorResult; + next(done: boolean, value?: any): IteratorResult; + [Symbol.iterator](): any; } /** * Collection - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Collection.html } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Collection.html } */ - export interface Collection { + export interface Collection { readonly length: number; /** @@ -107,24 +115,24 @@ declare namespace Realm { * @param {any[]} ...arg * @returns Results */ - filtered(query: string, ...arg: any[]): Results; + filtered(query: string, ...arg: any[]): Results; /** * @param {string|SortDescriptor} descriptor * @param {boolean} reverse? * @returns Results */ - sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; - + sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; + /** - * @returns Iterator + * @returns Iterator */ - [Symbol.iterator](): Iterator; + [Symbol.iterator](): Iterator; /** * @returns Results */ - snapshot(): Results; + snapshot(): Results; /** * @returns Iterator @@ -150,70 +158,87 @@ declare namespace Realm { /** * @param {number} start? * @param {number} end? - * @returns Object + * @returns T */ - slice(start?: number, end?: number): Object[]; + slice(start?: number, end?: number): T[]; /** * @param {(object:any,index?:any,collection?:any)=>void} callback * @param {any} thisArg? - * @returns Object|void + * @returns T */ - find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): Object | void; + find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): T | null | undefined; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns number */ - findIndex(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): number; + findIndex(callback: (object: any, index?: number, collection?: any) => void, thisArg?: any): number; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns void */ - forEach(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): void; + forEach(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): void; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns boolean */ - every(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): boolean; + every(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): boolean; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns boolean */ - some(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): boolean; + some(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): boolean; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns any */ - map(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): any[]; + map(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): any[]; /** - * @param {(previousValue:any,object?:any,index?:any,collection?:any)=>void} callback + * @param {(previousValue:T,object?:T,index?:number,collection?:any)=>void} callback * @param {any} initialValue? * @returns any */ - reduce(callback: (previousValue: any, object?: any, index?: any, collection?: any) => void, initialValue?: any): any; + reduce(callback: (previousValue: T, object?: T, index?: number, collection?: any) => void, initialValue?: any): any; /** - * @param {(previousValue:any,object?:any,index?:any,collection?:any)=>void} callback + * @param {(previousValue:T,object?:T,index?:any,collection?:any)=>void} callback * @param {any} initialValue? * @returns any */ - reduceRight(callback: (previousValue: any, object?: any, index?: any, collection?: any) => void, initialValue?: any): any; + reduceRight(callback: (previousValue: T, object?: T, index?: any, collection?: any) => void, initialValue?: any): any; + + /** + * @param {(collection:any,changes:any)=>void} callback + * @returns void + */ + addListener(callback: (collection: any, changes: any) => void): void; + + /** + * @returns void + */ + removeAllListeners(): void; + + /** + * @param {()=>void} callback + * @returns void + */ + removeListener(callback: () => void): void; } /** * Object - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Object.html } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Object.html } */ export interface Object { /** @@ -224,45 +249,117 @@ declare namespace Realm { /** * List - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.List.html } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.List.html } */ - export interface List extends Collection { + export interface List extends Collection { /** - * @returns Object|void + * @returns T */ - pop(): Object | void; + pop(): T | null | undefined; /** - * @param {any} object + * @param {T} object * @returns number */ - push(object: any): number; + push(object: T): number; /** - * @returns Object|void + * @returns T */ - shift(): Object | void; + shift(): T | null | undefined; /** * @param {number} index * @param {number} count? * @param {any} object? - * @returns Object + * @returns T */ - splice(index: number, count?: number, object?: any): Object[]; + splice(index: number, count?: number, object?: any): T[]; /** - * @param {any} object + * @param {T} object * @returns number */ - unshift(object: any): number; + unshift(object: T): number; } /** * Results - * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Results.html } + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Results.html } */ - export interface Results extends Collection {} + export type Results = Collection; + + /** + * User + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.User.html } + */ + export interface User { + all: any; + current: User; + readonly identity: string; + readonly isAdmin: boolean; + readonly server: string; + readonly token: string; + adminUser(adminToken: string): User; + login(server: string, username: string, password: string, callback: (error: any, user: any) => void): void; + loginWithProvider(server: string, provider: string, providerToken: string, callback: (error: any, user: any) => void): void; + register(server: string, username: string, password: string, callback: (error: any, user: any) => void): void; + registerWithProvider(server: string, provider: string, providerToken: string, callback: (error: any, user: any) => void): void; + logout(): void; + openManagementRealm(): Realm; + } + + /** + * Session + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.Session.html } + */ + export interface Session { + readonly config: any; + readonly state: string; + readonly url: string; + readonly user: User; + } + + /** + * AuthError + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.AuthError.html } + */ + export interface AuthError { + readonly code: number; + readonly type: string; + } + + /** + * ChangeEvent + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.ChangeEvent.html } + */ + export interface ChangeEvent { + readonly changes: any; + readonly oldRealm: Realm; + readonly path: string; + readonly realm: Realm; + } + + /** + * LogLevel + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.html#~LogLevel } + */ + type LogLevelType = string | 'error' | 'info' | 'defug'; + + /** + * Sync + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.html } + */ + interface Sync { + User: User; + Session: Session; + AuthError: AuthError; + ChangeEvent: ChangeEvent; + addListener(serverURL: string, adminUser: User, regex: string, name: string, changeCallback: () => void): void; + removeAllListeners(name?: string[]): void; + removeListener(regex: string, name: string, changeCallback: () => void): void; + setLogLevel(logLevel: LogLevelType): void; + } } declare class Realm { @@ -274,12 +371,18 @@ declare class Realm { readonly schema: Realm.ObjectSchema[]; + readonly schemaVersion: number; + + static Sync: Realm.Sync; + + syncSession: Realm.Session; + /** - * @param {string} path? + * @param {string} path * @param {any} encryptionKey? * @returns number */ - schemaVersion(path?: string, encryptionKey?: any): number; + static schemaVersion(path: string, encryptionKey?: any): number; /** * @param {Realm.Configuration} config? @@ -293,17 +396,17 @@ declare class Realm { /** * @param {string|Realm.ObjectType} type - * @param {Realm.ObjectPropsType} properties + * @param {T&Realm.ObjectPropsType} properties * @param {boolean} update? - * @returns Realm.Object|T|any + * @returns T */ - create(type: string | Realm.ObjectType, properties: Realm.ObjectPropsType, update?: boolean): Realm.Object | T | any; + create(type: string | Realm.ObjectType, properties: T & Realm.ObjectPropsType, update?: boolean): T; /** - * @param {Realm.Object|Realm.Object[]|Realm.List|Realm.Results|any} object + * @param {Realm.Object|Realm.Object[]|Realm.List|Realm.Results|any} object * @returns void */ - delete(object: Realm.Object | Realm.Object[] | Realm.List | Realm.Results | any): void; + delete(object: Realm.Object | Realm.Object[] | Realm.List | Realm.Results | any): void; /** * @returns void @@ -313,15 +416,15 @@ declare class Realm { /** * @param {string|Realm.ObjectType} type * @param {number|string} key - * @returns Realm.Object|void + * @returns T */ - objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): Realm.Object | void; + objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): T | void; /** * @param {string|Realm.ObjectType} type - * @returns Realm.Results + * @returns Realm */ - objects(type: string | Realm.ObjectType): Realm.Results; + objects(type: string | Realm.ObjectType): Realm.ObjectType & Realm.Results; /** * @param {string} name diff --git a/realm/react-native/index.d.ts b/realm/react-native/index.d.ts new file mode 100644 index 0000000000..0563ca5914 --- /dev/null +++ b/realm/react-native/index.d.ts @@ -0,0 +1,3 @@ +import { ListView } from 'react-native'; + +export { ListView }; diff --git a/realm/realm-tests.ts b/realm/realm-tests.ts index e99247919b..71dccefdfa 100644 --- a/realm/realm-tests.ts +++ b/realm/realm-tests.ts @@ -1,4 +1,5 @@ import * as Realm from 'realm'; +import { ListView } from 'realm/react-native'; // schema test const personSchema = { @@ -15,7 +16,7 @@ const personSchema = { const key = new Int8Array(64); // constructor test -let realm = new Realm({ +const realm = new Realm({ schema: [personSchema], encryptionKey: key }); @@ -59,3 +60,44 @@ realm.removeAllListeners(); allPerson.find((person: any) => { return person.name === 'Jack'; }); + +const currentVersion = Realm.schemaVersion(Realm.defaultPath); + +// username/password authentication +Realm.Sync.User.register('http://localhost:9080', 'username@example.com', 'p@s$w0rd', (error, user) => { /* ... */ }); + +Realm.Sync.User.login('http://localhost.com:9080', 'username@example.com', 'p@s$w0rd', (error, user) => { + + const todoSchema = { + name: 'Todo', + primaryKey: 'id', + properties: { + id: 'int', + task: 'string', + } + }; + + // sync test + const realm = new Realm({ + schema: [todoSchema], + sync: { user, url: 'realm://localhost:9080/~/todos' } + }); + + // session test + const session = realm.syncSession; + const sessionUrl = session.config.url; +}); + +// facebook authentication +const fbAccessToken = 'acc3ssT0ken...'; +Realm.Sync.User.registerWithProvider('http://localhost:9080', 'facebook', fbAccessToken, (error, user) => { /* ... */ }); + +// user test +const user = Realm.Sync.User.current; +const users = Realm.Sync.User.all; + +// access control test +const managementRealm = user.openManagementRealm(); + +// ListView test +const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); diff --git a/realm/tsconfig.json b/realm/tsconfig.json index 0dc37a0163..ae6e53ac64 100644 --- a/realm/tsconfig.json +++ b/realm/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -17,6 +18,7 @@ }, "files": [ "index.d.ts", + "react-native/index.d.ts", "realm-tests.ts" ] } \ No newline at end of file diff --git a/realm/tslint.json b/realm/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/realm/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/rebass/index.d.ts b/rebass/index.d.ts index 17708ae115..ae37b9fa2a 100644 --- a/rebass/index.d.ts +++ b/rebass/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jxnblk/rebass // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/recompose/index.d.ts b/recompose/index.d.ts index 5668d773d5..3ff504fab3 100644 --- a/recompose/index.d.ts +++ b/recompose/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Recompose v0.20.2 +// Type definitions for Recompose v0.20.3 // Project: https://github.com/acdlite/recompose // Definitions by: Iskander Sierra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -102,7 +103,7 @@ declare module 'recompose' { export function branch( test: predicate, trueEnhancer: InferableComponentEnhancer, - falseEnhancer: InferableComponentEnhancer + falseEnhancer?: InferableComponentEnhancer ): ComponentEnhancer; // renderComponent: https://github.com/acdlite/recompose/blob/master/docs/API.md#renderComponent diff --git a/recompose/recompose-tests.tsx b/recompose/recompose-tests.tsx index 25b52d70b0..c4c66b3e2c 100644 --- a/recompose/recompose-tests.tsx +++ b/recompose/recompose-tests.tsx @@ -148,13 +148,19 @@ function testBranch() { const innerComponent: React.StatelessComponent = (props: InnerProps) =>
props.update()}>{props.count}
; + const innerComponent2 = () =>
Hello
; const enhancer = branch( (props: OutterProps) => props.toggled, withState("count", "update", 0), withState("count", "update", 100) ); + const enhancer2 = branch( + (props: OutterProps) => props.toggled, + renderComponent(innerComponent), + ) const enhanced: React.ComponentClass = enhancer(innerComponent); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); } function testRenderComponent() { diff --git a/redis/index.d.ts b/redis/index.d.ts index 75745b99f4..c20e4f1277 100644 --- a/redis/index.d.ts +++ b/redis/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redis 0.12.1 +// Type definitions for redis 0.12.2 // Project: https://github.com/mranney/node_redis // Definitions by: Carlos Ballesteros Velasco , Peter Harris , TANAKA Koichi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -91,9 +91,24 @@ export interface RedisClient extends NodeJS.EventEmitter { offline_queue: any[]; server_info: ServerInfo; - end(): void; + /** + * Forcibly close the connection to the Redis server. Note that this does not wait until all replies have been parsed. If you want to exit cleanly, call client.quit() + * + * @param {boolean} flush You should set flush to true, if you are not absolutely sure you do not care about any other commands. If you set flush to false all still running commands will silently fail. + */ + end(flush: boolean): void; unref(): void; + /** + * Stop sending commands and queue the commands. + */ + cork(): void; + + /** + * Resume and send the queued commands at once. + */ + uncork(): void; + // Low level command execution send_command(command: string, ...args: any[]): boolean; @@ -264,8 +279,8 @@ export interface RedisClient extends NodeJS.EventEmitter { hmget(...args: any[]): boolean; hincrby(args: any[], callback?: ResCallbackT): boolean; hincrby(...args: any[]): boolean; - hincrbyfloat(args:any[], callback?:ResCallbackT): boolean; - hincrbyfloat(...args:any[]): boolean; + hincrbyfloat(args: any[], callback?: ResCallbackT): boolean; + hincrbyfloat(...args: any[]): boolean; hdel(args: any[], callback?: ResCallbackT): boolean; hdel(...args: any[]): boolean; hlen(args: any[], callback?: ResCallbackT): boolean; @@ -398,7 +413,7 @@ export interface RedisClient extends NodeJS.EventEmitter { zscan(args: any[], callback?: ResCallbackT): boolean; // Extras - duplicate(options?:any[], callback?:ResCallbackT): RedisClient; + duplicate(options?: any[], callback?: ResCallbackT): RedisClient; } export interface Multi { diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index d98979f256..c1908e1089 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -31,10 +31,10 @@ client = redis.createClient(num, str, options); function retryStrategyNumber(options: redis.RetryStrategyOptions): number { // Ensure that the properties of RetryStrategyOptions are resilient to breaking change. // If the properties of the interface changes, the variables below will also need to be adapted. - var error: Error = options.error; + var error: Error = options.error; var total_retry_time: number = options.total_retry_time; - var times_connected: number = options.times_connected; - var attempt: number = options.attempt; + var times_connected: number = options.times_connected; + var attempt: number = options.attempt; return 5000; } function retryStrategyError(options: redis.RetryStrategyOptions): Error { @@ -57,7 +57,7 @@ info = client.server_info; // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- -client.end(); +client.end(true); // Connection (http://redis.io/commands#connection) client.auth(str, resCallback); @@ -98,11 +98,11 @@ client.subscribe(str); // Multi client.multi() - .scard(str) - .smembers(str) - .keys('*', resCallback) - .dbsize() - .exec(resCallback); + .scard(str) + .smembers(str) + .keys('*', resCallback) + .dbsize() + .exec(resCallback); client.multi(commandArr).exec(); @@ -112,4 +112,10 @@ client.monitor(resCallback); // Send command client.send_command(str, args, resCallback); // Duplicate -client.duplicate(); \ No newline at end of file +client.duplicate(); + +// Pipeline +client.cork(); +client.set("abc", "fff", strCallback); +client.get("abc", resCallback); +client.uncork(); diff --git a/redux-actions/index.d.ts b/redux-actions/index.d.ts index a22a0b41cc..0353318031 100644 --- a/redux-actions/index.d.ts +++ b/redux-actions/index.d.ts @@ -38,7 +38,13 @@ interface ReducerNextThrowMeta { throw?(state: State, action: ActionMeta): State; } -type ActionFunctions = ActionFunction0> | ActionFunction1> | ActionFunction2> | ActionFunction3> | ActionFunction4> | ActionFunctionAny>; +type ActionFunctions = + ActionFunction0> | + ActionFunction1> | + ActionFunction2> | + ActionFunction3> | + ActionFunction4> | + ActionFunctionAny>; type Reducer = (state: State, action: Action) => State; diff --git a/redux-actions/redux-actions-tests.ts b/redux-actions/redux-actions-tests.ts index 60923b9f10..11fa7adf13 100644 --- a/redux-actions/redux-actions-tests.ts +++ b/redux-actions/redux-actions-tests.ts @@ -26,7 +26,7 @@ const actionHandlerWithReduceMap = ReduxActions.handleAction( next(state: number, action: ReduxActions.Action) { return state * action.payload; }, - throw(state: number) { return state } + throw(state: number) { return state; } }, 0 ); @@ -34,17 +34,17 @@ const actionHandlerWithReduceMap = ReduxActions.handleAction( state = actionHandlerWithReduceMap(0, multiplyAction(10)); const actionsHandler = ReduxActions.handleActions({ - 'INCREMENT': (state: number, action: ReduxActions.Action) => state + action.payload, - 'MULTIPLY': (state: number, action: ReduxActions.Action) => state * action.payload + INCREMENT: (state: number, action: ReduxActions.Action) => state + action.payload, + MULTIPLY: (state: number, action: ReduxActions.Action) => state * action.payload }, 0); state = actionsHandler(0, { type: 'INCREMENT' }); const actionsHandlerWithInitialState = ReduxActions.handleActions({ - 'INCREMENT': { + INCREMENT: { next: (state: number, action: ReduxActions.Action) => state + action.payload, }, - 'MULTIPLY': { + MULTIPLY: { next: (state: number, action: ReduxActions.Action) => state * action.payload } }, 0); @@ -53,17 +53,17 @@ state = actionsHandlerWithInitialState(0, { type: 'INCREMENT' }); // ---------------------------------------------------------------------------------------------------- -type TypedState = { +interface TypedState { value: number; -}; +} -type TypedPayload = { +interface TypedPayload { increase: number; } -type MetaType = { - remote: boolean -}; +interface MetaType { + remote: boolean; +} let typedState: TypedState; @@ -103,37 +103,37 @@ const typedActionHandlerWithReduceMap = ReduxActions.handleAction) { return { value: state.value + action.payload.increase }; }, - throw(state: TypedState) { return state } + throw(state: TypedState) { return state; } }, {value: 1} ); typedState = typedActionHandlerWithReduceMap({ value: 0 }, typedIncrementByActionWithMeta(10)); -const act = ReduxActions.createAction('ACTION1') -act('hello').payload === 'hello' +const act = ReduxActions.createAction('ACTION1'); +act('hello').payload === 'hello'; -const act2 = ReduxActions.createAction('ACTION2', (s: {load: boolean}) => s) -act2({load: true}).payload.load == true +const act2 = ReduxActions.createAction('ACTION2', (s: {load: boolean}) => s); +act2({load: true}).payload.load === true; -const act3 = ReduxActions.createAction('ACTION3', (s: string) => ({s})) -act3('hello').payload.s == 'hello' +const act3 = ReduxActions.createAction('ACTION3', (s: string) => ({s})); +act3('hello').payload.s === 'hello'; ReduxActions.handleAction<{ hello: string }, string>(act, (state, action) => { - return { hello: action.payload } -}, {hello: 'greetings'}) + return { hello: action.payload }; +}, {hello: 'greetings'}); ReduxActions.handleAction<{ hello: { load: boolean } }, { load: boolean }>(act2, (state, action) => { - return { hello: action.payload } -}, {hello: {load: true}}) + return { hello: action.payload }; +}, {hello: {load: true}}); ReduxActions.handleAction(act3, (state, action) => { - return { hello: action.payload.s } -}, {hello: 'greetings'}) + return { hello: action.payload.s }; +}, {hello: 'greetings'}); ReduxActions.handleAction(ReduxActions.combineActions(act, act3, act2), (state, action) => { -}, 0) +}, 0); /* can't do this until it lands in 2.2, HKTs ReduxActions.handleAction(act, (state, action) => { diff --git a/redux-actions/tslint.json b/redux-actions/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/redux-actions/tslint.json +++ b/redux-actions/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-batched-actions/tslint.json b/redux-batched-actions/tslint.json index 192203ab54..377cc837d4 100644 --- a/redux-batched-actions/tslint.json +++ b/redux-batched-actions/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-bootstrap/index.d.ts b/redux-bootstrap/index.d.ts index 6a539853b7..60d53bb713 100644 --- a/redux-bootstrap/index.d.ts +++ b/redux-bootstrap/index.d.ts @@ -1,29 +1,30 @@ -// Type definitions for react-bootstrap v1.0.0 +// Type definitions for react-bootstrap 1.0 // Project: https://github.com/remojansen/redux-bootstrap // Definitions by: Remo H. Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare module "redux-bootstrap" { - import * as Redux from "redux"; - import ReactRouterRedux = require("react-router-redux"); +import * as React from "react"; +import { Middleware, Reducer, Store } from "redux"; +import { History } from "history"; - interface BootstrapOptions { - routes: JSX.Element; - reducers: ReducersOption; - middlewares?: Redux.Middleware[]; - initialState?: any; - container?: string; - } - - interface BootstrapResult { - store: Redux.Store; - history: ReactRouterRedux.ReactRouterReduxHistory; - root: JSX.Element; - } - - interface ReducersOption { - [index: string]: Redux.Reducer; - } - - export default function bootstrap(options: BootstrapOptions): BootstrapResult; +export interface BootstrapOptions { + routes: JSX.Element; + reducers: ReducersOption; + middlewares?: Middleware[]; + initialState?: any; + container?: string; } + +export interface BootstrapResult { + store: Store; + history: History; + root: JSX.Element; +} + +export interface ReducersOption { + [index: string]: Reducer; +} + +export default function bootstrap(options: BootstrapOptions): BootstrapResult; + diff --git a/redux-bootstrap/tsconfig.json b/redux-bootstrap/tsconfig.json index a5c0900ca4..cca0524f9c 100644 --- a/redux-bootstrap/tsconfig.json +++ b/redux-bootstrap/tsconfig.json @@ -9,9 +9,6 @@ "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], diff --git a/redux-devtools-dock-monitor/index.d.ts b/redux-devtools-dock-monitor/index.d.ts index c1f8743292..de90f9a36e 100644 --- a/redux-devtools-dock-monitor/index.d.ts +++ b/redux-devtools-dock-monitor/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools-dock-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/redux-devtools-log-monitor/index.d.ts b/redux-devtools-log-monitor/index.d.ts index cc6f8cc7df..32062607c2 100644 --- a/redux-devtools-log-monitor/index.d.ts +++ b/redux-devtools-log-monitor/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools-log-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react' import {ColorScheme} from 'base16' diff --git a/redux-devtools/index.d.ts b/redux-devtools/index.d.ts index 28a551313f..f94239ff2e 100644 --- a/redux-devtools/index.d.ts +++ b/redux-devtools/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; diff --git a/redux-form/v4/index.d.ts b/redux-form/v4/index.d.ts index 77a3004710..fa4cd9dbaa 100644 --- a/redux-form/v4/index.d.ts +++ b/redux-form/v4/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/erikras/redux-form // Definitions by: Daniel Lytkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; import { Component, SyntheticEvent, FormEventHandler } from 'react'; diff --git a/redux-immutable/index.d.ts b/redux-immutable/index.d.ts index 2c378f02d8..483de7c9bf 100644 --- a/redux-immutable/index.d.ts +++ b/redux-immutable/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for redux-immutable v3.0.5 +// Type definitions for redux-immutable v3.0.10 // Project: https://github.com/gajus/redux-immutable -// Definitions by: Pedro Pereira +// Definitions by: Pedro Pereira , Sebastian Sebald // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Redux from 'redux'; -export declare function combineReducers(reducers: Object): Redux.Reducer; +export declare function combineReducers(reducers: Redux.ReducersMapObject): Redux.Reducer; diff --git a/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts b/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts index bb15d77121..24b5a32528 100644 --- a/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts +++ b/redux-localstorage-debounce/redux-localstorage-debounce-tests.ts @@ -1,21 +1,21 @@ -import { compose } from "redux" +import { compose } from "redux"; import { default as persistState -} from "redux-localstorage" -import * as adapter from "redux-localstorage/lib/adapters/localStorage" -import { default as debounce } from "redux-localstorage-debounce" +} from "redux-localstorage"; +import * as adapter from "redux-localstorage/lib/adapters/localStorage"; +import { default as debounce } from "redux-localstorage-debounce"; const storageWait = compose( debounce(100) -)(adapter(window.localStorage)) -const enhancerWait = persistState(storageWait, "test") +)(adapter(window.localStorage)); +const enhancerWait = persistState(storageWait, "test"); const storageMax = compose( debounce(100, 200) -)(adapter(window.localStorage)) -const enhancerMax = persistState(storageMax, "test") +)(adapter(window.localStorage)); +const enhancerMax = persistState(storageMax, "test"); const storageOpts = compose( debounce(100, { maxWait : 200, foo : "bar" }) -)(adapter(window.localStorage)) -const enhancerOpts = persistState(storageOpts, "test") +)(adapter(window.localStorage)); +const enhancerOpts = persistState(storageOpts, "test"); diff --git a/redux-localstorage-debounce/tslint.json b/redux-localstorage-debounce/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/redux-localstorage-debounce/tslint.json +++ b/redux-localstorage-debounce/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-localstorage-filter/redux-localstorage-filter-tests.ts b/redux-localstorage-filter/redux-localstorage-filter-tests.ts index 83939ea310..5569b22345 100644 --- a/redux-localstorage-filter/redux-localstorage-filter-tests.ts +++ b/redux-localstorage-filter/redux-localstorage-filter-tests.ts @@ -1,16 +1,16 @@ -import { compose } from "redux" +import { compose } from "redux"; import { default as persistState -} from "redux-localstorage" -import * as adapter from "redux-localstorage/lib/adapters/localStorage" -import { default as filter } from "redux-localstorage-filter" +} from "redux-localstorage"; +import * as adapter from "redux-localstorage/lib/adapters/localStorage"; +import { default as filter } from "redux-localstorage-filter"; const storageSingle = compose( filter("foo") -)(adapter(window.localStorage)) -const enhancerSingle = persistState(storageSingle, "test") +)(adapter(window.localStorage)); +const enhancerSingle = persistState(storageSingle, "test"); const storageMulti = compose( filter(["foo", "bar"]) -)(adapter(window.localStorage)) -const enhancerMulti = persistState(storageMulti, "test") +)(adapter(window.localStorage)); +const enhancerMulti = persistState(storageMulti, "test"); diff --git a/redux-localstorage-filter/tslint.json b/redux-localstorage-filter/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/redux-localstorage-filter/tslint.json +++ b/redux-localstorage-filter/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/redux-localstorage/redux-localstorage-tests.ts b/redux-localstorage/redux-localstorage-tests.ts index e0e5ad4bfa..49bf442fcf 100644 --- a/redux-localstorage/redux-localstorage-tests.ts +++ b/redux-localstorage/redux-localstorage-tests.ts @@ -1,33 +1,33 @@ -import { Reducer, compose, combineReducers, createStore } from "redux" +import { Reducer, compose, combineReducers, createStore } from "redux"; import { default as persistState, mergePersistedState, actionTypes -} from "redux-localstorage" -import * as adapterAsyncStorage from "redux-localstorage/lib/adapters/AsyncStorage" -import * as adapterLocalStorage from "redux-localstorage/lib/adapters/localStorage" -import * as adapterSessionStorage from "redux-localstorage/lib/adapters/sessionStorage" +} from "redux-localstorage"; +import * as adapterAsyncStorage from "redux-localstorage/lib/adapters/AsyncStorage"; +import * as adapterLocalStorage from "redux-localstorage/lib/adapters/localStorage"; +import * as adapterSessionStorage from "redux-localstorage/lib/adapters/sessionStorage"; -const AsyncStorage: any = {} +const AsyncStorage: any = {}; -const rootReducer: Reducer = (state: any, action: any) => state +const rootReducer: Reducer = (state: any, action: any) => state; const reducer = compose( mergePersistedState() -)(rootReducer) +)(rootReducer); -const storageAsyncStorage = adapterAsyncStorage(AsyncStorage) -const storageLocalStorage = adapterLocalStorage(window.localStorage) -const storageSessionStorage = adapterSessionStorage(window.sessionStorage) +const storageAsyncStorage = adapterAsyncStorage(AsyncStorage); +const storageLocalStorage = adapterLocalStorage(window.localStorage); +const storageSessionStorage = adapterSessionStorage(window.sessionStorage); const createStoreAsyncStorage = compose( persistState(storageAsyncStorage, "foo") -)(createStore)(reducer) +)(createStore)(reducer); const createStoreLocalStorage = compose( persistState(storageLocalStorage, "foo") -)(createStore)(reducer) +)(createStore)(reducer); const createStoreSessionStorage = compose( persistState(storageSessionStorage, "foo") -)(createStore)(reducer) +)(createStore)(reducer); diff --git a/redux-localstorage/tslint.json b/redux-localstorage/tslint.json index e050abdce9..d032145676 100644 --- a/redux-localstorage/tslint.json +++ b/redux-localstorage/tslint.json @@ -4,4 +4,4 @@ "forbidden-types": false, "no-empty-interface": false } -} \ No newline at end of file +} diff --git a/redux-logger/index.d.ts b/redux-logger/index.d.ts index edcb2b9152..257f070d44 100644 --- a/redux-logger/index.d.ts +++ b/redux-logger/index.d.ts @@ -5,46 +5,45 @@ import * as Redux from "redux"; -type LoggerPredicate = (getState: () => any, action: any) => boolean; - -type StateToString = (state: any) => string; -type ActionToString = (action: any) => string; -type ErrorToString = (error: any, prevState: any) => string; - -interface ColorsObject { - title?: boolean | ActionToString; - prevState?: boolean | StateToString; - action?: boolean | ActionToString; - nextState?: boolean | StateToString; - error?: boolean | ErrorToString; -} - -interface LevelObject { - prevState?: string | boolean | StateToString; - action?: string | boolean | ActionToString; - nextState?: string | boolean | StateToString; - error?: string | boolean | ErrorToString; -} - -interface ReduxLoggerOptions { - level?: string | ActionToString | LevelObject; - duration?: boolean; - timestamp?: boolean; - colors?: ColorsObject; - logger?: any; - logErrors?: boolean; - collapsed?: boolean | LoggerPredicate; - predicate?: LoggerPredicate; - stateTransformer?: (state: any) => any; - actionTransformer?: (action: any) => any; - errorTransformer?: (error: any) => any; - diff?: boolean; - diffPredicate?: LoggerPredicate; -} - - // Trickery to get TypeScript to accept that our anonymous, non-default export is a function. // see https://github.com/Microsoft/TypeScript/issues/3612 for more -declare namespace createLogger { } -declare function createLogger(options?: ReduxLoggerOptions): Redux.Middleware; +declare namespace createLogger { + export type LoggerPredicate = (getState: () => any, action: any) => boolean; + + export type StateToString = (state: any) => string; + export type ActionToString = (action: any) => string; + export type ErrorToString = (error: any, prevState: any) => string; + + export interface ColorsObject { + title?: boolean | ActionToString; + prevState?: boolean | StateToString; + action?: boolean | ActionToString; + nextState?: boolean | StateToString; + error?: boolean | ErrorToString; + } + + export interface LevelObject { + prevState?: string | boolean | StateToString; + action?: string | boolean | ActionToString; + nextState?: string | boolean | StateToString; + error?: string | boolean | ErrorToString; + } + + export interface ReduxLoggerOptions { + level?: string | ActionToString | LevelObject; + duration?: boolean; + timestamp?: boolean; + colors?: ColorsObject; + logger?: any; + logErrors?: boolean; + collapsed?: boolean | LoggerPredicate; + predicate?: LoggerPredicate; + stateTransformer?: (state: any) => any; + actionTransformer?: (action: any) => any; + errorTransformer?: (error: any) => any; + diff?: boolean; + diffPredicate?: LoggerPredicate; + } +} +declare function createLogger(options?: createLogger.ReduxLoggerOptions): Redux.Middleware; export = createLogger; diff --git a/redux-router/index.d.ts b/redux-router/index.d.ts index 144f53c048..0c0f0ff29b 100644 --- a/redux-router/index.d.ts +++ b/redux-router/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rackt/redux-router // Definitions by: Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as React from 'react'; import * as ReactRouter from 'react-router'; diff --git a/redux-router/tsconfig.json b/redux-router/tsconfig.json index 786008c59c..10120c4840 100644 --- a/redux-router/tsconfig.json +++ b/redux-router/tsconfig.json @@ -10,7 +10,8 @@ "strictNullChecks": false, "baseUrl": "../", "paths": { - "history": ["history/v2"] + "history": ["history/v2"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" diff --git a/redux-saga/index.d.ts b/redux-saga/index.d.ts deleted file mode 100644 index 0319c8b44b..0000000000 --- a/redux-saga/index.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -// Type definitions for redux-saga 0.9.1 -// Project: https://github.com/yelouafi/redux-saga -// Definitions by: Daniel Lytkin , Dimitri Rosenberg -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'redux-saga' { - export class SagaCancellationException { - } - - export type Saga = (getState?: () => T) => Iterable; - export type Predicate = (action: any) => boolean; - export type Pattern = string | string[] | Predicate; - - import {Middleware} from 'redux'; - - interface SagaMiddleware extends Middleware { - run(saga: Saga, ...args: any[]): void; - } - - export default function (...sagas: Saga[]): SagaMiddleware; - - export { - CANCEL, - RACE_AUTO_CANCEL, - PARALLEL_AUTO_CANCEL, - MANUAL_CANCEL - } from 'redux-saga/lib/proc'; - - import * as monitorActions from 'redux-saga/lib/monitorActions'; - export {monitorActions} - - export {runSaga, storeIO} from 'redux-saga/lib/runSaga' - - export interface Task { - name:string; - isRunning():boolean; - result():T; - error():any; - cancel(): void; - } - - export function takeEvery(pattern: Pattern, saga: Saga, ...args: any[]): { [Symbol.iterator](): IterableIterator }; - - export function takeLatest(pattern: Pattern, saga: Saga, ...args: any[]): { [Symbol.iterator](): IterableIterator }; - - export function delay(ms: number): Promise; - - export function delay(ms: number, val: T): Promise; - - export function isCancelError(e: any): boolean; -} - -declare module 'redux-saga/effects' { - import {Task} from 'redux-saga'; - import {Predicate} from 'redux-saga'; - import {Pattern} from 'redux-saga'; - - export type Effect = {}; - - type EffectFunction = (arg1?: T1, arg2?: T2, arg3?: T3, ...rest: any[]) => Promise | Iterable; - - interface EffectFunctionContext { - 0: any; - 1: EffectFunction; - } - - export function take(pattern?: Pattern): Effect; - - export function put(action: any): Effect; - - export function race(effects: {[key:string]: any}): Effect; - - export function call(fn: EffectFunction, arg1?: T1, arg2?: T2, arg3?: T3, ...rest: any[]): Effect; - - export function call(fn: EffectFunctionContext, arg1?: T1, arg2?: T2, arg3?: T3, ...rest: any[]): Effect; - - export function apply(context: any, fn: EffectFunction, arg1?: T1, arg2?: T2, arg3?: T3, ...rest: any[]): Effect; - - export function fork(effect: Effect): Effect; - - export function fork(fn: EffectFunction, arg1?: T1, arg2?: T2, arg3?: T3, ...rest: any[]): Effect; - - export function fork(fn: EffectFunctionContext, arg1?: T1, arg2?: T2, arg3?: T3, ...rest: any[]): Effect; - - export function join(task: Task): Effect; - - export function select(selector?: (state: any, ...args: any[]) => any, ...args: any[]): Effect; - - export function cancel(task: Task): Effect; -} - -declare module 'redux-saga/lib/proc' { - import {Task} from 'redux-saga'; - - export const CANCEL: symbol; - export const NOT_ITERATOR_ERROR: string; - export const PARALLEL_AUTO_CANCEL: string; - export const RACE_AUTO_CANCEL: string; - export const MANUAL_CANCEL: string; - - export default function proc(iterator: Iterable, - subscribe?: (cb: Function) => Function, - dispatch?: (action: any) => any, - monitor?: (action: any) => void, - parentEffectId?: any, - name?: string): Task; -} - - -declare module 'redux-saga/lib/runSaga' { - import {Store} from 'redux'; - import {Task} from 'redux-saga'; - - interface IO { - dispatch: (action: any) => any; - subscribe: (cb: Function) => Function; - } - - export function storeIO(store: Store): IO; - - export function runSaga(iterator: Iterable, - io: IO, - monitor?: (action: any) => void): Task; -} - - -declare module 'redux-saga/lib/emitter' { - export default function emitter(): { - subscribe(cb: Function):Function; - emit(item: any):void; - } -} - -declare module 'redux-saga/lib/monitorActions' { - export const MONITOR_ACTION: string; - export const EFFECT_TRIGGERED: string; - export const EFFECT_RESOLVED: string; - export const EFFECT_REJECTED: string; -} diff --git a/redux-saga/redux-saga-tests.ts b/redux-saga/redux-saga-tests.ts deleted file mode 100644 index 1165103186..0000000000 --- a/redux-saga/redux-saga-tests.ts +++ /dev/null @@ -1,213 +0,0 @@ - - - -import sagaMiddleware, { - storeIO, - runSaga, - Saga, - SagaCancellationException, - takeEvery, - takeLatest, - isCancelError -} from 'redux-saga' - -import { - take, - put, - race, - call, - apply, - fork, - select, - cancel, -} from 'redux-saga/effects' - -import {applyMiddleware, createStore} from 'redux'; - -declare const delay: (ms: number) => Promise; -declare const fetchApi: (url: string) => Promise; - -namespace GettingStarted { - - const incrementAsync:Saga = function* incrementAsync() { - - while(true) { - - // wait for each INCREMENT_ASYNC action - const nextAction = yield take('INCREMENT_ASYNC') - - // delay is a sample function - // return a Promise that resolves after (ms) milliseconds - yield delay(1000) - - // dispatch INCREMENT_COUNTER - yield put( {type: 'INCREMENT_COUNTER'} ) - } - - } - - const createStoreWithSaga = applyMiddleware( - // ..., - sagaMiddleware(incrementAsync) - )(createStore) - - export default function configureStore(initialState) { - return createStoreWithSaga((state: any) => state, initialState) - } -} - -namespace EffectCombinators { - const fetchPostsWithTimeout:Saga = function* fetchPostsWithTimeout() { - while( yield take('FETCH_POSTS') ) { - // starts a race between 2 effects - const {posts, timeout} = yield race({ - posts : call([this, fetchApi], '/posts'), - timeout : call(delay, 1000) - }) - - if(posts) - put( {type: 'RECEIVE_POSTS', posts} ) - else - put( {type: 'TIMEOUT_ERROR'} ) - } - } -} - - -namespace SequencingSagasViaYield { - function showScore(score) { - return { - type: 'SHOW_SCORE', score - } - } - - function* playLevelOne(getState) { yield 1 } - - function* playLevelTwo(getState) { yield 2 } - - function* playLevelThree(getState) { yield 3 } - - const game: Saga = function* game(getState) { - - const score1 = yield* playLevelOne(getState) - yield put(showScore(score1)) - - const score2 = yield* playLevelTwo(getState) - yield put(showScore(score2)) - - const score3 = yield* playLevelThree(getState) - yield put(showScore(score3)) - - } -} - - -namespace ComposingSagas { - function* fetchProducts() { - yield put( {type: 'REQUEST_PRODUCTS'} ) - const products = yield call(fetchApi, '/products') - yield put( {type: 'RECEIVE_PRODUCTS', products } ) - } - - function* watchFetch() { - while ( yield take('FETCH_PRODUCTS') ) { - yield call(fetchProducts) // waits for the fetchProducts task to - // terminate - } - } -} - - -namespace NonBlockingCallsWithForkJoin { - function* fetchPosts() { - yield put( {type: 'REQUEST_POSTS'} ) - const posts = yield call(fetchApi, '/posts') - yield put( {type: 'RECEIVE_POSTS', posts} ) - } - - function* watchFetch() { - while ( yield take('FETCH_POSTS') ) { - yield fork(fetchPosts) // non blocking call - } - } -} - - -namespace TaskCancellation { - declare const someApi: () => any; - - function* bgSync() { - try { - while(true) { - yield put({type: 'REQUEST_START'}) - const result = yield apply(this, someApi) - yield put({type: 'REQUEST_SUCCESS', result}) - yield call(delay, 5000) - } - } catch(error) { - if(error instanceof SagaCancellationException && isCancelError(error)) - yield put({type: 'REQUEST_FAILURE', message: 'Sync cancelled!'}) - } - } - - function* main() { - while( yield take('START_BACKGROUND_SYNC') ) { - // starts the task in the background - const bgSyncTask = yield fork(bgSync) - - // wait for the user stop action - yield take('STOP_BACKGROUND_SYNC') - // user clicked stop. cancel the background task - // this will throw a SagaCancellationException into the forked bgSync - // task - yield cancel(bgSyncTask) - } - } -} - - -namespace DynamicallyStartingSagasWithRunSaga { - const store = createStore((state: any, action: any) => state); - - function* serverSaga(getState) { - yield getState() - } - - runSaga( - serverSaga(store.getState), - storeIO(store) - ) -} - -namespace DynamicallyStartingSagasWithMiddleware { - function* startupSaga() { - } - - function* dynamicSaga() { - } - - sagaMiddleware(startupSaga).run(dynamicSaga) -} - -namespace TestHelpers { - function* watchAndLog(getState) { - yield* takeEvery('*', function* logger(action) { - console.log('action', action) - }) - } - - function* fetchUser(action) { - } - - function* watchLastFetchUser() { - yield* takeLatest('USER_REQUESTED', fetchUser) - } -} - -namespace AccessCurrentState { - export const getCart = state => state.cart; - - function* checkout() { - const cart = yield select(getCart) - } -} diff --git a/redux-ui/index.d.ts b/redux-ui/index.d.ts index f38cd16ec1..3b1f8f4a58 100644 --- a/redux-ui/index.d.ts +++ b/redux-ui/index.d.ts @@ -1,53 +1,50 @@ -// Type definitions for redux-ui 0.0.15 +// Type definitions for redux-ui 0.0 // Project: https://github.com/tonyhb/redux-ui // Definitions by: Andy Shu Xin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "redux-ui" { +import * as Redux from 'redux'; - import * as Redux from 'redux'; +export interface uiParams { + // optional key which is used to determine the UI path in which state will + // be stored. if omitted this is randomly generated. + key?: string; - export interface uiParams { - // optional key which is used to determine the UI path in which state will - // be stored. if omitted this is randomly generated. - key?: string; + // optional persist, defaults to false. if set to true persist will keep UI + // state for this component after it unmounts. if set to false the UI state + // will be deleted and recreated when the component remounts + persist?: boolean; - // optional persist, defaults to false. if set to true persist will keep UI - // state for this component after it unmounts. if set to false the UI state - // will be deleted and recreated when the component remounts - persist?: boolean; + // **required**: UI state for the component + state: UIStateShape; - // **required**: UI state for the component - state: UIStateShape; + // optional mergeProps passed to react-redux' @connect + mergeProps?: (stateProps: any, dispatchProps: any, ownProps: any) => any; - // optional mergeProps passed to react-redux' @connect - mergeProps?: (stateProps: any, dispatchProps: any, ownProps: any) => any; - - // optional `options` passed to react-redux @connect - options?: { - pure?: boolean; - withRef?: boolean; - }; - } - - export interface ReduxUIProps { - // The key passed to the decorator from the decorator - // (eg. 'some-decorator' with `@ui('some-decorator')` - uiKey: string; - - // The UI state for the component's `uiKey` - ui: UIStateShape; - - // A function accepting either a name/value pair or object which updates - // state within `uiKey` - updateUI(obj: UIStateShape): void; - updateUI(key: string, value: any): void; - - // A function which resets the state within `uiKey` to its default - resetUI(): void; - } - - export const reducer: Redux.Reducer; - - export default function ui(params?: uiParams): (component: T) => T; + // optional `options` passed to react-redux @connect + options?: { + pure?: boolean; + withRef?: boolean; + }; } + +export interface ReduxUIProps { + // The key passed to the decorator from the decorator + // (eg. 'some-decorator' with `@ui('some-decorator')` + uiKey: string; + + // The UI state for the component's `uiKey` + ui: UIStateShape; + + // A function accepting either a name/value pair or object which updates + // state within `uiKey` + updateUI(obj: UIStateShape): void; + updateUI(key: string, value: any): void; + + // A function which resets the state within `uiKey` to its default + resetUI(): void; +} + +export const reducer: Redux.Reducer; + +export default function ui(params?: uiParams): (component: T) => T; diff --git a/redux-ui/redux-ui-tests.ts b/redux-ui/redux-ui-tests.ts index 63ac16c84e..352e70576d 100644 --- a/redux-ui/redux-ui-tests.ts +++ b/redux-ui/redux-ui-tests.ts @@ -1,10 +1,10 @@ -import * as React from 'react' -import * as Redux from 'redux' -import ui, { ReduxUIProps, reducer } from 'redux-ui' +import * as React from 'react'; +import * as Redux from 'redux'; +import ui, { ReduxUIProps, reducer } from 'redux-ui'; -type UIShape = { +interface UIShape { s: string; -}; +} @ui({ key: 'Root', diff --git a/redux-ui/tslint.json b/redux-ui/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/redux-ui/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/reflux/index.d.ts b/reflux/index.d.ts index 4cef17c03b..58177ee7fe 100644 --- a/reflux/index.d.ts +++ b/reflux/index.d.ts @@ -1,64 +1,59 @@ -// Type definitions for RefluxJS +// Type definitions for RefluxJS 0.4 // Project: https://github.com/reflux/refluxjs // Definitions by: Maurice de Beijer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = RefluxCore; export as namespace Reflux; -declare module RefluxCore { - - interface StoreDefinition { - listenables?: any[], - init?: Function, - getInitialState?: Function, - [propertyName: string]: any; - } - - interface ListenFn { - (...params: any[]):any, - completed: Function, - failed: Function - } - interface Listenable { - listen: ListenFn - } - - interface Subscription { - stop: Function, - listenable: Listenable - } - - interface Store { - hasListener(listenable: Listenable): boolean, - listenToMany(listenables: Listenable[]): void, - validateListening(listenable: Listenable): string, - listenTo(listenable: Listenable, callback: Function, defaultCallback?: Function): Subscription, - stopListeningTo(listenable: Listenable): boolean, - stopListeningToAll(): void, - fetchInitialState(listenable: Listenable, defaultCallback: Function): void, - trigger(state: any):void; - listen(callback: Function, bindContext: any): Function; - } - - interface ActionsDefinition { - [index: string]:any - } - - interface Actions { - [index: string]: Listenable - } - - function createStore(definition: StoreDefinition): Store; - - function createAction(definition?: ActionsDefinition): any; - - function createActions(definition: ActionsDefinition): any; - function createActions(definitions: string[]): any; - - function connect(store: Store, key?: string):void; - function listenTo(store: Store, handler: string):void; - function setState(state: any):void; - - function ListenerMixin(): any; +interface StoreDefinition { + listenables?: any[]; + init?: Function; + getInitialState?: Function; + [propertyName: string]: any; } + +interface ListenFn { + (...params: any[]): any; + completed: Function; + failed: Function; +} +interface Listenable { + listen: ListenFn; +} + +interface Subscription { + stop: Function; + listenable: Listenable; +} + +interface Store { + hasListener(listenable: Listenable): boolean; + listenToMany(listenables: Listenable[]): void; + validateListening(listenable: Listenable): string; + listenTo(listenable: Listenable, callback: Function, defaultCallback?: Function): Subscription; + stopListeningTo(listenable: Listenable): boolean; + stopListeningToAll(): void; + fetchInitialState(listenable: Listenable, defaultCallback: Function): void; + trigger(state: any): void; + listen(callback: Function, bindContext: any): Function; +} + +interface ActionsDefinition { + [index: string]: any; +} + +interface Actions { + [index: string]: Listenable; +} + +export function createStore(definition: StoreDefinition): Store; + +export function createAction(definition?: ActionsDefinition): any; + +export function createActions(definitions: ActionsDefinition | string[]): any; + +export function connect(store: Store, key?: string): void; +export function listenTo(store: Store, handler: string): void; +export function setState(state: any): void; + +export function ListenerMixin(): any; diff --git a/reflux/reflux-tests.ts b/reflux/reflux-tests.ts index 5094ed9ecc..7a392282fa 100644 --- a/reflux/reflux-tests.ts +++ b/reflux/reflux-tests.ts @@ -1,6 +1,3 @@ - -/// - import Reflux = require("reflux"); import React = require("react"); @@ -15,7 +12,7 @@ var asyncActions = Reflux.createActions({ fireBall: {asyncResult: true} }); -asyncActions.fireBall.listen(function () { +asyncActions.fireBall.listen(function() { // Trigger async action setTimeout(() => this.completed(true), 1000); }); @@ -25,13 +22,12 @@ asyncActions.fireBall.listen(function () { var statusStore = Reflux.createStore({ // Initial setup - init: function () { - + init() { // Register statusUpdate action this.listenTo(asyncActions.fireBall, this.onFireBall); }, // Callback - onFireBall: function (flag: boolean) { + onFireBall(flag: boolean) { var status = flag ? 'ONLINE' : 'OFFLINE'; // Pass on to listeners @@ -48,13 +44,13 @@ var action = Reflux.createAction(); var actions = Reflux.createActions(["fireBall", "magicMissile"]); var Store = Reflux.createStore({ - init: function () { + init() { this.listenToMany(actions); }, - onFireBall: function () { + onFireBall() { // whoooosh! }, - onMagicMissile: function () { + onMagicMissile() { // bzzzzapp! } }); diff --git a/reflux/tslint.json b/reflux/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/reflux/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/request/index.d.ts b/request/index.d.ts index edf31b9a9b..d576c82e3b 100644 --- a/request/index.d.ts +++ b/request/index.d.ts @@ -91,6 +91,8 @@ declare namespace request { qsStringifyOptions?: any; qsParseOptions?: any; json?: any; + jsonReviver?: (key: string, value: any) => any; + jsonReplacer?: (key: string, value: any) => any; multipart?: RequestPart[] | Multipart; agent?: http.Agent | https.Agent; agentOptions?: any; diff --git a/request/request-tests.ts b/request/request-tests.ts index b26149533b..1bd81760c8 100644 --- a/request/request-tests.ts +++ b/request/request-tests.ts @@ -91,6 +91,12 @@ var options: request.Options = { aws: aws, qs: obj, json: value, + jsonReviver: (key: string, value: any) => { + + }, + jsonReplacer: (key: string, value: any) => { + + }, multipart: value, agent: new http.Agent(), agentOptions: value, diff --git a/restify-plugins/index.d.ts b/restify-plugins/index.d.ts index 3ce557374f..68c9131c3b 100644 --- a/restify-plugins/index.d.ts +++ b/restify-plugins/index.d.ts @@ -6,7 +6,7 @@ import {RequestHandler, Server, Request, Response, Route} from 'restify'; import Logger = require('bunyan'); -//*************** This module includes the follow pre plugins, which are intended to be used prior to the routing of a request: +// *************** This module includes the follow pre plugins, which are intended to be used prior to the routing of a request: export namespace pre { /** @@ -45,7 +45,7 @@ export namespace pre { function userAgentConnection( options?: {userAgentRegExp: any} ): RequestHandler; } -//*************** This module includes the following header parser plugins: +// *************** This module includes the following header parser plugins: /** * Check the client's Accept header can be handled by this server. @@ -106,7 +106,7 @@ export function conditionalRequest(): RequestHandler[]; */ export function fullResponse(): RequestHandler; -//************ This module includes the following data parsing plugins: +// ************ This module includes the following data parsing plugins: interface BodyParserOptions { /** @@ -120,22 +120,30 @@ interface BodyParserOptions { 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. + * 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. + * 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. + * 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. + * 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; @@ -263,7 +271,8 @@ interface QueryParserOptions { 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`. + * 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; @@ -292,7 +301,7 @@ interface RequestLogger { */ export function requestLogger(options?: RequestLogger): RequestHandler; -//******************** The module includes the following response plugins: +// ******************** The module includes the following response plugins: /** * expires requests based on current time + delta diff --git a/restify/index.d.ts b/restify/index.d.ts index f53aa0eba9..3888d58481 100644 --- a/restify/index.d.ts +++ b/restify/index.d.ts @@ -300,6 +300,7 @@ interface HandlerTiming { interface Response extends http.ServerResponse { header: (key: string, value?: any) => any; cache: (type?: any, options?: Object) => 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; @@ -448,6 +449,7 @@ interface Server extends http.Server { } interface ServerOptions { + ca?: string; certificate?: string; key?: string; formatters?: Object; diff --git a/restify/restify-tests.ts b/restify/restify-tests.ts index dcf7dc4ca6..147171ae29 100644 --- a/restify/restify-tests.ts +++ b/restify/restify-tests.ts @@ -18,6 +18,7 @@ var server = restify.createServer({ }); server = restify.createServer({ + ca: "test", certificate: "test", key: "test", formatters: {}, @@ -43,7 +44,7 @@ function send(req: restify.Request, res: restify.Response, next: restify.Next) { req.header('key') === 'val'; req.trailer('key', 'val'); req.trailer('key') === 'val'; - + req.accepts('test') === true; req.accepts(['test']) === true; req.acceptsEncoding('test') === true; @@ -343,7 +344,7 @@ client2.get('/str/mcavage', function(err: any, req: any) { }); }); }); - + client.basicAuth('test', 'password'); client2.basicAuth('test', 'password'); diff --git a/rethinkdb/index.d.ts b/rethinkdb/index.d.ts index b07a4e27c6..f375a50fc7 100644 --- a/rethinkdb/index.d.ts +++ b/rethinkdb/index.d.ts @@ -310,9 +310,9 @@ declare module "rethinkdb" { } interface UpdateOptions { - non_atomic: boolean; - durability: string; // 'soft' - return_vals: boolean; // false + nonAtomic?: boolean; + durability?: 'hard' | 'soft'; + returnChanges?: boolean; } interface WriteResult { diff --git a/roslib/index.d.ts b/roslib/index.d.ts index fbb6deff6e..368c190bd6 100644 --- a/roslib/index.d.ts +++ b/roslib/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for roslib.js +// Type definitions for roslib.js 0.18.0 // Project: http://wiki.ros.org/roslibjs -// Definitions by: Stefan Profanter +// Definitions by: Stefan Profanter , Cooper Benson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,6 +11,7 @@ ---------------------------------- */ export = ROSLIB; +export as namespace ROSLIB; declare namespace ROSLIB { export class Ros { @@ -66,6 +67,16 @@ declare namespace ROSLIB { */ callOnConnection(message:any):void; + /** + * Retrieves list of actionlib servers in ROS as an array. + * + * @param callback function with params: + * * action_servers - Array of actionlib servers names + * @param failedCallback - the callback function when the ros call failed (optional). Params: + * * error - the error message reported by ROS + */ + getActionServers(callback:(action_servers:string[]) => void, failedCallback?:(error:any)=>void):void; + /** * Retrieves list of topics in ROS as an array. * @@ -339,7 +350,7 @@ declare namespace ROSLIB { * * provided and other listeners are registered the topic won't * * unsubscribe, just stop emitting to the passed listener */ - unsubscribe(callback?:() => void):void; + unsubscribe(callback?:(callback:(message:Message) => void) => void):void; /** * Registers as a publisher for the topic. diff --git a/roslib/roslib-tests.ts b/roslib/roslib-tests.ts index b67578536a..36b505ea12 100644 --- a/roslib/roslib-tests.ts +++ b/roslib/roslib-tests.ts @@ -48,10 +48,13 @@ var listener = new ROSLIB.Topic({ messageType: 'std_msgs/String' }); -listener.subscribe(function (message:any) { - console.log('Received message on ' + listener.name + ': ' + message.data); +let subscription_callback = function (message:ROSLIB.Message) { + console.log('Received message on ' + listener.name + ': ' + message); listener.unsubscribe(); -}); +} + +listener.subscribe(subscription_callback); +listener.unsubscribe(subscription_callback); // Calling a service // ----------------- diff --git a/route-parser/tsconfig.json b/route-parser/tsconfig.json index 6f14fe510c..89555e3656 100644 --- a/route-parser/tsconfig.json +++ b/route-parser/tsconfig.json @@ -5,7 +5,9 @@ ], "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, @@ -17,4 +19,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} +} \ No newline at end of file diff --git a/route-parser/tslint.json b/route-parser/tslint.json index 192203ab54..377cc837d4 100644 --- a/route-parser/tslint.json +++ b/route-parser/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/rrule/test/commonJs.ts b/rrule/test/commonJs.ts index e6a2c86dac..f193febe91 100644 --- a/rrule/test/commonJs.ts +++ b/rrule/test/commonJs.ts @@ -1,2 +1,2 @@ import { RRule } from "rrule"; -let rule: RRule = new RRule({ freq: RRule.WEEKLY }); +const rule: RRule = new RRule({ freq: RRule.WEEKLY }); diff --git a/rrule/test/rrule.ts b/rrule/test/rrule.ts index 733a8546db..461283c45d 100644 --- a/rrule/test/rrule.ts +++ b/rrule/test/rrule.ts @@ -10,13 +10,13 @@ let rule: RRule = new RRule({ }); let x: Date[]; -let y: string[]; +const y: string[] = []; // Get all occurrence dates (Date instances): x = rule.all(); // Get a slice: -x = rule.between(new Date(2012, 7, 1), new Date(2012, 8, 1)) +x = rule.between(new Date(2012, 7, 1), new Date(2012, 8, 1)); // Get an iCalendar RRULE string representation: // The output can be used with RRule.fromString(). @@ -28,36 +28,36 @@ y.push(rule.toText()); // Get full a string representation of all options, // including the default and inferred ones. -y.push(RRule.optionsToString(rule.options)) +y.push(RRule.optionsToString(rule.options)); // Cherry-pick only some options from an rrule: y.push(RRule.optionsToString({ freq: rule.options.freq, dtstart: rule.options.dtstart, -})) +})); -rule = RRule.fromString("FREQ=WEEKLY;DTSTART=20120201T093000Z") +rule = RRule.fromString("FREQ=WEEKLY;DTSTART=20120201T093000Z"); // This is equivalent -rule = new RRule(RRule.parseString("FREQ=WEEKLY;DTSTART=20120201T093000Z")) +rule = new RRule(RRule.parseString("FREQ=WEEKLY;DTSTART=20120201T093000Z")); -var options = RRule.parseString('FREQ=DAILY;INTERVAL=6') -options.dtstart = new Date(2000, 1, 1) -rule = new RRule(options) +var options = RRule.parseString('FREQ=DAILY;INTERVAL=6'); +options.dtstart = new Date(2000, 1, 1); +rule = new RRule(options); rule = new RRule({ freq: RRule.WEEKLY, count: 23 -}) -y.push(rule.toText()) +}); +y.push(rule.toText()); -rule = RRule.fromText('every day for 3 times') +rule = RRule.fromText('every day for 3 times'); -options = RRule.parseText('every day for 3 times') +options = RRule.parseText('every day for 3 times'); // {freq: 3, count: "3"} -options.dtstart = new Date(2000, 1, 1) -rule = new RRule(options) +options.dtstart = new Date(2000, 1, 1); +rule = new RRule(options); // Test arrays -let multipleInstance = new RRule({freq:3, byhour:[6,12,18]}) +const multipleInstance = new RRule({freq: 3, byhour: [6, 12, 18]}); diff --git a/rrule/tslint.json b/rrule/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/rrule/tslint.json +++ b/rrule/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/rsvp/index.d.ts b/rsvp/index.d.ts new file mode 100644 index 0000000000..a831944a8f --- /dev/null +++ b/rsvp/index.d.ts @@ -0,0 +1,319 @@ +// Type definitions for RSVP 3.3.3 +// Project: https://github.com/tildeio/rsvp.js +// Definitions by: Taylor Brown , Mikael Kohlmyr +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Some of this file was taken from the type definitions for es6-promise https://github.com/borisyankov/DefinitelyTyped/blob/master/es6-promise/es6-promise.d.ts +// Credit for that file goes to: François de Campredon + +// Some of this file was taken from the type definitions for Q : https://github.com/borisyankov/DefinitelyTyped/blob/master/q/Q.d.ts +// Credit for that file goes to: Barrie Nemetchek , Andrew Gaspar , John Reilly + +declare module RSVP { + + interface Thenable { + then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => Thenable): Thenable; + then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => U): Thenable; + then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => void): Thenable; + then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => Thenable): Thenable; + then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => U): Thenable; + then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => void): Thenable; + } + + interface Deferred { + promise: Promise; + resolve(value: T): void; + reject(reason: any): void; + } + + class Promise implements Thenable { + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise is fulfilled with result object passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ + constructor(callback:(resolve:(result?:R) => void, reject:(error:any) => void) => void, label? : string); + + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise will be fulfilled/rejected with the outcome of thenable passed to resolve. + * If you call reject your promise is rejected with the object passed to resolve. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ + constructor(callback:(resolve:(thenable?:Thenable) => void, reject:(error:any) => void) => void, label? : string); + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => Thenable):Promise; + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => U):Promise; + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => void):Promise; + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => Thenable):Promise; + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => U):Promise; + + /** + * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfilled called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + */ + then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => void):Promise; + + /** + * Sugar for promise.then(undefined, onRejected) + * + * @param onRejected called when/if "promise" rejects + */ + catch(onRejected?:(error:any) => Thenable):Promise; + + /** + * Sugar for promise.then(undefined, onRejected) + * + * @param onRejected called when/if "promise" rejects + */ + catch(onRejected?:(error:any) => U):Promise; + + /** + * Sugar for promise.then(undefined, onRejected) + * + * @param onRejected called when/if "promise" rejects + */ + catch(onRejected?:(error:any) => void):Promise; + + finally(finallyCallback: () => any): Promise; + + static all(promises: Thenable[]): Promise; + static all(promises: any[]): Promise; + static race(promises:Promise[]):Promise; + + /** + @method resolve + @param {Any} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + static resolve(object: Thenable): Promise; + static resolve(object: T): Promise; + + /** + @method cast (Deprecated in favor of resolve + @param {Any} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + static cast(object: Thenable, label? : string): Promise; + static cast(object: T, label? : string): Promise; + + /** + `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + */ + static reject(reason?: any): Promise; + } + + interface PromiseState { + state: string /* "fulfilled", "rejected", "pending" */; + value?: T; + reason?: any; + } + + interface InstrumentEvent{ + guid:string; // guid of promise. Must be globally unique, not just within the implementation + childGuid:string; // child of child promise (for chained via `then`) + eventName:string; // one of ['created', 'chained', 'fulfilled', 'rejected'] + detail:any; // fulfillment value or rejection reason, if applicable + label:string; // label passed to promise's constructor + timeStamp:number; // milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now + } + + export function on(eventName : string, callback: (value:any)=>void) : void; + export function on(eventName : "error", errorHandler: (reason:any)=>void): void; + export function on(eventName : "created", listener: (event:InstrumentEvent)=>void): void; + export function on(eventName : "chained", listener: (event:InstrumentEvent)=>void): void; + export function on(eventName : "fulfilled", listener: (event:InstrumentEvent)=>void): void; + export function on(eventName : "rejected", listener: (event:InstrumentEvent)=>void): void; + + export function configure(configName : string, value : any): void; + export function configure(configName : "instrument", shouldInstrument : boolean): void; + + /** + * configure('onerror', handler) is deprecated in favor of on('error', handler) + * @param configName + * @param errorHandler + */ + export function configure(configName : "onerror", errorHandler : (reason:any)=>void): void; + + /** + * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. + * the array passed to all can be a mixture of promise-like objects and other objects. + * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. + */ + export function all(promises: Thenable[]): Promise; + export function all(promises: any[]): Promise; + /** + * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. + * the array passed to all can be a mixture of promise-like objects and other objects. + * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. + * The key difference to the all() function is that both the fulfillment value and the argument to the hash() function + * are object literals. This allows you to simply reference the results directly off the returned object without + * having to remember the initial order like you would with all(). + * + */ + export function hash(promises: { [key: string]: Thenable }): Promise<{ [key: string]: T }>; + export function hash(promises: { [key: string]: any }): Promise<{ [key: string]: T }>; + + /** + `RSVP.map` is similar to JavaScript's native `map` method, except that it + waits for all promises to become fulfilled before running the `mapFn` on + each item in given to `promises`. `RSVP.map` returns a promise that will + become fulfilled with the result of running `mapFn` on the values the promises + become fulfilled with. + */ + export function map(promises: Thenable[], mapFn : (item:any)=>any, label? : string): Promise; + export function map(promises: any[], mapFn : (item:any)=>any, label? : string): Promise; + + + /** + * `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing + * a fail-fast method, it waits until all the promises have returned and + * shows you all the results. This is useful if you want to handle multiple + * promises' failure states together as a set. + */ + export function allSettled(promises: Thenable[]): Promise[]>; + export function allSettled(promises: any[]): Promise[]>; + + /** + * `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object + * instead of an array for its `promises` argument. + * + * Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method, + * but like `RSVP.allSettled`, `hashSettled` waits until all the + * constituent promises have returned and then shows you all the results + * with their states and values/reasons. This is useful if you want to + * handle multiple promises' failure states together as a set. + */ + export function hashSettled(promises: Thenable[]): Promise[]>; + export function hashSettled(promises: any[]): Promise[]>; + + /** + * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. + */ + function race(promises:Promise[]):Promise; + + /** + * `RSVP.denodeify` takes a "node-style" function and returns a function that + * will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the + * browser when you'd prefer to use promises over using callbacks. For example, + * `denodeify` transforms the following: + */ + export function denodeify(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; + + /** + * Favor the Promise Constructor instead (if possible) + * + */ + export function defer(): Deferred; + + + /** + `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + */ + export function reject(reason?: any): Promise; + + /** + `RSVP.Promise.resolve` returns a promise that will become resolved with the + passed `value`. + */ + export function resolve(object: Thenable): Promise; + export function resolve(object: T): Promise; + + /** + * `RSVP.filter` is similar to JavaScript's native `filter` method, except that it + * waits for all promises to become fulfilled before running the `filterFn` on + * each item in given to `promises`. `RSVP.filter` returns a promise that will + * become fulfilled with the result of running `filterFn` on the values the + * promises become fulfilled with. + */ + export function filter(promises: Thenable[], filterFn:(value:any)=>any): Promise; + + /** + `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event + loop in order to aid debugging. + + Promises A+ specifies that any exceptions that occur with a promise must be + caught by the promises implementation and bubbled to the last handler. For + this reason, it is recommended that you always specify a second rejection + handler function to `then`. However, `RSVP.rethrow` will throw the exception + outside of the promise, so it bubbles up to your console if in the browser, + or domain/cause uncaught exception in Node. `rethrow` will also throw the + error again so the error can be handled by the promise per the spec. + */ + export function rethrow(reason : any):void; + +} + + +declare module "rsvp" { + export = RSVP; +} diff --git a/rsvp/rsvp-tests.ts b/rsvp/rsvp-tests.ts new file mode 100644 index 0000000000..50770ba8b6 --- /dev/null +++ b/rsvp/rsvp-tests.ts @@ -0,0 +1,4 @@ +import rsvp = require("rsvp"); + +var promise = new rsvp.Promise(function(resolve:any, rejector:any){ +}); diff --git a/rsvp/tsconfig.json b/rsvp/tsconfig.json new file mode 100644 index 0000000000..58c8e605be --- /dev/null +++ b/rsvp/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", + "rsvp-tests.ts" + ] +} \ No newline at end of file diff --git a/rx-core-binding/index.d.ts b/rx-core-binding/index.d.ts index cf283070e9..54861eb6cb 100644 --- a/rx-core-binding/index.d.ts +++ b/rx-core-binding/index.d.ts @@ -66,7 +66,8 @@ declare namespace Rx { publish(selector: (source: ConnectableObservable) => Observable): Observable; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. - * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, + * then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); @@ -80,7 +81,8 @@ declare namespace Rx { publishValue(selector: (source: ConnectableObservable) => Observable, initialValue: T): Observable; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. - * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, + * then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); diff --git a/rx-core-binding/tslint.json b/rx-core-binding/tslint.json index c169b612d0..5e437d39a2 100644 --- a/rx-core-binding/tslint.json +++ b/rx-core-binding/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - "no-empty-interface": false, - "interface-name": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false, + "interface-name": false, + "no-single-declare-module": false + } } diff --git a/rx-core/index.d.ts b/rx-core/index.d.ts index 62ef95ff80..15b55e93d9 100644 --- a/rx-core/index.d.ts +++ b/rx-core/index.d.ts @@ -50,8 +50,16 @@ declare namespace Rx { distinct(keySelector?: (value: T) => TKey, keySerializer?: (key: TKey) => string): Observable; groupBy(keySelector: (value: T) => TKey, skipElementSelector?: boolean, keySerializer?: (key: TKey) => string): Observable>; groupBy(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, keySerializer?: (key: TKey) => string): Observable>; - groupByUntil(keySelector: (value: T) => TKey, skipElementSelector: boolean, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; - groupByUntil(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; + groupByUntil( + keySelector: (value: T) => TKey, + skipElementSelector: boolean, + durationSelector: (group: GroupedObservable) => Observable, + keySerializer?: (key: TKey) => string): Observable>; + groupByUntil( + keySelector: (value: T) => TKey, + elementSelector: (value: T) => TElement, + durationSelector: (group: GroupedObservable) => Observable, + keySerializer?: (key: TKey) => string): Observable>; } interface ObservableStatic { diff --git a/rx-core/tslint.json b/rx-core/tslint.json index e601518a4d..915d3c55f9 100644 --- a/rx-core/tslint.json +++ b/rx-core/tslint.json @@ -1,9 +1,9 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-empty-interface": false, - "interface-name": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-empty-interface": false, + "interface-name": false, + "no-single-declare-module": false + } } diff --git a/rx-dom/tslint.json b/rx-dom/tslint.json index 7ec0b302e1..8dd3240216 100644 --- a/rx-dom/tslint.json +++ b/rx-dom/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - // this package augments Rx with namespace level functions - // it would be particualrly strange to type these functions differently - "forbidden-types": false - } + "extends": "../tslint.json", + "rules": { + // this package augments Rx with namespace level functions + // it would be particualrly strange to type these functions differently + "forbidden-types": false + } } diff --git a/rx-lite-aggregates/index.d.ts b/rx-lite-aggregates/index.d.ts index d09a4868f2..6dd9c76387 100644 --- a/rx-lite-aggregates/index.d.ts +++ b/rx-lite-aggregates/index.d.ts @@ -12,7 +12,7 @@ declare namespace Rx { aggregate(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; reduce(accumulator: (acc: T, value: T) => T): Observable; - reduce(accumulator: (acc: TAcc, value: T) => TAcc, seed: TAcc): Observable; // TS0.9.5: won't work https://typescript.codeplex.com/discussions/471751 + reduce(accumulator: (acc: TAcc, value: T) => TAcc, seed: TAcc): Observable; any(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; some(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; // alias for any diff --git a/rx-lite-aggregates/tslint.json b/rx-lite-aggregates/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-aggregates/tslint.json +++ b/rx-lite-aggregates/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-async/rx-lite-async-tests.ts b/rx-lite-async/rx-lite-async-tests.ts index a8119fbb82..8c88cc135c 100644 --- a/rx-lite-async/rx-lite-async-tests.ts +++ b/rx-lite-async/rx-lite-async-tests.ts @@ -8,20 +8,20 @@ namespace Rx.Tests.Async { var sch: Rx.IScheduler; function start() { - obsNum = Rx.Observable.start(()=> 10, obsStr, sch); + obsNum = Rx.Observable.start(() => 10, obsStr, sch); obsNum = Rx.Observable.start(() => 10, obsStr); - obsNum = Rx.Observable.start(()=> 10); + obsNum = Rx.Observable.start(() => 10); } function toAsync() { - obsNum = Rx.Observable.toAsync(()=> 1, sch)(); - obsNum = Rx.Observable.toAsync((a1: number)=> a1)(1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number)=> a1 + a2.toFixed(0))("", 1); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date)=> a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); - obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean)=> a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); + obsNum = Rx.Observable.toAsync(() => 1, sch)(); + obsNum = Rx.Observable.toAsync((a1: number) => a1)(1); + obsStr = Rx.Observable.toAsync((a1: string, a2: number) => a1 + a2.toFixed(0))("", 1); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date) => a1 + a2.toFixed(0) + a3.toDateString())("", 1, new Date()); + obsStr = Rx.Observable.toAsync((a1: string, a2: number, a3: Date, a4: boolean) => a1 + a2.toFixed(0) + a3.toDateString() + (a4 ? 1 : 0))("", 1, new Date(), false); } function startAsync() { - var o: Rx.Observable = Rx.Observable.startAsync(() => >{}); + var o: Rx.Observable = Rx.Observable.startAsync(() => > {}); } } diff --git a/rx-lite-async/tslint.json b/rx-lite-async/tslint.json index cfdf2986e5..32344bf0f6 100644 --- a/rx-lite-async/tslint.json +++ b/rx-lite-async/tslint.json @@ -1,6 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "max-line-length": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-backpressure/tslint.json b/rx-lite-backpressure/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/rx-lite-backpressure/tslint.json +++ b/rx-lite-backpressure/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/rx-lite-coincidence/tslint.json b/rx-lite-coincidence/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-coincidence/tslint.json +++ b/rx-lite-coincidence/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-experimental/tslint.json b/rx-lite-experimental/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-experimental/tslint.json +++ b/rx-lite-experimental/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-joinpatterns/tslint.json b/rx-lite-joinpatterns/tslint.json index 587e1d39df..b3684af44b 100644 --- a/rx-lite-joinpatterns/tslint.json +++ b/rx-lite-joinpatterns/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - "interface-name": false, - "no-empty-interface": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "interface-name": false, + "no-empty-interface": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-testing/tslint.json b/rx-lite-testing/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/rx-lite-testing/tslint.json +++ b/rx-lite-testing/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/rx-lite-time/tslint.json b/rx-lite-time/tslint.json index bd7d2217e3..a7c18034d5 100644 --- a/rx-lite-time/tslint.json +++ b/rx-lite-time/tslint.json @@ -1,7 +1,7 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-single-declare-module": false + } } diff --git a/rx-lite-virtualtime/index.d.ts b/rx-lite-virtualtime/index.d.ts index 617282ccc6..d0907c7168 100644 --- a/rx-lite-virtualtime/index.d.ts +++ b/rx-lite-virtualtime/index.d.ts @@ -7,7 +7,7 @@ declare namespace Rx { export interface VirtualTimeScheduler extends Scheduler { - //protected constructor(initialClock: TAbsolute, comparer: (first: TAbsolute, second: TAbsolute) => number); + // protected constructor(initialClock: TAbsolute, comparer: (first: TAbsolute, second: TAbsolute) => number); advanceBy(time: TRelative): void; advanceTo(time: TAbsolute): void; diff --git a/rx-lite-virtualtime/tslint.json b/rx-lite-virtualtime/tslint.json index 587e1d39df..b3684af44b 100644 --- a/rx-lite-virtualtime/tslint.json +++ b/rx-lite-virtualtime/tslint.json @@ -1,8 +1,8 @@ { - "extends": "../tslint.json", - "rules": { - "interface-name": false, - "no-empty-interface": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "interface-name": false, + "no-empty-interface": false, + "no-single-declare-module": false + } } diff --git a/rx-lite/index.d.ts b/rx-lite/index.d.ts index fb5056c478..7e085031aa 100644 --- a/rx-lite/index.d.ts +++ b/rx-lite/index.d.ts @@ -232,7 +232,7 @@ declare namespace Rx { withLatestFrom(souces: (Observable | IPromise)[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; concat(...sources: (Observable | IPromise)[]): Observable; concat(sources: (Observable | IPromise)[]): Observable; - concatAll(): Observable; + concatAll(): T; concatObservable(): Observable; // alias for concatAll concatMap(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat concatMap(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat diff --git a/rx-lite/rx-lite-tests.ts b/rx-lite/rx-lite-tests.ts index 8422bfd9f2..d0f871fcbb 100644 --- a/rx-lite/rx-lite-tests.ts +++ b/rx-lite/rx-lite-tests.ts @@ -54,7 +54,7 @@ namespace Tests.Async { p = p.then(x => x); p = p.then(x => p); p = p.then(undefined, reason => 10); - //p = p.then(undefined, reason => p); + // p = p.then(undefined, reason => p); var ps: Rx.IPromise = p.then(undefined, reason => "error"); ps = p.then(x => ""); @@ -77,17 +77,17 @@ function test_scan() { function test_concatAll() { /* concatAll Example */ var source = Rx.Observable.range(0, 3) - .map(function (x) { return Rx.Observable.range(x, 3); }) + .map(x => Rx.Observable.range(x, 3)) .concatAll(); var subscription = source.subscribe( - function (x) { + x => { console.log('Next: %s', x); }, - function (err) { + err => { console.log('Error: %s', err); }, - function () { + () => { console.log('Completed'); }); } @@ -95,17 +95,17 @@ function test_concatAll() { function test_mergeAll() { /* mergeAll example */ var source = Rx.Observable.range(0, 3) - .map(function (x) { return Rx.Observable.range(x, 3); }) + .map(x => Rx.Observable.range(x, 3)) .mergeAll(); var subscription = source.subscribe( - function (x) { + x => { console.log('Next: %s', x); }, - function (err) { + err => { console.log('Error: %s', err); }, - function () { + () => { console.log('Completed'); }); @@ -117,7 +117,7 @@ function test_publish() { var source = interval .take(2) - .doAction(function (x) { + .doAction(x => { console.log('Side effect'); }); @@ -130,13 +130,13 @@ function test_publish() { function createObserver(tag: string) { return Rx.Observer.create( - function (x) { + x => { console.log('Next: ' + tag + x); }, - function (err) { + err => { console.log('Error: ' + err); }, - function () { + () => { console.log('Completed'); }); } diff --git a/rx-lite/tslint.json b/rx-lite/tslint.json index 9dd4e0d05f..1bec85bd5c 100644 --- a/rx-lite/tslint.json +++ b/rx-lite/tslint.json @@ -1,11 +1,12 @@ { - "extends": "../tslint.json", - "rules": { - "unified-signatures": false, - "no-empty-interface": false, - "forbidden-types": false, - "interface-name": false, - "array-type": false, - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "unified-signatures": false, + "no-empty-interface": false, + "forbidden-types": false, + "interface-name": false, + "array-type": false, + "max-line-length": false, + "no-single-declare-module": false + } } diff --git a/rx/tslint.json b/rx/tslint.json index cfdf2986e5..0b14fdec0d 100644 --- a/rx/tslint.json +++ b/rx/tslint.json @@ -1,6 +1,6 @@ { - "extends": "../tslint.json", - "rules": { - "no-single-declare-module": false - } + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } } diff --git a/sax/index.d.ts b/sax/index.d.ts index c17ebd6928..4c556d8aab 100644 --- a/sax/index.d.ts +++ b/sax/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for sax js +// Type definitions for sax-js 1.x // Project: https://github.com/isaacs/sax-js // Definitions by: Asana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -63,6 +63,7 @@ export declare class SAXParser { strict: boolean; opt: SAXOptions; tag: string; + ENTITIES: {[key: string]: string}; // Events onerror(e: Error): void; diff --git a/sax/sax-tests.ts b/sax/sax-tests.ts index 353ead08e0..4d9a90293d 100644 --- a/sax/sax-tests.ts +++ b/sax/sax-tests.ts @@ -13,6 +13,8 @@ import fs = require("fs"); let parser = sax.parser(/*strict=*/true, opts); + parser.ENTITIES["foo"] = "bar"; + parser.onerror = function(e: Error) { }; diff --git a/scripts/fix-tslint.ts b/scripts/fix-tslint.ts new file mode 100644 index 0000000000..940257e945 --- /dev/null +++ b/scripts/fix-tslint.ts @@ -0,0 +1,50 @@ +// Usage: ts-node fix-tslint.ts + +/// + +import assert = require("assert"); +import * as fs from 'fs'; +import * as path from 'path'; +import JSON = require("comment-json"); + +function repeat(s: string, count: number) { + return Array(count + 1).join(s); +} + +const home = path.join(__dirname, '..'); + +for (const dirName of fs.readdirSync(home)) { + if (dirName.startsWith(".") || dirName === "node_modules" || dirName === "scripts") { + continue; + } + + const dir = path.join(home, dirName); + const stats = fs.lstatSync(dir); + if (stats.isDirectory()) { + fixTslint(dir); + // Also do it for old versions + for (const subdir of fs.readdirSync(dir)) { + if (/^v\d+$/.test(subdir)) { + fixTslint(path.join(dir, subdir)); + } + } + } +} + +function fixTslint(dir: string): void { + const target = path.join(dir, 'tslint.json'); + if (!fs.existsSync(target)) return; + let json = JSON.parse(fs.readFileSync(target, 'utf-8')); + json = fix(json); + const text = Object.keys(json).length === 1 ? '{ "extends": "../tslint.json" }' : JSON.stringify(json, undefined, 4); + fs.writeFileSync(target, text + "\n", "utf-8"); +} + +function fix(config: any): any { + const out: any = {}; + for (const key in config) { + let value = config[key]; + out[key] = value; + } + return out; +} diff --git a/scripts/lint.js b/scripts/lint.js index ea3ec1d778..4d47ce3406 100644 --- a/scripts/lint.js +++ b/scripts/lint.js @@ -12,7 +12,7 @@ if (pkg.includes("/") && pkg[pkg.length - 1] !== "/") { tslintPath = path.join("..", tslintPath); } -const cmd = `node ${tslintPath}/lib/tslint-cli --format stylish "**/*.d.ts"`; +const cmd = `node ${tslintPath}/lib/tslint-cli --format stylish "**/*.ts"`; console.log(cmd); try { diff --git a/scripts/new-package.js b/scripts/new-package.js deleted file mode 100644 index 360fdff85f..0000000000 --- a/scripts/new-package.js +++ /dev/null @@ -1,121 +0,0 @@ -/// -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const http_1 = require("http"); -const fs_1 = require("fs"); -const path = require("path"); -const newPackageName = process.argv[2]; -if (!newPackageName) { - throw new Error("Usage: node scripts/new-package.js new-package-name"); -} -run().catch(e => { - console.error(e); - process.exit(1); -}); -function run() { - return __awaiter(this, void 0, void 0, function* () { - const files = [ - ["index.d.ts", yield getIndex()], - [`${newPackageName}-tests.ts`, ""], - ["tsconfig.json", `${JSON.stringify(getTSConfig(), undefined, 4)}\n`], - ["tslint.json", '{ "extends": "../tslint.json" }\n'], - ]; - try { - yield pify1(fs_1.mkdir, newPackageName); - yield Promise.all(files.map(([name, text]) => write(name, text))); - } - catch (e) { - if (e.code === "EEXIST") { - console.warn(`Module “${newPackageName}” already exists!`); - } - else { - console.error(`Error creating module files: ${e}\nCleaning Up.`); - yield Promise.all(files.map(([name]) => rm(name))); - yield pify1(fs_1.rmdir, newPackageName); - } - process.exit(1); - } - }); -} -function getIndex() { - return __awaiter(this, void 0, void 0, function* () { - let version = "x.x"; - let 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.)"; - try { - const reg = JSON.parse(yield loadString(`http://registry.npmjs.org/${newPackageName}`)); - const { latest } = reg["dist-tags"]; - const { homepage } = reg.versions[latest]; - version = latest.split(".").slice(0, 2).join("."); - if (homepage !== undefined) - project = homepage; - } - catch (e) { - console.warn(`Warning: could not retrieve version/homepage information: ${e.message}`); - } - return `// Type definitions for ${newPackageName} ${version} -// Project: ${project} -// Definitions by: My Self -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -Fill the header in! -`; - }); -} -function getTSConfig() { - return { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - `${newPackageName}-tests.ts` - ] - }; -} -function write(name, content) { - return new Promise((resolve, reject) => { - fs_1.writeFile(path.join(newPackageName, name), content, err => err ? reject(err) : resolve()); - }); -} -function rm(name) { - return pify1(fs_1.unlink, path.join(newPackageName, name)).catch((e) => { - if (e.code === "ENOENT") - return; - throw e; - }); -} -function pify1(fn, arg) { - return new Promise((resolve, reject) => { - fn(arg, err => err ? reject(err) : resolve()); - }); -} -function loadString(url) { - return new Promise((resolve, reject) => { - http_1.get(url, (res) => { - if (res.statusCode !== 200) { - return reject(new Error(`HTTP Error ${res.statusCode}: ${http_1.STATUS_CODES[res.statusCode || 500]} for ${url}`)); - } - let rawData = ""; - res.on("data", chunk => rawData += chunk); - res.on("end", () => resolve(rawData)); - }).on("error", e => reject(e)); - }); -} diff --git a/scripts/new-package.ts b/scripts/new-package.ts deleted file mode 100644 index 6e9384c896..0000000000 --- a/scripts/new-package.ts +++ /dev/null @@ -1,131 +0,0 @@ -/// - -import { get, STATUS_CODES } from "http" -import { mkdir, writeFile, unlink, rmdir } from "fs" -import * as path from "path" - -interface Package { - name: string - description: string - version: string - homepage?: string -} - -interface Registry { - name: string - description: string - "dist-tags": { latest: string } - versions: { [version: string]: Package } -} - -const newPackageName = process.argv[2] -if (!newPackageName) { - throw new Error("Usage: node scripts/new-package.js new-package-name") -} - -run().catch(e => { - console.error(e) - process.exit(1) -}) - -async function run() { - const files: [string, string][] = [ - ["index.d.ts", await getIndex()], - [`${newPackageName}-tests.ts`, ""], - ["tsconfig.json", `${JSON.stringify(getTSConfig(), undefined, 4)}\n`], - ["tslint.json", '{ "extends": "../tslint.json" }\n'], - ] - - try { - await pify1(mkdir, newPackageName) - await Promise.all(files.map(([name, text]) => write(name, text))) - } catch (e) { - if (e.code === "EEXIST") { - console.warn(`Module “${newPackageName}” already exists!`) - } else { - console.error(`Error creating module files: ${e}\nCleaning Up.`) - await Promise.all(files.map(([name]) => rm(name))) - await pify1(rmdir, newPackageName) - } - process.exit(1) - } -} - -async function getIndex() { - let version = "x.x" - let 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.)" - try { - const reg: Registry = JSON.parse(await loadString(`http://registry.npmjs.org/${newPackageName}`)) - - const { latest } = reg["dist-tags"] - const { homepage } = reg.versions[latest] - - version = latest.split(".").slice(0, 2).join(".") - if (homepage !== undefined) project = homepage - } catch (e) { - console.warn(`Warning: could not retrieve version/homepage information: ${e.message}`) - } - - return `// Type definitions for ${newPackageName} ${version} -// Project: ${project} -// Definitions by: My Self -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -Fill the header in! -` -} - -function getTSConfig() { - return { - "compilerOptions": { - "module": "commonjs", - "lib": ["es6"], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - `${newPackageName}-tests.ts` - ] - } -} - -function write(name: string, content: string) { - return new Promise((resolve, reject) => { - writeFile(path.join(newPackageName, name), content, err => err ? reject(err): resolve()) - }) -} - -function rm(name: string) { - return pify1(unlink, path.join(newPackageName, name)).catch((e: NodeJS.ErrnoException) => { - if (e.code === "ENOENT") return - throw e - }) -} - -function pify1 void) => void, A>(fn: F, arg: A) { - return new Promise((resolve, reject) => { - fn(arg, err => err ? reject(err): resolve()) - }) -} - -function loadString(url: string): Promise { - return new Promise((resolve, reject) => { - get(url, (res) => { - if (res.statusCode !== 200) { - return reject(new Error(`HTTP Error ${res.statusCode}: ${STATUS_CODES[res.statusCode || 500]} for ${url}`)) - } - let rawData = "" - res.on("data", chunk => rawData += chunk) - res.on("end", () => resolve(rawData)) - }).on("error", e => reject(e)) - }) -} diff --git a/selenium-webdriver/chrome.d.ts b/selenium-webdriver/chrome.d.ts index 2ecff8d2f8..ce26566f02 100644 --- a/selenium-webdriver/chrome.d.ts +++ b/selenium-webdriver/chrome.d.ts @@ -1,418 +1,414 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace chrome { +/** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ +export class Driver extends webdriver.WebDriver { /** - * Creates a new WebDriver client for Chrome. - * - * @extends {webdriver.WebDriver} + * @param {(webdriver.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + * @constructor */ - class Driver extends webdriver.WebDriver { - /** - * @param {(webdriver.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@link getDefaultService default service} by default. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - * @constructor - */ - constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); - } - - interface IOptionsValues { - args: string[]; - binary?: string; - detach: boolean; - extensions: string[]; - localState?: any; - logFile?: string; - prefs?: any; - } - - interface IPerfLoggingPrefs { - enableNetwork: boolean; - enablePage: boolean; - enableTimeline: boolean; - tracingCategories: string; - bufferUsageReportingInterval: number; - } - - /** - * Class for managing ChromeDriver specific options. - */ - class Options { - /** - * @constructor - */ - constructor(); - - /** - * Extracts the ChromeDriver specific options from the given capabilities - * object. - * @param {!webdriver.Capabilities} capabilities The capabilities object. - * @return {!Options} The ChromeDriver options. - */ - static fromCapabilities(capabilities: webdriver.Capabilities): Options; - - - /** - * Add additional command line arguments to use when launching the Chrome - * browser. Each argument may be specified with or without the '--' prefix - * (e.g. '--foo' and 'foo'). Arguments with an associated value should be - * delimited by an '=': 'foo=bar'. - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: string[]): Options; - - - /** - * List of Chrome command line switches to exclude that ChromeDriver by default - * passes when starting Chrome. Do not prefix switches with '--'. - * - * @param {...(string|!Array)} var_args The switches to exclude. - * @return {!Options} A self reference. - */ - excludeSwitches(...var_args: string[]): Options; - - - /** - * Add additional extensions to install when launching Chrome. Each extension - * should be specified as the path to the packed CRX file, or a Buffer for an - * extension. - * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The - * extensions to add. - * @return {!Options} A self reference. - */ - addExtensions(...var_args: any[]): Options; - - - /** - * Sets the path to the Chrome binary to use. On Mac OS X, this path should - * reference the actual Chrome executable, not just the application binary - * (e.g. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'). - * - * The binary path be absolute or relative to the chromedriver server - * executable, but it must exist on the machine that will launch Chrome. - * - * @param {string} path The path to the Chrome binary to use. - * @return {!Options} A self reference. - */ - setChromeBinaryPath(path: string): Options; - - - /** - * Sets whether to leave the started Chrome browser running if the controlling - * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is - * called. - * @param {boolean} detach Whether to leave the browser running if the - * chromedriver service is killed before the session. - * @return {!Options} A self reference. - */ - detachDriver(detach: boolean): Options; - - - /** - * Sets the user preferences for Chrome's user profile. See the 'Preferences' - * file in Chrome's user data directory for examples. - * @param {!Object} prefs Dictionary of user preferences to use. - * @return {!Options} A self reference. - */ - setUserPreferences(prefs: any): Options; - - - /** - * Sets the logging preferences for the new session. - * @param {!webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the performance logging preferences. Options include: - * - * - `enableNetwork`: Whether or not to collect events from Network domain. - * - `enablePage`: Whether or not to collect events from Page domain. - * - `enableTimeline`: Whether or not to collect events from Timeline domain. - * Note: when tracing is enabled, Timeline domain is implicitly disabled, - * unless `enableTimeline` is explicitly set to true. - * - `tracingCategories`: A comma-separated string of Chrome tracing categories - * for which trace events should be collected. An unspecified or empty - * string disables tracing. - * - `bufferUsageReportingInterval`: The requested number of milliseconds - * between DevTools trace buffer usage events. For example, if 1000, then - * once per second, DevTools will report how full the trace buffer is. If a - * report indicates the buffer usage is 100%, a warning will be issued. - * - * @param {{enableNetwork: boolean, - * enablePage: boolean, - * enableTimeline: boolean, - * tracingCategories: string, - * bufferUsageReportingInterval: number}} prefs The performance - * logging preferences. - * @return {!Options} A self reference. - */ - setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; - - - /** - * Sets preferences for the 'Local State' file in Chrome's user data - * directory. - * @param {!Object} state Dictionary of local state preferences. - * @return {!Options} A self reference. - */ - setLocalState(state: any): Options; - - - /** - * Sets the name of the activity hosting a Chrome-based Android WebView. This - * option must be set to connect to an [Android WebView]( - * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) - * - * @param {string} name The activity name. - * @return {!Options} A self reference. - */ - androidActivity(name: string): Options; - - - /** - * Sets the device serial number to connect to via ADB. If not specified, the - * ChromeDriver will select an unused device at random. An error will be - * returned if all devices already have active sessions. - * - * @param {string} serial The device serial number to connect to. - * @return {!Options} A self reference. - */ - androidDeviceSerial(serial: string): Options; - - - /** - * Configures the ChromeDriver to launch Chrome on Android via adb. This - * function is shorthand for - * {@link #androidPackage options.androidPackage('com.android.chrome')}. - * @return {!Options} A self reference. - */ - androidChrome(): Options; - - - /** - * Sets the package name of the Chrome or WebView app. - * - * @param {?string} pkg The package to connect to, or `null` to disable Android - * and switch back to using desktop Chrome. - * @return {!Options} A self reference. - */ - androidPackage(pkg: string): Options; - - - /** - * Sets the process name of the Activity hosting the WebView (as given by `ps`). - * If not specified, the process name is assumed to be the same as - * {@link #androidPackage}. - * - * @param {string} processName The main activity name. - * @return {!Options} A self reference. - */ - androidProcess(processName: string): Options; - - - /** - * Sets whether to connect to an already-running instead of the specified - * {@linkplain #androidProcess app} instead of launching the app with a clean - * data directory. - * - * @param {boolean} useRunning Whether to connect to a running instance. - * @return {!Options} A self reference. - */ - androidUseRunningApp(useRunning: boolean): Options; - - - /** - * Sets the path to Chrome's log file. This path should exist on the machine - * that will launch Chrome. - * @param {string} path Path to the log file to use. - * @return {!Options} A self reference. - */ - setChromeLogFile(path: string): Options; - - - /** - * Sets the directory to store Chrome minidumps in. This option is only - * supported when ChromeDriver is running on Linux. - * @param {string} path The directory path. - * @return {!Options} A self reference. - */ - setChromeMinidumpPath(path: string): Options; - - - /** - * Configures Chrome to emulate a mobile device. For more information, refer - * to the ChromeDriver project page on [mobile emulation][em]. Configuration - * options include: - * - * - `deviceName`: The name of a pre-configured [emulated device][devem] - * - `width`: screen width, in pixels - * - `height`: screen height, in pixels - * - `pixelRatio`: screen pixel ratio - * - * __Example 1: Using a Pre-configured Device__ - * - * let options = new chrome.Options().setMobileEmulation( - * {deviceName: 'Google Nexus 5'}); - * - * let driver = new chrome.Driver(options); - * - * __Example 2: Using Custom Screen Configuration__ - * - * let options = new chrome.Options().setMobileEmulation({ - * width: 360, - * height: 640, - * pixelRatio: 3.0 - * }); - * - * let driver = new chrome.Driver(options); - * - * - * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation - * [devem]: https://developer.chrome.com/devtools/docs/device-mode - * - * @param {?({deviceName: string}| - * {width: number, height: number, pixelRatio: number})} config The - * mobile emulation configuration, or `null` to disable emulation. - * @return {!Options} A self reference. - */ - setMobileEmulation(config: any): Options; - - /** - * Sets the proxy settings for the new session. - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts this options instance to a {@link webdriver.Capabilities} object. - * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge - * these options into, if any. - * @return {!webdriver.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - } - - /** - * Creates {@link remote.DriverService} instances that manage a ChromeDriver - * server. - */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the chromedriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the chromedriver - * cannot be found on the PATH. - * @constructor - */ - constructor(opt_exe?: string); - - /** - * Sets the port to start the ChromeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - - /** - * Sets which port adb is listening to. _The ChromeDriver will connect to adb - * if an {@linkplain Options#androidPackage Android session} is requested, but - * adb **must** be started beforehand._ - * - * @param {number} port Which port adb is running on. - * @return {!ServiceBuilder} A self reference. - */ - setAdbPort(port: number): ServiceBuilder; - - - /** - * Sets the path of the log file the driver should log to. If a log file is - * not specified, the driver will log to stderr. - * @param {string} path Path of the log file to use. - * @return {!ServiceBuilder} A self reference. - */ - loggingTo(path: string): ServiceBuilder; - - - /** - * Enables verbose logging. - * @return {!ServiceBuilder} A self reference. - */ - enableVerboseLogging(): ServiceBuilder; - - - /** - * Sets the number of threads the driver should use to manage HTTP requests. - * By default, the driver will use 4 threads. - * @param {number} n The number of threads to use. - * @return {!ServiceBuilder} A self reference. - */ - setNumHttpThreads(n: number): ServiceBuilder; - - - /** - * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). - * By default, the driver will accept commands relative to '/'. - * @param {string} path The base path to use. - * @return {!ServiceBuilder} A self reference. - */ - setUrlBasePath(path: string): ServiceBuilder; - - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} config The - * configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: { [key: string]: string }): ServiceBuilder; - - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; - } - - /** - * Returns the default ChromeDriver service. If such a service has not been - * configured, one will be constructed using the default configuration for - * a ChromeDriver executable found on the system PATH. - * @return {!remote.DriverService} The default ChromeDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Sets the default service to use for new ChromeDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): void; + constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } -export = chrome; +interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; +} + +interface IPerfLoggingPrefs { + enableNetwork: boolean; + enablePage: boolean; + enableTimeline: boolean; + tracingCategories: string; + bufferUsageReportingInterval: number; +} + +/** + * Class for managing ChromeDriver specific options. + */ +export class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the '--' prefix + * (e.g. '--foo' and 'foo'). Arguments with an associated value should be + * delimited by an '=': 'foo=bar'. + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * List of Chrome command line switches to exclude that ChromeDriver by default + * passes when starting Chrome. Do not prefix switches with '--'. + * + * @param {...(string|!Array)} var_args The switches to exclude. + * @return {!Options} A self reference. + */ + excludeSwitches(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the 'Preferences' + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the performance logging preferences. Options include: + * + * - `enableNetwork`: Whether or not to collect events from Network domain. + * - `enablePage`: Whether or not to collect events from Page domain. + * - `enableTimeline`: Whether or not to collect events from Timeline domain. + * Note: when tracing is enabled, Timeline domain is implicitly disabled, + * unless `enableTimeline` is explicitly set to true. + * - `tracingCategories`: A comma-separated string of Chrome tracing categories + * for which trace events should be collected. An unspecified or empty + * string disables tracing. + * - `bufferUsageReportingInterval`: The requested number of milliseconds + * between DevTools trace buffer usage events. For example, if 1000, then + * once per second, DevTools will report how full the trace buffer is. If a + * report indicates the buffer usage is 100%, a warning will be issued. + * + * @param {{enableNetwork: boolean, + * enablePage: boolean, + * enableTimeline: boolean, + * tracingCategories: string, + * bufferUsageReportingInterval: number}} prefs The performance + * logging preferences. + * @return {!Options} A self reference. + */ + setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; + + + /** + * Sets preferences for the 'Local State' file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the name of the activity hosting a Chrome-based Android WebView. This + * option must be set to connect to an [Android WebView]( + * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) + * + * @param {string} name The activity name. + * @return {!Options} A self reference. + */ + androidActivity(name: string): Options; + + + /** + * Sets the device serial number to connect to via ADB. If not specified, the + * ChromeDriver will select an unused device at random. An error will be + * returned if all devices already have active sessions. + * + * @param {string} serial The device serial number to connect to. + * @return {!Options} A self reference. + */ + androidDeviceSerial(serial: string): Options; + + + /** + * Configures the ChromeDriver to launch Chrome on Android via adb. This + * function is shorthand for + * {@link #androidPackage options.androidPackage('com.android.chrome')}. + * @return {!Options} A self reference. + */ + androidChrome(): Options; + + + /** + * Sets the package name of the Chrome or WebView app. + * + * @param {?string} pkg The package to connect to, or `null` to disable Android + * and switch back to using desktop Chrome. + * @return {!Options} A self reference. + */ + androidPackage(pkg: string): Options; + + + /** + * Sets the process name of the Activity hosting the WebView (as given by `ps`). + * If not specified, the process name is assumed to be the same as + * {@link #androidPackage}. + * + * @param {string} processName The main activity name. + * @return {!Options} A self reference. + */ + androidProcess(processName: string): Options; + + + /** + * Sets whether to connect to an already-running instead of the specified + * {@linkplain #androidProcess app} instead of launching the app with a clean + * data directory. + * + * @param {boolean} useRunning Whether to connect to a running instance. + * @return {!Options} A self reference. + */ + androidUseRunningApp(useRunning: boolean): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets which port adb is listening to. _The ChromeDriver will connect to adb + * if an {@linkplain Options#androidPackage Android session} is requested, but + * adb **must** be started beforehand._ + * + * @param {number} port Which port adb is running on. + * @return {!ServiceBuilder} A self reference. + */ + setAdbPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). + * By default, the driver will accept commands relative to '/'. + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Sets the default service to use for new ChromeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/edge.d.ts b/selenium-webdriver/edge.d.ts index fd59756c3d..b18a959700 100644 --- a/selenium-webdriver/edge.d.ts +++ b/selenium-webdriver/edge.d.ts @@ -1,129 +1,124 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace edge { - - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@linkplain #getDefaultService default service} by default. - * @param {promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); /** - * Class for managing MicrosoftEdgeDriver specific options. + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override */ - class Options { - - /** - * Extracts the MicrosoftEdgeDriver specific options from the given - * capabilities object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The MicrosoftEdgeDriver options. - */ - static fromCapabilities(cap: webdriver.Capabilities): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Sets the page load strategy for Edge. - * Supported values are 'normal', 'eager', and 'none'; - * - * @param {string} pageLoadStrategy The page load strategy to use. - * @return {!Options} A self reference. - */ - setPageLoadStrategy(pageLoadStrategy: string): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - - /** - * Creates {@link remote.DriverService} instances that manage a - * MicrosoftEdgeDriver server in a child process. - */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the MicrosoftEdgeDriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the - * MicrosoftEdgeDriver cannot be found on the PATH. - */ - constructor(opt_exe?: string); - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - /** - * Sets the port to start the MicrosoftEdgeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; - } - - /** - * Returns the default MicrosoftEdgeDriver service. If such a service has - * not been configured, one will be constructed using the default configuration - * for an MicrosoftEdgeDriver executable found on the system PATH. - * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Sets the default service to use for new MicrosoftEdgeDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): void; + setFileDetector(): void; } -export = edge; +/** + * Class for managing MicrosoftEdgeDriver specific options. + */ +export class Options { + + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets the page load strategy for Edge. + * Supported values are 'normal', 'eager', and 'none'; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/executors.d.ts b/selenium-webdriver/executors.d.ts index 6cded31fec..c7bf15ef8d 100644 --- a/selenium-webdriver/executors.d.ts +++ b/selenium-webdriver/executors.d.ts @@ -1,15 +1,11 @@ import * as webdriver from './index'; -declare namespace executors { - /** - * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param {(string|!promise.Promise)} url The server's URL, - * or a promise that will resolve to that URL. - * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the - * client to use. - * @returns {!./lib/command.Executor} The new command executor. - */ - function createExecutor(url: string | webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; -} - -export = executors; +/** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param {(string|!promise.Promise)} url The server's URL, + * or a promise that will resolve to that URL. + * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the + * client to use. + * @returns {!./lib/command.Executor} The new command executor. + */ +export function createExecutor(url: string | webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; diff --git a/selenium-webdriver/firefox.d.ts b/selenium-webdriver/firefox.d.ts index 25542f144f..7678c404ce 100644 --- a/selenium-webdriver/firefox.d.ts +++ b/selenium-webdriver/firefox.d.ts @@ -1,257 +1,253 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace firefox { +/** + * Manages a Firefox subprocess configured for use with WebDriver. + */ +export class Binary { /** - * Manages a Firefox subprocess configured for use with WebDriver. + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); - - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } + constructor(opt_exe?: string); /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); + addArguments(...var_args: string[]): void; - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; - - - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; - - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; - } /** - * Configuration options for the FirefoxDriver. + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. */ - class Options { - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string | any): Options; + launch(profile: string): webdriver.promise.Promise; - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string | any): Options; - - /** - * Sets the logging preferences for the new session. - * @param {logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the proxy to use. - * - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Sets whether to use Mozilla's Marionette to drive the browser. - * - * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver - */ - useMarionette(marionette: any): Options; - - /** - * Converts these options to a {@link capabilities.Capabilities} instance. - * - * @return {!capabilities.Capabilities} A new capabilities object. - */ - toCapabilities(): webdriver.Capabilities; - } /** - * @return {string} . - * @throws {Error} + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. */ - function findWires(): string; - - /** - * @param {(string|!Binary)} binary . - * @return {!remote.DriverService} . - */ - function createWiresService(binary: string | any): remote.DriverService; - - /** - * @param {(Profile|string)} profile The profile to prepare. - * @param {number} port The port the FirefoxDriver should listen on. - * @return {!Promise} a promise for the path to the profile directory. - */ - function prepareProfile(profile: string | any, port: number): any; - - /** - * A WebDriver client for Firefox. - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(Options|capabilities.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash - * object. - * @param {promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - */ - constructor(opt_config?: Options | webdriver.Capabilities | Object, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } + kill(): webdriver.promise.Promise; } -export = firefox; +/** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ +export class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; +} + +/** + * Configuration options for the FirefoxDriver. + */ +export class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string | any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string | any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; +} + +/** + * @return {string} . + * @throws {Error} + */ +export function findWires(): string; + +/** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ +export function createWiresService(binary: string | any): remote.DriverService; + +/** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ +export function prepareProfile(profile: string | any, port: number): any; + +/** + * A WebDriver client for Firefox. + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options | webdriver.Capabilities | Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} diff --git a/selenium-webdriver/http.d.ts b/selenium-webdriver/http.d.ts index b4ade88430..a0a25a7955 100644 --- a/selenium-webdriver/http.d.ts +++ b/selenium-webdriver/http.d.ts @@ -1,156 +1,152 @@ import * as webdriver from './index'; -declare namespace http { +/** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ +export function headersToString(headers: any): string; + +/** + * Represents a HTTP request message. This class is a 'partial' request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ +export class HttpRequest { /** - * Converts a headers map to a HTTP header block string. - * @param {!Map} headers The map to convert. - * @return {string} The headers as a string. + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. */ - function headersToString(headers: any): string; + constructor(method: string, path: string, opt_data?: Object); - /** - * Represents a HTTP request message. This class is a 'partial' request and only - * defines the path on the server to send a request to. It is each client's - * responsibility to build the full URL for the final request. - * @final - */ - class HttpRequest { - /** - * @param {string} method The HTTP method to use for the request. - * @param {string} path The path on the server to send the request to. - * @param {Object=} opt_data This request's non-serialized JSON payload data. - */ - constructor(method: string, path: string, opt_data?: Object); - - /** @override */ - toString(): string; - } - - /** - * Represents a HTTP response message. - * @final - */ - class HttpResponse { - /** - * @param {number} status The response code. - * @param {!Object} headers The response headers. All header names - * will be converted to lowercase strings for consistent lookups. - * @param {string} body The response body. - */ - constructor(status: number, headers: Object, body: string); - - /** @override */ - toString(): string; - } - - - function post(path: string): any; - function del(path: string): any; - function get(path: string): any; - function resource(method: string, path: string): any; - - /** - * A basic HTTP client used to send messages to a remote end. - */ - class HttpClient { - /** - * @param {string} serverUrl URL for the WebDriver server to send commands to. - * @param {http.Agent=} opt_agent The agent to use for each request. - * Defaults to `http.globalAgent`. - * @param {?string=} opt_proxy The proxy to use for the connection to the - * server. Default is to use no proxy. - */ - constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); - - /** - * Sends a request to the server. The client will automatically follow any - * redirects returned by the server, fulfilling the returned promise with the - * final response. - * - * @param {!HttpRequest} httpRequest The request to send. - * @return {!promise.Promise} A promise that will be fulfilled - * with the server's response. - */ - send(httpRequest: HttpRequest): webdriver.promise.Promise; - } - - /** - * Sends a single HTTP request. - * @param {!Object} options The request options. - * @param {function(!HttpResponse)} onOk The function to call if the - * request succeeds. - * @param {function(!Error)} onError The function to call if the request fails. - * @param {?string=} opt_data The data to send with the request. - * @param {?string=} opt_proxy The proxy server to use for the request. - */ - function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; - - /** - * A command executor that communicates with the server using HTTP + JSON. - * - * By default, each instance of this class will use the legacy wire protocol - * from [Selenium project][json]. The executor will automatically switch to the - * [W3C wire protocol][w3c] if the remote end returns a compliant response to - * a new session command. - * - * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol - * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html - * - * @implements {cmd.Executor} - */ - class Executor { - /** - * @param {!HttpClient} client The client to use for sending requests to the - * server. - */ - constructor(client: HttpClient); - - /** - * Defines a new command for use with this executor. When a command is sent, - * the {@code path} will be preprocessed using the command's parameters; any - * path segments prefixed with ':' will be replaced by the parameter of the - * same name. For example, given '/person/:name' and the parameters - * '{name: 'Bob'}', the final command path will be '/person/Bob'. - * - * @param {string} name The command name. - * @param {string} method The HTTP method to use when sending this command. - * @param {string} path The path to send the command to, relative to - * the WebDriver server's command root and of the form - * '/path/:variable/segment'. - */ - defineCommand(name: string, method: string, path: string): void; - - /** @override */ - execute(command: any): any; - } - - /** - * @param {string} str . - * @return {?} . - */ - function tryParse(str: string): any; - - /** - * Callback used to parse {@link HttpResponse} objects from a - * {@link HttpClient}. - * @param {!HttpResponse} httpResponse The HTTP response to parse. - * @param {boolean} w3c Whether the response should be processed using the - * W3C wire protocol. - * @return {{value: ?}} The parsed response. - * @throws {WebDriverError} If the HTTP response is an error. - */ - function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; - - /** - * Builds a fully qualified path using the given set of command parameters. Each - * path segment prefixed with ':' will be replaced by the value of the - * corresponding parameter. All parameters spliced into the path will be - * removed from the parameter map. - * @param {string} path The original resource path. - * @param {!Object<*>} parameters The parameters object to splice into the path. - * @return {string} The modified path. - */ - function buildPath(path: string, parameters: Object): string; + /** @override */ + toString(): string; } -export = http; +/** + * Represents a HTTP response message. + * @final + */ +export class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; +} + + +export function post(path: string): any; +export function del(path: string): any; +export function get(path: string): any; +export function resource(method: string, path: string): any; + +/** + * A basic HTTP client used to send messages to a remote end. + */ +export class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; +} + +/** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ +export function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + +/** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ +export class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ':' will be replaced by the parameter of the + * same name. For example, given '/person/:name' and the parameters + * '{name: 'Bob'}', the final command path will be '/person/Bob'. + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * '/path/:variable/segment'. + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; +} + +/** + * @param {string} str . + * @return {?} . + */ +export function tryParse(str: string): any; + +/** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ +export function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + +/** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ +export function buildPath(path: string, parameters: Object): string; diff --git a/selenium-webdriver/ie.d.ts b/selenium-webdriver/ie.d.ts index 5d9b51c64d..9e8cab2457 100644 --- a/selenium-webdriver/ie.d.ts +++ b/selenium-webdriver/ie.d.ts @@ -1,211 +1,205 @@ import * as webdriver from './index'; -declare namespace ie { +/** + * A WebDriver client for Microsoft's Internet Explorer. + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow); /** - * A WebDriver client for Microsoft's Internet Explorer. + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override */ - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {promise.ControlFlow=} opt_flow The control flow to use, - * or {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } - - /** - * Class for managing IEDriver specific options. - */ - class Options { - constructor(); - - /** - * Extracts the IEDriver specific options from the given capabilities - * object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The IEDriver options. - */ - static fromCapabilities(caps: webdriver.Capabilities): Options; - - /** - * Whether to disable the protected mode settings check when the session is - * created. Disbling this setting may lead to significant instability as the - * browser may become unresponsive/hang. Only 'best effort' support is provided - * when using this capability. - * - * For more information, refer to the IEDriver's - * [required system configuration](http://goo.gl/eH0Yi3). - * - * @param {boolean} ignoreSettings Whether to ignore protected mode settings. - * @return {!Options} A self reference. - */ - introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; - - /** - * Indicates whether to skip the check that the browser's zoom level is set to - * 100%. - * - * @param {boolean} ignore Whether to ignore the browser's zoom level settings. - * @return {!Options} A self reference. - */ - ignoreZoomSetting(ignore: boolean): Options; - - /** - * Sets the initial URL loaded when IE starts. This is intended to be used with - * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in - * the proper Protected Mode zone. Setting this option may cause browser - * instability or flaky and unresponsive code. Only 'best effort' support is - * provided when using this option. - * - * @param {string} url The initial browser URL. - * @return {!Options} A self reference. - */ - initialBrowserUrl(url: string): Options; - - /** - * Configures whether to enable persistent mouse hovering (true by default). - * Persistent hovering is achieved by continuously firing mouse over events at - * the last location the mouse cursor has been moved to. - * - * @param {boolean} enable Whether to enable persistent hovering. - * @return {!Options} A self reference. - */ - enablePersistentHover(enable: boolean): Options; - - /** - * Configures whether the driver should attempt to remove obsolete - * {@linkplain webdriver.WebElement WebElements} from its internal cache on - * page navigation (true by default). Disabling this option will cause the - * driver to run with a larger memory footprint. - * - * @param {boolean} enable Whether to enable element reference cleanup. - * @return {!Options} A self reference. - */ - enableElementCacheCleanup(enable: boolean): Options; - - /** - * Configures whether to require the IE window to have input focus before - * performing any user interactions (i.e. mouse or keyboard events). This - * option is disabled by default, but delivers much more accurate interaction - * events when enabled. - * - * @param {boolean} require Whether to require window focus. - * @return {!Options} A self reference. - */ - requireWindowFocus(require: boolean): Options; - - /** - * Configures the timeout, in milliseconds, that the driver will attempt to - * located and attach to a newly opened instance of Internet Explorer. The - * default is zero, which indicates waiting indefinitely. - * - * @param {number} timeout How long to wait for IE. - * @return {!Options} A self reference. - */ - browserAttachTimeout(timeout: number): Options; - - /** - * Configures whether to launch Internet Explorer using the CreateProcess API. - * If this option is not specified, IE is launched using IELaunchURL, if - * available. For IE 8 and above, this option requires the TabProcGrowth - * registry value to be set to 0. - * - * @param {boolean} force Whether to use the CreateProcess API. - * @return {!Options} A self reference. - */ - forceCreateProcessApi(force: boolean): Options; - - /** - * Specifies command-line switches to use when launching Internet Explorer. - * This is only valid when used with {@link #forceCreateProcessApi}. - * - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: Array): Options; - - /** - * Configures whether proxies should be configured on a per-process basis. If - * not set, setting a {@linkplain #setProxy proxy} will configure the system - * proxy. The default behavior is to use the system proxy. - * - * @param {boolean} enable Whether to enable per-process proxy settings. - * @return {!Options} A self reference. - */ - usePerProcessProxy(enable: boolean): Options; - - /** - * Configures whether to clear the cache, cookies, history, and saved form data - * before starting the browser. _Using this capability will clear session data - * for all running instances of Internet Explorer, including those started - * manually._ - * - * @param {boolean} cleanSession Whether to clear all session data on startup. - * @return {!Options} A self reference. - */ - ensureCleanSession(cleanSession: boolean): Options; - - /** - * Sets the path to the log file the driver should log to. - * @param {string} file The log file path. - * @return {!Options} A self reference. - */ - setLogFile(file: string): Options; - - /** - * Sets the IEDriverServer's logging {@linkplain Level level}. - * @param {Level} level The logging level. - * @return {!Options} A self reference. - */ - setLogLevel(level: webdriver.logging.Level): Options; - - /** - * Sets the IP address of the driver's host adapter. - * @param {string} host The IP address to use. - * @return {!Options} A self reference. - */ - setHost(host: string): Options; - - /** - * Sets the path of the temporary data directory to use. - * @param {string} path The log file path. - * @return {!Options} A self reference. - */ - setExtractPath(path: string): Options; - - /** - * Sets whether the driver should start in silent mode. - * @param {boolean} silent Whether to run in silent mode. - * @return {!Options} A self reference. - */ - silent(silent: boolean): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - + setFileDetector(): void; } -export = ie; +/** + * Class for managing IEDriver specific options. + */ +export class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only 'best effort' support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only 'best effort' support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} diff --git a/selenium-webdriver/index.d.ts b/selenium-webdriver/index.d.ts index 17fba9ceae..39d56d7d5b 100644 --- a/selenium-webdriver/index.d.ts +++ b/selenium-webdriver/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Selenium WebDriverJS 2.53.1 +// Type definitions for Selenium WebDriverJS 2.53 // Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver // Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,2090 +10,1004 @@ import * as ie from './ie'; import * as opera from './opera'; import * as safari from './safari'; -declare namespace webdriver { +export namespace error { + class IError extends Error { + constructor(opt_error?: string); - namespace error { - class IError extends Error { - constructor(opt_error?: string); - - code(): number; - } - - /** - * The base WebDriver error type. This error type is only used directly when a - * more appropriate category is not defined for the offending error. - */ - class WebDriverError extends IError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An attempt was made to select an element that cannot be selected. - */ - class ElementNotSelectableError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element command could not be completed because the element is not visible - * on the page. - */ - class ElementNotVisibleError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The arguments passed to a command are either invalid or malformed. - */ - class InvalidArgumentError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An illegal attempt was made to set a cookie under a different domain than - * the current page. - */ - class InvalidCookieDomainError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The coordinates provided to an interactions operation are invalid. - */ - class InvalidElementCoordinatesError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element command could not be completed because the element is in an - * invalid state, e.g. attempting to click an element that is no longer attached - * to the document. - */ - class InvalidElementStateError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Argument was an invalid selector. - */ - class InvalidSelectorError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Occurs when a command is directed to a session that does not exist. - */ - class NoSuchSessionError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An error occurred while executing JavaScript supplied by the user. - */ - class JavascriptError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The target for mouse interaction is not in the browser’s viewport and cannot - * be brought into that viewport. - */ - class MoveTargetOutOfBoundsError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An attempt was made to operate on a modal dialog when one was not open. - */ - class NoSuchAlertError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element could not be located on the page using the given search - * parameters. - */ - class NoSuchElementError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to switch to a frame could not be satisfied because the frame - * could not be found. - */ - class NoSuchFrameError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to switch to a window could not be satisfied because the window - * could not be found. - */ - class NoSuchWindowError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A script did not complete before its timeout expired. - */ - class ScriptTimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A new session could not be created. - */ - class SessionNotCreatedError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An element command failed because the referenced element is no longer - * attached to the DOM. - */ - class StaleElementReferenceError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * An operation did not completErrorCodee before its timeout expired. - */ - class TimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to set a cookie’s value could not be satisfied. - */ - class UnableToSetCookieError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A screen capture operation was not possible. - */ - class UnableToCaptureScreenError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A modal dialog was open, blocking this operation. - */ - class UnexpectedAlertOpenError extends WebDriverError { - /** - * @param {string=} opt_error the error message, if any. - * @param {string=} opt_text the text of the open dialog, if available. - */ - constructor(opt_error?: string, opt_text?: string); - - /** - * @return {(string|undefined)} The text displayed with the unhandled alert, - * if available. - */ - getAlertText(): string; - } - - /** - * A command could not be executed because the remote end is not aware of it. - */ - class UnknownCommandError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The requested command matched a known URL but did not match an method for - * that URL. - */ - class UnknownMethodError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Reports an unsupport operation. - */ - class UnsupportedOperationError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - } - - namespace logging { - - /** - * A hash describing log preferences. - * @typedef {Object.} - */ - class Preferences { - setLevel(type: string, level: Level | string | number): void; - toJSON(): { [key: string]: string }; - } - - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - - /** - * Common log types. - * @enum {string} - */ - var Type: IType; - - /** - * Defines a message level that may be used to control logging output. - * - * @final - */ - class Level { - name_: string; - value_: number; - /** - * @param {string} name the level's name. - * @param {number} level the level's numeric value. - */ - constructor(name: string, level: number); - - /** @override */ - toString(): string; - - /** This logger's name. */ - name: string; - - /** The numeric log level. */ - value: number; - - /** - * Indicates no log messages should be recorded. - * @const - */ - static OFF: Level; - /** - * Log messages with a level of `1000` or higher. - * @const - */ - static SEVERE: Level; - /** - * Log messages with a level of `900` or higher. - * @const - */ - static WARNING: Level; - /** - * Log messages with a level of `800` or higher. - * @const - */ - static INFO: Level; - /** - * Log messages with a level of `700` or higher. - * @const - */ - static DEBUG: Level; - /** - * Log messages with a level of `500` or higher. - * @const - */ - static FINE: Level; - /** - * Log messages with a level of `400` or higher. - * @const - */ - static FINER: Level; - /** - * Log messages with a level of `300` or higher. - * @const - */ - static FINEST: Level; - /** - * Indicates all log messages should be recorded. - * @const - */ - static ALL: Level; - } - - /** - * Converts a level name or value to a {@link webdriver.logging.Level} value. - * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} - * will be returned. - * @param {(number|string)} nameOrValue The log level name, or value, to - * convert . - * @return {!webdriver.logging.Level} The converted level. - */ - function getLevel(nameOrValue: string | number): Level; - - interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; - } - - /** - * A single log entry. - */ - class Entry { - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: Level | string | number, message: string, opt_timestamp?: number, opt_type?: string | IType); - - /** @type {!webdriver.logging.Level} */ - level: Level; - - /** @type {string} */ - message: string; - - /** @type {number} */ - timestamp: number; - - /** @type {string} */ - type: string; - - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; - } - - /** - * An object used to log debugging messages. Loggers use a hierarchical, - * dot-separated naming scheme. For instance, 'foo' is considered the parent of - * the 'foo.bar' and an ancestor of 'foo.bar.baz'. - * - * Each logger may be assigned a {@linkplain #setLevel log level}, which - * controls which level of messages will be reported to the - * {@linkplain #addHandler handlers} attached to this instance. If a log level - * is not explicitly set on a logger, it will inherit its parent. - * - * This class should never be directly instantiated. Instead, users should - * obtain logger references using the {@linkplain ./logging.getLogger() - * getLogger()} function. - * - * @final - */ - class Logger { - /** - * @param {string} name the name of this logger. - * @param {Level=} opt_level the initial level for this logger. - */ - constructor(name: string, opt_level?: Level); - - /** @private {string} */ - name_: string; - /** @private {Level} */ - level_: Level; - /** @private {Logger} */ - parent_: Logger; - /** @private {Set} */ - handlers_: any; - - /** @return {string} the name of this logger. */ - getName(): string; - - /** - * @param {Level} level the new level for this logger, or `null` if the logger - * should inherit its level from its parent logger. - */ - setLevel(level: Level): void; - - /** @return {Level} the log level for this logger. */ - getLevel(): Level; - - /** - * @return {!Level} the effective level for this logger. - */ - getEffectiveLevel(): Level; - - /** - * @param {!Level} level the level to check. - * @return {boolean} whether messages recorded at the given level are loggable - * by this instance. - */ - isLoggable(level: Level): boolean; - - /** - * Adds a handler to this logger. The handler will be invoked for each message - * logged with this instance, or any of its descendants. - * - * @param {function(!Entry)} handler the handler to add. - */ - addHandler(handler: any): void; - - /** - * Removes a handler from this logger. - * - * @param {function(!Entry)} handler the handler to remove. - * @return {boolean} whether a handler was successfully removed. - */ - removeHandler(handler: any): void; - - /** - * Logs a message at the given level. The message may be defined as a string - * or as a function that will return the message. If a function is provided, - * it will only be invoked if this logger's - * {@linkplain #getEffectiveLevel() effective log level} includes the given - * `level`. - * - * @param {!Level} level the level at which to log the message. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - log(level: Level, loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.SEVERE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - severe(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.WARNING} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - warning(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.INFO} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - info(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.DEBUG} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - debug(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.FINE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - fine(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.FINER} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finer(loggable: string | Function): void; - - /** - * Logs a message at the {@link Level.FINEST} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finest(loggable: string | Function): void; - } - - /** - * Maintains a collection of loggers. - * - * @final - */ - class LogManager { - /** - * Retrieves a named logger, creating it in the process. This function will - * implicitly create the requested logger, and any of its parents, if they - * do not yet exist. - * - * @param {string} name the logger's name. - * @return {!Logger} the requested logger. - */ - getLogger(name: string): Logger; - - /** - * Creates a new logger. - * - * @param {string} name the logger's name. - * @param {!Logger} parent the logger's parent. - * @return {!Logger} the new logger. - * @private - */ - createLogger_(name: string, parent: Logger): Logger; - } - } - - namespace promise { - //region Functions - - /** - * Given an array of promises, will return a promise that will be fulfilled - * with the fulfillment values of the input array's values. If any of the - * input array's promises are rejected, the returned promise will be rejected - * with the same reason. - * - * @param {!Array<(T|!ManagedPromise)>} arr An array of - * promises to wait on. - * @return {!ManagedPromise>} A promise that is - * fulfilled with an array containing the fulfilled values of the - * input array, or rejected with the same reason as the first - * rejected value. - * @template T - */ - function all(arr: Array>): Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@link webdriver.promise.when}, except it does not return a new promise. - * @param {*} value The value to observe. - * @param {Function} callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - */ - function asap(value: any, callback: Function, opt_errback?: Function): void; - - /** - * @return {!webdriver.promise.ControlFlow} The currently active control flow. - */ - function controlFlow(): ControlFlow; - - /** - * Creates a new control flow. The provided callback will be invoked as the - * first task within the new flow, with the flow as its sole argument. Returns - * a promise that resolves to the callback result. - * @param {function(!ControlFlow)} callback The entry point - * to the newly created flow. - * @return {!ManagedPromise} A promise that resolves to the callback - * result. - */ - function createFlow(callback: (flow: ControlFlow) => R): Promise; - - /** - * Determines whether a {@code value} should be treated as a promise. - * Any object whose 'then' property is a function will be considered a promise. - * - * @param {*} value The value to test. - * @return {boolean} Whether the value is a promise. - */ - function isPromise(value: any): boolean; - - /** - * Tests is a function is a generator. - * @param {!Function} fn The function to test. - * @return {boolean} Whether the function is a generator. - */ - function isGenerator(fn: Function): boolean; - - /** - * Creates a promise that will be resolved at a set time in the future. - * @param {number} ms The amount of time, in milliseconds, to wait before - * resolving the promise. - * @return {!ManagedPromise} The promise. - */ - function delayed(ms: number): Promise; - - /** - * Calls a function for each element in an array, and if the function returns - * true adds the element to a new array. - * - * If the return value of the filter function is a promise, this function - * will wait for it to be fulfilled before determining whether to insert the - * element into the new array. - * - * If the filter function throws or returns a rejected promise, the promise - * returned by this function will be rejected with the same reason. Only the - * first failure will be reported; all subsequent errors will be silently - * ignored. - * - * @param {!(Array|ManagedPromise>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ( - * boolean|ManagedPromise)} fn The function - * to call for each element in the array. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function filter(arr: Array | Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; - - /** - * Creates a new deferred object. - * @return {!webdriver.promise.Deferred} The new deferred object. - */ - function defer(): Deferred; - - /** - * Creates a promise that has been resolved with the given value. - * @param {T=} opt_value The resolved value. - * @return {!ManagedPromise} The resolved promise. - * @template T - */ - function fulfilled(opt_value?: T): Promise; - - /** - * Calls a function for each element in an array and inserts the result into a - * new array, which is used as the fulfillment value of the promise returned - * by this function. - * - * If the return value of the mapping function is a promise, this function - * will wait for it to be fulfilled before inserting it into the new array. - * - * If the mapping function throws or returns a rejected promise, the - * promise returned by this function will be rejected with the same reason. - * Only the first failure will be reported; all subsequent errors will be - * silently ignored. - * - * @param {!(Array|ManagedPromise>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ?} fn The - * function to call for each element in the array. This function should - * expect three arguments (the element, the index, and the array itself. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function map(arr: Array | Promise>, fn: (self: any, type: any, index: number, array: T[]) => any, opt_self?: any): Promise - - /** - * Creates a promise that has been rejected with the given reason. - * @param {*=} opt_reason The rejection reason; may be any value, but is - * usually an Error or a string. - * @return {!ManagedPromise} The rejected promise. - * @template T - */ - function rejected(opt_reason?: any): Promise; - - /** - * Wraps a function that expects a node-style callback as its final - * argument. This callback expects two arguments: an error value (which will be - * null if the call succeeded), and the success value as the second argument. - * The callback will the resolve or reject the returned promise, based on its - * arguments. - * @param {!Function} fn The function to wrap. - * @param {...?} var_args The arguments to apply to the function, excluding the - * final callback. - * @return {!ManagedPromise} A promise that will be resolved with the - * result of the provided function's callback. - */ - function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; - - /** - * Consumes a {@code GeneratorFunction}. Each time the generator yields a - * promise, this function will wait for it to be fulfilled before feeding the - * fulfilled value back into {@code next}. Likewise, if a yielded promise is - * rejected, the rejection error will be passed to {@code throw}. - * - * __Example 1:__ the Fibonacci Sequence. - * - * promise.consume(function* fibonacci() { - * var n1 = 1, n2 = 1; - * for (var i = 0; i < 4; ++i) { - * var tmp = yield n1 + n2; - * n1 = n2; - * n2 = tmp; - * } - * return n1 + n2; - * }).then(function(result) { - * console.log(result); // 13 - * }); - * - * __Example 2:__ a generator that throws. - * - * promise.consume(function* () { - * yield promise.delayed(250).then(function() { - * throw Error('boom'); - * }); - * }).catch(function(e) { - * console.log(e.toString()); // Error: boom - * }); - * - * @param {!Function} generatorFn The generator function to execute. - * @param {Object=} opt_self The object to use as 'this' when invoking the - * initial generator. - * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!ManagedPromise} A promise that will resolve to the - * generator's final result. - * @throws {TypeError} If the given function is not a generator. - */ - function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; - - /** - * Registers an observer on a promised {@code value}, returning a new promise - * that will be resolved when the value is. If {@code value} is not a promise, - * then the return promise will be immediately resolved. - * @param {*} value The value to observe. - * @param {Function=} opt_callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - * @return {!ManagedPromise} A new promise. - */ - function when(value: T | Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - - /** - * Returns a promise that will be resolved with the input value in a - * fully-resolved state. If the value is an array, each element will be fully - * resolved. Likewise, if the value is an object, all keys will be fully - * resolved. In both cases, all nested arrays and objects will also be - * fully resolved. All fields are resolved in place; the returned promise will - * resolve on {@code value} and not a copy. - * - * Warning: This function makes no checks against objects that contain - * cyclical references: - * - * var value = {}; - * value['self'] = value; - * promise.fullyResolved(value); // Stack overflow. - * - * @param {*} value The value to fully resolve. - * @return {!ManagedPromise} A promise for a fully resolved version - * of the input value. - */ - function fullyResolved(value: any): Promise; - - /** - * Changes the default flow to use when no others are active. - * @param {!ControlFlow} flow The new default flow. - * @throws {Error} If the default flow is not currently active. - */ - function setDefaultFlow(flow: ControlFlow): void; - - //endregion - - /** - * Error used when the computation of a promise is cancelled. - */ - class CancellationError extends Error { - /** - * @param {string=} opt_msg The cancellation message. - */ - constructor(opt_msg?: string); - } - - interface IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. - * - * @param {?(function(T): (R|IThenable))=} opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param {?(function(*): (R|IThenable))=} opt_errback - * The function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => any): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - } - - /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ - class Thenable implements IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. - * - * @param {?(function(T): (R|IThenable))=} opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param {?(function(*): (R|IThenable))=} opt_errback - * The function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => R | IThenable): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } finally { - * cleanUp(); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().finally(cleanUp); - * - * __Note:__ similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - * - * try { - * throw Error('one'); - * } finally { - * throw Error('two'); // Hides Error: one - * } - * - * promise.rejected(Error('one')) - * .finally(function() { - * throw Error('two'); // Hides Error: one - * }); - * - * @param {function(): (R|IThenable)} callback The function to call when - * this promise is resolved. - * @return {!ManagedPromise} A promise that will be fulfilled - * with the callback result. - * @template R - */ - finally(callback: Function): Promise; - - /** - * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function - * will also ensure the prototype's {@code then} function is exported from - * compiled code. - * @param {function(new: Thenable, ...?)} ctor The - * constructor whose prototype to modify. - */ - static addImplementation(ctor: Function): void; - - /** - * Checks if an object has been tagged for implementing the Thenable - * interface as defined by {@link Thenable.addImplementation}. - * @param {*} object The object to test. - * @return {boolean} Whether the object is an implementation of the Thenable - * interface. - */ - static isImplementation(object: any): boolean; - } - - interface IFulfilledCallback { - (value: T | IThenable | Thenable | void): void; - } - - interface IRejectedCallback { - (reason: any): void; - } - - /** - * Represents the eventual value of a completed operation. Each promise may be - * in one of three states: pending, fulfilled, or rejected. Each promise starts - * in the pending state and may make a single transition to either a - * fulfilled or rejected state, at which point the promise is considered - * resolved. - * - * @implements {promise.Thenable} - * @template T - * @see http://promises-aplus.github.io/promises-spec/ - */ - class Promise implements IThenable { - /** - * @param {function( - * function((T|IThenable|Thenable)=), - * function(*=))} resolver - * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback - * functions, one for fulfilling the promise and another for rejecting it. - * @param {ControlFlow=} opt_flow The control flow - * this instance was created under. Defaults to the currently active flow. - */ - constructor(resolver: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); - - //region Methods - - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. - * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *

-       *   // Synchronous API:
-       *   try {
-       *     doSynchronousWork();
-       *   } catch (ex) {
-       *     console.error(ex);
-       *   }
-       *
-       *   // Asynchronous promise API:
-       *   doAsynchronousWork().thenCatch(function(ex) {
-       *     console.error(ex);
-       *   });
-       * 
- * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - thenCatch(errback: (error: any) => any): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *

-       *   // Synchronous API:
-       *   try {
-       *     doSynchronousWork();
-       *   } finally {
-       *     cleanUp();
-       *   }
-       *
-       *   // Asynchronous promise API:
-       *   doAsynchronousWork().thenFinally(cleanUp);
-       * 
- * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *

-       *   try {
-       *     throw Error('one');
-       *   } finally {
-       *     throw Error('two');  // Hides Error: one
-       *   }
-       *
-       *   webdriver.promise.rejected(Error('one'))
-       *       .thenFinally(function() {
-       *         throw Error('two');  // Hides Error: one
-       *       });
-       * 
- * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: Function): Promise; - - //endregion - } - - /** - * Represents a value that will be resolved at some point in the future. This - * class represents the protected 'producer' half of a Promise - each Deferred - * has a {@code promise} property that may be returned to consumers for - * registering callbacks, reserving the ability to resolve the deferred to the - * producer. - * - *

If this Deferred is rejected and there are no listeners registered before - * the next turn of the event loop, the rejection will be passed to the - * {@link webdriver.promise.ControlFlow} as an unhandled failure. - * - *

If this Deferred is cancelled, the cancellation reason will be forward to - * the Deferred's canceller function (if provided). The canceller may return a - * truth-y value to override the reason provided for rejection. - * - * @extends {webdriver.promise.Promise} - */ - class Deferred extends Promise { - //region Constructors - - /** - * - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow - * this instance was created under. This should only be provided during - * unit tests. - * @constructor - */ - constructor(opt_flow?: ControlFlow); - - //endregion - - static State_: { - BLOCKED: number; - PENDING: number; - REJECTED: number; - RESOLVED: number; - }; - - //region Properties - - /** - * The consumer promise for this instance. Provides protected access to the - * callback registering functions. - * @type {!webdriver.promise.Promise} - */ - promise: Promise; - - //endregion - - //region Methods - - /** - * Rejects this promise. If the error is itself a promise, this instance will - * be chained to it and be rejected with the error's resolved value. - * @param {*=} opt_error The rejection reason, typically either a - * {@code Error} or a {@code string}. - */ - reject(opt_error?: any): void; - errback(opt_error?: any): void; - - /** - * Resolves this promise with the given value. If the value is itself a - * promise and not a reference to this deferred, this instance will wait for - * it before resolving. - * @param {*=} opt_value The resolved value. - */ - fulfill(opt_value?: T): void; - - /** - * Removes all of the listeners previously registered on this deferred. - * @throws {Error} If this deferred has already been resolved. - */ - removeAll(): void; - - //endregion - } - - interface IControlFlowTimer { - clearInterval: (ms: number) => void; - clearTimeout: (ms: number) => void; - setInterval: (fn: Function, ms: number) => number; - setTimeout: (fn: Function, ms: number) => number; - } - - interface IEventType { - /** Emitted when all tasks have been successfully executed. */ - IDLE: string; - - /** Emitted when a ControlFlow has been reset. */ - RESET: string; - - /** Emitted whenever a new task has been scheduled. */ - SCHEDULE_TASK: string; - - /** - * Emitted whenever a control flow aborts due to an unhandled promise - * rejection. This event will be emitted along with the offending rejection - * reason. Upon emitting this event, the control flow will empty its task - * queue and revert to its initial state. - */ - UNCAUGHT_EXCEPTION: string; - } - - /** - * Handles the execution of scheduled tasks, each of which may be an - * asynchronous operation. The control flow will ensure tasks are executed in - * the ordered scheduled, starting each task only once those before it have - * completed. - * - * Each task scheduled within this flow may return a - * {@link webdriver.promise.Promise} to indicate it is an asynchronous - * operation. The ControlFlow will wait for such promises to be resolved before - * marking the task as completed. - * - * Tasks and each callback registered on a {@link webdriver.promise.Promise} - * will be run in their own ControlFlow frame. Any tasks scheduled within a - * frame will take priority over previously scheduled tasks. Furthermore, if any - * of the tasks in the frame fail, the remainder of the tasks in that frame will - * be discarded and the failure will be propagated to the user through the - * callback/task's promised result. - * - * Each time a ControlFlow empties its task queue, it will fire an - * {@link webdriver.promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, - * whenever the flow terminates due to an unhandled error, it will remove all - * remaining tasks in its queue and fire an - * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION - * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the - * flow, the error will be rethrown to the global error handler. - * - * @extends {EventEmitter} - * @final - */ - class ControlFlow extends EventEmitter { - /** - * @constructor - */ - constructor(); - - /** - * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. - * @enum {string} - */ - static EventType: IEventType; - - /** - * Returns a string representation of this control flow, which is its current - * {@link #getSchedule() schedule}, sans task stack traces. - * @return {string} The string representation of this contorl flow. - * @override - */ - toString(): string; - - /** - * Resets this instance, clearing its queue and removing all event listeners. - */ - reset(): void; - - /** - * Generates an annotated string describing the internal state of this control - * flow, including the currently executing as well as pending tasks. If - * {@code opt_includeStackTraces === true}, the string will include the - * stack trace from when each task was scheduled. - * @param {string=} opt_includeStackTraces Whether to include the stack traces - * from when each task was scheduled. Defaults to false. - * @return {string} String representation of this flow's internal state. - */ - getSchedule(opt_includeStackTraces?: boolean): string; - - /** - * Schedules a task for execution. If there is nothing currently in the - * queue, the task will be executed in the next turn of the event loop. If - * the task function is a generator, the task will be executed using - * {@link webdriver.promise.consume}. - * - * @param {function(): (T|promise.Promise)} fn The function to - * call to start the task. If the function returns a - * {@link webdriver.promise.Promise}, this instance will wait for it to be - * resolved before starting the next task. - * @param {string=} opt_description A description of the task. - * @return {!promise.Promise} A promise that will be resolved - * with the result of the action. - * @template T - */ - execute(fn: () => (T | Promise), opt_description?: string): Promise; - - /** - * Inserts a {@code setTimeout} into the command queue. This is equivalent to - * a thread sleep in a synchronous programming language. - * - * @param {number} ms The timeout delay, in milliseconds. - * @param {string=} opt_description A description to accompany the timeout. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the result of the action. - */ - timeout(ms: number, opt_description?: string): Promise; - - /** - * Schedules a task that shall wait for a condition to hold. Each condition - * function may return any value, but it will always be evaluated as a boolean. - * - * Condition functions may schedule sub-tasks with this instance, however, - * their execution time will be factored into whether a wait has timed out. - * - * In the event a condition returns a Promise, the polling loop will wait for - * it to be resolved before evaluating whether the condition has been satisfied. - * The resolution time for a promise is factored into whether a wait has timed - * out. - * - * If the condition function throws, or returns a rejected promise, the - * wait task will fail. - * - * If the condition is defined as a promise, the flow will wait for it to - * settle. If the timeout expires before the promise settles, the promise - * returned by this function will be rejected. - * - * If this function is invoked with `timeout === 0`, or the timeout is omitted, - * the flow will wait indefinitely for the condition to be satisfied. - * - * @param {(!promise.Promise|function())} condition The condition to poll, - * or a promise to wait on. - * @param {number=} opt_timeout How long to wait, in milliseconds, for the - * condition to hold before timing out. If omitted, the flow will wait - * indefinitely. - * @param {string=} opt_message An optional error message to include if the - * wait times out; defaults to the empty string. - * @return {!promise.Promise} A promise that will be fulfilled - * when the condition has been satisified. The promise shall be rejected if - * the wait times out waiting for the condition. - * @throws {TypeError} If condition is not a function or promise or if timeout - * is not a number >= 0. - * @template T - */ - wait(condition: Promise | Function, opt_timeout?: number, opt_message?: string): Promise; - } - } - - namespace until { - /** - * Defines a condition to - */ - class Condition { - /** - * @param {string} message A descriptive error message. Should complete the - * sentence 'Waiting [...]' - * @param {function(!webdriver.WebDriver): OUT} fn The condition function to - * evaluate on each iteration of the wait loop. - * @constructor - */ - constructor(message: string, fn: (webdriver: WebDriver) => any); - - /** @return {string} A description of this condition. */ - description(): string; - - /** @type {function(!webdriver.WebDriver): OUT} */ - fn(webdriver: WebDriver): any; - } - - /** - * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as - * - * 1. a numeric index into - * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) - * for the currently selected frame. - * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - * 3. a locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - * - * Upon successful resolution of this condition, the driver will be left - * focused on the new frame. - * - * @param {!(number|./webdriver.WebElement|By| - * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame - * The frame identifier. - * @return {!Condition} A new condition. - */ - function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; - - /** - * Creates a condition that waits for an alert to be opened. Upon success, the - * returned promise will be fulfilled with the handle for the opened alert. - * - * @return {!Condition} The new condition. - */ - function alertIsPresent(): Condition; - - /** - * Creates a condition that will wait for the given element to be disabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsDisabled(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be enabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsEnabled(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be deselected. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsNotSelected(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be in the DOM, - * yet not visible to the user. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsNotVisible(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to be selected. - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsSelected(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the given element to become visible. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsVisible(element: WebElement): Condition; - - /** - * Creates a condition that will loop until an element is - * {@link ./webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(By|Function)} locator The locator to use. - * @return {!until.Condition.} The new condition. - */ - function elementLocated(locator: By | Function): Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to contain the given - * substring. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} substr The substring to search for. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextContains(element: WebElement, substr: string): Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match the given - * {@code text} exactly. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} text The expected text. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextIs(element: WebElement, text: string): Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match a regular - * expression. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextMatches(element: WebElement, regex: RegExp): Condition; - - /** - * Creates a condition that will loop until at least one element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.>} The new - * condition. - */ - function elementsLocated(locator: By | Function): Condition; - - /** - * Creates a condition that will wait for the given element to become stale. An - * element is considered stale once it is removed from the DOM, or a new page - * has loaded. - * - * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition} The new condition. - */ - function stalenessOf(element: WebElement): Condition; - - /** - * Creates a condition that will wait for the current page's title to contain - * the given substring. - * - * @param {string} substr The substring that should be present in the page - * title. - * @return {!until.Condition.} The new condition. - */ - function titleContains(substr: string): Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given value. - * - * @param {string} title The expected page title. - * @return {!until.Condition} The new condition. - */ - function titleIs(title: string): Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given regular expression. - * - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - */ - function titleMatches(regex: RegExp): Condition; - } - - interface ILocation { - x: number; - y: number; - } - - interface ISize { - width: number; - height: number; - } - - interface IButton { - LEFT: string; - MIDDLE: string; - RIGHT: string; + code(): number; } /** - * Representations of pressable keys that aren't text. These are stored in - * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to - * http://www.google.com.au/search?&q=unicode+pua&btnG=Search - * + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to select an element that cannot be selected. + */ + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } +} + +export namespace logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, level: Level | string | number): void; + toJSON(): { [key: string]: string }; + } + + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + + /** + * Common log types. * @enum {string} */ - var Button: IButton; - - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: string; - - NUMPAD0: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; - - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; - - COMMAND: string; // Apple command key - META: string; // alias for Windows key - - /** - * Simulate pressing many keys at once in a 'chord'. Takes a sequence of - * keys or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resulting string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - */ - chord: (...var_args: Array) => string; - } + var Type: IType; /** - * Representations of pressable keys that aren't text. These are stored in - * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to - * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * Defines a message level that may be used to control logging output. * - * @enum {string} - */ - var Key: IKey; - - /** - * Class for defining sequences of complex user interactions. Each sequence - * will not be executed until {@link #perform} is called. - * - * Example: - * - * new ActionSequence(driver). - * keyDown(Key.SHIFT). - * click(element1). - * click(element2). - * dragAndDrop(element3, element4). - * keyUp(Key.SHIFT). - * perform(); - * - */ - class ActionSequence { - - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The driver instance to use. - * @constructor - */ - constructor(driver: WebDriver); - - //endregion - - //region Methods - - /** - * Executes this action sequence. - * @return {!webdriver.promise.Promise} A promise that will be resolved once - * this sequence has completed. - */ - perform(): webdriver.promise.Promise; - - /** - * Moves the mouse. The location to move to may be specified in terms of the - * mouse's current location, an offset relative to the top-left corner of an - * element, or an element (in which case the middle of the element is used). - * - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in - * pixels. - * @param {{x: number, y: number}=} opt_offset If the target {@code location} - * is defined as a {@link ./webdriver.WebElement}, this parameter defines - * an offset within that element. The offset should be specified in pixels - * relative to the top-left corner of the element's bounding box. If - * omitted, the element's center will be used as the target offset. - * @return {!ActionSequence} A self reference. - */ - mouseMove(location: WebElement | ILocation, opt_offset?: ILocation): ActionSequence; - - /** - * Presses a mouse button. The mouse button will not be released until - * {@link #mouseUp} is called, regardless of whether that call is made in this - * sequence or another. The behavior for out-of-order events (e.g. mouseDown, - * click) is undefined. - * - * If an element is provided, the mouse will first be moved to the center - * of that element. This is equivalent to: - * - * sequence.mouseMove(element).mouseDown() - * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - mouseDown(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; - - /** - * Releases a mouse button. Behavior is undefined for calling this function - * without a previous call to {@link #mouseDown}. - * - * If an element is provided, the mouse will first be moved to the center - * of that element. This is equivalent to: - * - * sequence.mouseMove(element).mouseUp() - * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - mouseUp(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; - - /** - * Convenience function for performing a 'drag and drop' manuever. The target - * element may be moved to the location of another element, or by an offset (in - * pixels). - * - * @param {!./webdriver.WebElement} element The element to drag. - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in - * pixels. - * @return {!ActionSequence} A self reference. - */ - dragAndDrop(element: WebElement, location: WebElement | ILocation): ActionSequence; - - /** - * Clicks a mouse button. - * - * If an element is provided, the mouse will first be moved to the center - * of that element. This is equivalent to: - * - * sequence.mouseMove(element).click() - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - click(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; - - /** - * Double-clicks a mouse button. - * - * If an element is provided, the mouse will first be moved to the center of - * that element. This is equivalent to: - * - * sequence.mouseMove(element).doubleClick() - * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either - * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor - * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the - * first argument. - * @return {!ActionSequence} A self reference. - */ - doubleClick(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; - - /** - * Performs a modifier key press. The modifier key is not released - * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be - * targetted at the currently focused element. - * @param {!webdriver.Key} key The modifier key to push. Must be one of - * {ALT, CONTROL, SHIFT, COMMAND, META}. - * @return {!webdriver.ActionSequence} A self reference. - * @throws {Error} If the key is not a valid modifier key. - */ - keyDown(key: string): ActionSequence; - - /** - * Performs a modifier key release. The release is targetted at the currently - * focused element. - * @param {!webdriver.Key} key The modifier key to release. Must be one of - * {ALT, CONTROL, SHIFT, COMMAND, META}. - * @return {!webdriver.ActionSequence} A self reference. - * @throws {Error} If the key is not a valid modifier key. - */ - keyUp(key: string): ActionSequence; - - /** - * Simulates typing multiple keys. Each modifier key encountered in the - * sequence will not be released until it is encountered again. All key events - * will be targeted at the currently focused element. - * - * @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args - * The keys to type. - * @return {!ActionSequence} A self reference. - * @throws {Error} If the key is not a valid modifier key. - */ - sendKeys(...var_args: Array>): ActionSequence; - - //endregion - } - - - /** - * Class for defining sequences of user touch interactions. Each sequence - * will not be executed until {@link #perform} is called. - * - * Example: - * - * new webdriver.TouchSequence(driver). - * tapAndHold({x: 0, y: 0}). - * move({x: 3, y: 4}). - * release({x: 10, y: 10}). - * perform(); - */ - class TouchSequence { - /* - * @param {!webdriver.WebDriver} driver The driver instance to use. - * @constructor - */ - constructor(driver: WebDriver); - - - /** - * Executes this action sequence. - * @return {!webdriver.promise.Promise} A promise that will be resolved once - * this sequence has completed. - */ - perform(): webdriver.promise.Promise; - - - /** - * Taps an element. - * - * @param {!webdriver.WebElement} elem The element to tap. - * @return {!webdriver.TouchSequence} A self reference. - */ - tap(elem: WebElement): TouchSequence; - - - /** - * Double taps an element. - * - * @param {!webdriver.WebElement} elem The element to double tap. - * @return {!webdriver.TouchSequence} A self reference. - */ - doubleTap(elem: WebElement): TouchSequence; - - - /** - * Long press on an element. - * - * @param {!webdriver.WebElement} elem The element to long press. - * @return {!webdriver.TouchSequence} A self reference. - */ - longPress(elem: WebElement): TouchSequence; - - - /** - * Touch down at the given location. - * - * @param {{ x: number, y: number }} location The location to touch down at. - * @return {!webdriver.TouchSequence} A self reference. - */ - tapAndHold(location: ILocation): TouchSequence; - - - /** - * Move a held {@linkplain #tapAndHold touch} to the specified location. - * - * @param {{x: number, y: number}} location The location to move to. - * @return {!webdriver.TouchSequence} A self reference. - */ - move(location: ILocation): TouchSequence; - - - /** - * Release a held {@linkplain #tapAndHold touch} at the specified location. - * - * @param {{x: number, y: number}} location The location to release at. - * @return {!webdriver.TouchSequence} A self reference. - */ - release(location: ILocation): TouchSequence; - - - /** - * Scrolls the touch screen by the given offset. - * - * @param {{x: number, y: number}} offset The offset to scroll to. - * @return {!webdriver.TouchSequence} A self reference. - */ - scroll(offset: IOffset): TouchSequence; - - /** - * Scrolls the touch screen, starting on `elem` and moving by the specified - * offset. - * - * @param {!webdriver.WebElement} elem The element where scroll starts. - * @param {{x: number, y: number}} offset The offset to scroll to. - * @return {!webdriver.TouchSequence} A self reference. - */ - scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - - /** - * Flick, starting anywhere on the screen, at speed xspeed and yspeed. - * - * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each - direction, in pixels per second. - * @return {!webdriver.TouchSequence} A self reference. - */ - flick(speed: ISpeed): TouchSequence; - - /** - * Flick starting at elem and moving by x and y at specified speed. - * - * @param {!webdriver.WebElement} elem The element where flick starts. - * @param {{x: number, y: number}} offset The offset to flick to. - * @param {number} speed The speed to flick at in pixels per second. - * @return {!webdriver.TouchSequence} A self reference. - */ - flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; - } - - interface IOffset { - x: number; - y: number; - } - - interface ISpeed { - xspeed: number; - yspeed: number; - } - - /** - * Represents a modal dialog such as {@code alert}, {@code confirm}, or - * {@code prompt}. Provides functions to retrieve the message displayed with - * the alert, accept or dismiss the alert, and set the response text (in the - * case of {@code prompt}). - */ - class Alert { - /** - * @param {!WebDriver} driver The driver controlling the browser this alert - * is attached to. - * @param {string} text The message text displayed with this alert. - */ - constructor(driver: WebDriver, text: string); - - //region Methods - - /** - * Retrieves the message text displayed with this alert. For instance, if the - * alert were opened with alert('hello'), then this would return 'hello'. - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * text displayed with this alert. - */ - getText(): webdriver.promise.Promise; - - /** - * Sets the username and password in an alert prompting for credentials (such - * as a Basic HTTP Auth prompt). This method will implicitly - * {@linkplain #accept() submit} the dialog. - * - * @param {string} username The username to send. - * @param {string} password The password to send. - * @return {!promise.Promise} A promise that will be resolved when this - * command has completed. - */ - authenticateAs(username: string, password: string): webdriver.promise.Promise; - - /** - * Accepts this alert. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. - */ - accept(): webdriver.promise.Promise; - - /** - * Dismisses this alert. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. - */ - dismiss(): webdriver.promise.Promise; - - /** - * Sets the response text on this alert. This command will return an error if - * the underlying alert does not support response text (e.g. window.alert and - * window.confirm). - * @param {string} text The text to set. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. - */ - sendKeys(text: string): webdriver.promise.Promise; - - //endregion - - } - - /** - * AlertPromise is a promise that will be fulfilled with an Alert. This promise - * serves as a forward proxy on an Alert, allowing calls to be scheduled - * directly on this instance before the underlying Alert has been fulfilled. In - * other words, the following two statements are equivalent: - * - * driver.switchTo().alert().dismiss(); - * driver.switchTo().alert().then(function(alert) { - * return alert.dismiss(); - * }); - * - * @implements {promise.Thenable.} * @final */ - class AlertPromise extends Alert implements webdriver.promise.IThenable{ + class Level { + name_: string; + value_: number; /** - * @param {!WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!promise.Thenable} alert A thenable - * that will be fulfilled with the promised alert. + * @param {string} name the level's name. + * @param {number} level the level's numeric value. */ - constructor(driver: WebDriver, alert: webdriver.promise.Promise); + constructor(name: string, level: number); - //region Methods + /** @override */ + toString(): string; + + /** This logger's name. */ + name: string; + + /** The numeric log level. */ + value: number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } + + /** + * Converts a level name or value to a {@link logging.Level} value. + * If the name/value is not recognized, {@link logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!logging.Level} The converted level. + */ + function getLevel(nameOrValue: string | number): Level; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + /** + * @param {(!logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level | string | number, message: string, opt_timestamp?: number, opt_type?: string | IType); + + /** @type {!logging.Level} */ + level: Level; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } + + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, 'foo' is considered the parent of + * the 'foo.bar' and an ancestor of 'foo.bar.baz'. + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); + + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; + + /** @return {string} the name of this logger. */ + getName(): string; + + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; + + /** @return {Level} the log level for this logger. */ + getLevel(): Level; + + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; + + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; + + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; + + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; + + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string | Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; + } +} + +export namespace promise { + // region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array<(T|!ManagedPromise)>} arr An array of + * promises to wait on. + * @return {!ManagedPromise} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Array>): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!ManagedPromise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose 'then' property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!ManagedPromise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + * If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + * If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[] | Promise, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a new deferred object. + * @return {!promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + * If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + * If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[] | Promise, fn: (self: any, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!ManagedPromise} The rejected promise. + * @template T + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * The callback will the resolve or reject the returned promise, based on its + * arguments. + * @param {!Function} fn The function to wrap. + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + * __Example 1:__ the Fibonacci Sequence. + * + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); + * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as 'this' when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!ManagedPromise} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!ManagedPromise} A new promise. + */ + function when(value: T | Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!ManagedPromise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + // endregion + + /** + * Error used when the computation of a promise is cancelled. + */ + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => R | IThenable): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + * + * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } + * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); + * + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled + * with the callback result. + * @template R + */ + finally(callback: Function): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + /** + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + interface IFulfilledCallback { + (value: T | IThenable | Thenable | undefined): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, fulfilled, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or rejected state, at which point the promise is considered + * resolved. + * + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ + */ + class Promise implements IThenable { + /** + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + */ + constructor(resolver: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); + + // region Methods /** * Cancels the computation of this promise's value, rejecting the promise in the @@ -2120,7 +1034,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: Function, opt_errback?: Function): webdriver.promise.Promise; + then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -2139,14 +1053,14 @@ declare namespace webdriver { * }); * * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * @param {function(*): (R|promise.Promise.)} errback The function * to call if this promise is rejected. The function should expect a single * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * @return {!promise.Promise.} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + thenCatch(errback: (error: any) => any): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -2171,7 +1085,7 @@ declare namespace webdriver { * resolved with the result of the invoked callback. * @template R */ - catch(errback: Function): webdriver.promise.Promise; + catch(errback: Function): Promise; /** @@ -2200,2854 +1114,3935 @@ declare namespace webdriver { * throw Error('two'); // Hides Error: one * } * - * webdriver.promise.rejected(Error('one')) + * promise.rejected(Error('one')) * .thenFinally(function() { * throw Error('two'); // Hides Error: one * }); * * * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * @param {function(): (R|promise.Promise.)} callback The function * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @return {!promise.Promise.} A promise that will be fulfilled * with the callback result. * @template R */ - thenFinally(callback: Function): webdriver.promise.Promise; - } + thenFinally(callback: Function): Promise; - /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ - class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { + // endregion } /** - * Recognized browser names. - * @enum {string} + * Represents a value that will be resolved at some point in the future. This + * class represents the protected 'producer' half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link promise.ControlFlow} as an unhandled failure. + * + *

If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {promise.Promise} */ - interface IBrowser { - ANDROID: string; - CHROME: string; - EDGE: string; - FIREFOX: string; - IE: string; - INTERNET_EXPLORER: string; - IPAD: string; - IPHONE: string; - OPERA: string; - PHANTOM_JS: string; - SAFARI: string; - HTMLUNIT: string; + class Deferred extends Promise { + // region Constructors + + /** + * + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + // endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + }; + + // region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!promise.Promise} + */ + promise: Promise; + + // endregion + + // region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + // endregion } - var Browser: IBrowser; + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } - interface ProxyConfig { - proxyType: string; - proxyAutoconfigUrl?: string; - ftpProxy?: string; - httpProxy?: string; - sslProxy?: string; - noProxy?: string; + interface IEventType { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; } /** - * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment - * variables listed below may be used to override a builder's configuration, - * allowing quick runtime changes. + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. * - * - {@code SELENIUM_BROWSER}: defines the target browser in the form - * {@code browser[:version][:platform]}. + * Each task scheduled within this flow may return a + * {@link promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. * - * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder - * instances. This environment variable should be set to a fully qualified - * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This - * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * Tasks and each callback registered on a {@link promise.Promise} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will take priority over previously scheduled tasks. Furthermore, if any + * of the tasks in the frame fail, the remainder of the tasks in that frame will + * be discarded and the failure will be propagated to the user through the + * callback/task's promised result. * - * - {@code SELENIUM_SERVER_JAR}: defines the path to the - * - * standalone Selenium server jar to use. The server will be started the - * first time a WebDriver instance and be killed when the process exits. + * Each time a ControlFlow empties its task queue, it will fire an + * {@link promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION + * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the + * flow, the error will be rethrown to the global error handler. * - * Suppose you had mytest.js that created WebDriver with - * - * var driver = new webdriver.Builder() - * .forBrowser('chrome') - * .build(); - * - * This test could be made to use Firefox on the local machine by running with - * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to - * target Google Chrome on a remote machine, you can simply set the - * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: - * - * SELENIUM_BROWSER=chrome:36:LINUX \ - * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ - * node mytest.js - * - * You could also use a local copy of the standalone Selenium server: - * - * SELENIUM_BROWSER=chrome:36:LINUX \ - * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ - * node mytest.js + * @extends {EventEmitter} + * @final */ - class Builder { - - //region Constructors - + class ControlFlow extends EventEmitter { /** * @constructor */ constructor(); - //endregion - - //region Methods + /** + * Events that may be emitted by an {@link promise.ControlFlow}. + * @enum {string} + */ + static EventType: IEventType; /** - * Configures this builder to ignore any environment variable overrides and to - * only use the configuration specified through this instance's API. - * - * @return {!Builder} A self reference. + * Returns a string representation of this control flow, which is its current + * {@link #getSchedule() schedule}, sans task stack traces. + * @return {string} The string representation of this contorl flow. + * @override */ - disableEnvironmentOverrides(): Builder; - - /** - * Creates a new WebDriver client based on this builder's current - * configuration. - * - * While this method will immediately return a new WebDriver instance, any - * commands issued against it will be deferred until the associated browser - * has been fully initialized. Users may call {@link #buildAsync()} to obtain - * a promise that will not be fulfilled until the browser has been created - * (the difference is purely in style). - * - * @return {!webdriver.WebDriver} A new WebDriver instance. - * @throws {Error} If the current configuration is invalid. - * @see #buildAsync() - */ - build(): WebDriver; - - /** - * Creates a new WebDriver client based on this builder's current - * configuration. This method returns a promise that will not be fulfilled - * until the new browser session has been fully initialized. - * - * __Note:__ this method is purely a convenience wrapper around - * {@link #build()}. - * - * @return {!promise.Promise} A promise that will be - * fulfilled with the newly created WebDriver instance once the browser - * has been fully initialized. - * @see #build() - */ - buildAsync(): webdriver.promise.Promise; - - /** - * Configures the target browser for clients created by this instance. - * Any calls to {@link #withCapabilities} after this function will - * overwrite these settings. - * - *

You may also define the target browser using the {@code SELENIUM_BROWSER} - * environment variable. If set, this environment variable should be of the - * form {@code browser[:[version][:platform]]}. - * - * @param {(string|webdriver.Browser)} name The name of the target browser; - * common defaults are available on the {@link webdriver.Browser} enum. - * @param {string=} opt_version A desired version; may be omitted if any - * version should be used. - * @param {string=} opt_platform The desired platform; may be omitted if any - * version may be used. - * @return {!Builder} A self reference. - */ - forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; - - /** - * Returns the base set of capabilities this instance is currently configured - * to use. - * @return {!webdriver.Capabilities} The current capabilities for this builder. - */ - getCapabilities(): Capabilities; - - /** - * @return {string} The URL of the WebDriver server this instance is configured - * to use. - */ - getServerUrl(): string; - - /** - * @return {?string} The URL of the proxy server to use for the WebDriver's - * HTTP connections, or `null` if not set. - */ - getWebDriverProxy(): string; - - /** - * Sets the default action to take with an unexpected alert before returning - * an error. - * @param {string} beahvior The desired behavior; should be 'accept', 'dismiss', - * or 'ignore'. Defaults to 'dismiss'. - * @return {!Builder} A self reference. - */ - setAlertBehavior(behavior: string): Builder; - - /** - * Sets Chrome-specific options for drivers created by this builder. Any - * logging or proxy settings defined on the given options will take precedence - * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, - * respectively. - * - * @param {!chrome.Options} options The ChromeDriver options to use. - * @return {!Builder} A self reference. - */ - setChromeOptions(options: chrome.Options): Builder; - - /** - * Sets the control flow that created drivers should execute actions in. If - * the flow is never set, or is set to {@code null}, it will use the active - * flow at the time {@link #build()} is called. - * @param {webdriver.promise.ControlFlow} flow The control flow to use, or - * {@code null} to - * @return {!Builder} A self reference. - */ - setControlFlow(flow: webdriver.promise.ControlFlow): Builder; - - /** - * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser - * for drivers created by this builder. Any proxy settings defined on the - * given options will take precedence over those set through - * {@link #setProxy}. - * - * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. - * @return {!Builder} A self reference. - */ - setEdgeOptions(options: edge.Options): Builder; - - /** - * Sets whether native events should be used. - * @param {boolean} enabled Whether to enable native events. - * @return {!Builder} A self reference. - */ - setEnableNativeEvents(enabled: boolean): Builder; - - /** - * Sets Firefox-specific options for drivers created by this builder. Any - * logging or proxy settings defined on the given options will take precedence - * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, - * respectively. - * - * @param {!firefox.Options} options The FirefoxDriver options to use. - * @return {!Builder} A self reference. - */ - setFirefoxOptions(options: firefox.Options): Builder; - - /** - * Set Internet Explorer specific {@linkplain ie.Options options} for drivers - * created by this builder. Any proxy settings defined on the given options - * will take precedence over those set through {@link #setProxy}. - * - * @param {!ie.Options} options The IEDriver options to use. - * @return {!Builder} A self reference. - */ - setIeOptions(options: ie.Options): Builder; - - /** - * Sets the logging preferences for the created session. Preferences may be - * changed by repeated calls, or by calling {@link #withCapabilities}. - * @param {!(webdriver.logging.Preferences|Object.)} prefs The - * desired logging preferences. - * @return {!Builder} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences | Object): Builder; - - /** - * Sets Opera specific {@linkplain opera.Options options} for drivers created - * by this builder. Any logging or proxy settings defined on the given options - * will take precedence over those set through {@link #setLoggingPrefs} and - * {@link #setProxy}, respectively. - * - * @param {!opera.Options} options The OperaDriver options to use. - * @return {!Builder} A self reference. - */ - setOperaOptions(options: opera.Options): Builder; - - /** - * Sets the proxy configuration to use for WebDriver clients created by this - * builder. Any calls to {@link #withCapabilities} after this function will - * overwrite these settings. - * @param {!capabilities.ProxyConfig} config The configuration to use. - * @return {!Builder} A self reference. - */ - setProxy(config: webdriver.ProxyConfig): Builder; - - /** - * Sets Safari specific {@linkplain safari.Options options} for drivers - * created by this builder. Any logging settings defined on the given options - * will take precedence over those set through {@link #setLoggingPrefs}. - * - * @param {!safari.Options} options The Safari options to use. - * @return {!Builder} A self reference. - */ - setSafari(options: safari.Options): Builder; - - /** - * Sets how elements should be scrolled into view for interaction. - * @param {number} behavior The desired scroll behavior: either 0 to align with - * the top of the viewport or 1 to align with the bottom. - * @return {!Builder} A self reference. - */ - setScrollBehavior(behavior: number): Builder; - - /** - * Sets the URL of a remote WebDriver server to use. Once a remote URL has been - * specified, the builder direct all new clients to that server. If this method - * is never called, the Builder will attempt to create all clients locally. - * - *

As an alternative to this method, you may also set the - * {@code SELENIUM_REMOTE_URL} environment variable. - * - * @param {string} url The URL of a remote server to use. - * @return {!Builder} A self reference. - */ - usingServer(url: string): Builder; - - /** - * Sets the URL of the proxy to use for the WebDriver's HTTP connections. - * If this method is never called, the Builder will create a connection - * without a proxy. - * - * @param {string} proxy The URL of a proxy to use. - * @return {!Builder} A self reference. - */ - usingWebDriverProxy(proxy: string): Builder; - - /** - * Sets the desired capabilities when requesting a new session. This will - * overwrite any previously set capabilities. - * @param {!(Object|webdriver.Capabilities)} capabilities The desired - * capabilities for a new session. - * @return {!Builder} A self reference. - */ - withCapabilities(capabilities: Object | Capabilities): Builder; - - //endregion - } - - /** - * Describes a mechanism for locating an element on the page. - * @final - */ - class By { - - /** - * @param {string} using the name of the location strategy to use. - * @param {string} value the value to search for. - */ - constructor(using: string, value: string); - - /** - * Locates elements that have a specific class name. - * - * @param {string} name The class name to search for. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - static className(name: string): By; - - /** - * Locates elements using a CSS selector. - * - * @param {string} selector The CSS selector to use. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - static css(selector: string): By; - - /** - * Locates eleemnts by the ID attribute. This locator uses the CSS selector - * `*[id='$ID']`, _not_ `document.getElementById`. - * - * @param {string} id The ID to search for. - * @return {!By} The new locator. - */ - static id(id: string): By; - - /** - * Locates link elements whose - * {@linkplain webdriver.WebElement#getText visible text} matches the given - * string. - * - * @param {string} text The link text to search for. - * @return {!By} The new locator. - */ - static linkText(text: string): By; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!./webdriver.WebDriver): !./promise.Promise} - * A new JavaScript-based locator function. - */ - static js(script: string | Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose `name` attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!By} The new locator. - */ - static name(name: string): By; - - /** - * Locates link elements whose - * {@linkplain webdriver.WebElement#getText visible text} contains the given - * substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!By} The new locator. - */ - static partialLinkText(text: string): By; - - /** - * Locates elements with a given tag name. - * - * @param {string} name The tag name to search for. - * @return {!By} The new locator. - * @deprecated Use {@link By.css() By.css(tagName)} instead. - */ - static tagName(name: string): By; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector `//div`, WebDriver will search from the document root - * regardless of whether the locator was used with a WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - static xpath(xpath: string): By; - - /** @override */ toString(): string; - } - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type ByHash = { className: string } | - { css: string } | - { id: string } | - { js: string } | - { linkText: string } | - { name: string } | - { partialLinkText: string } | - { tagName: string } | - { xpath: string }; - - /** - * Common webdriver capability keys. - * @enum {string} - */ - interface ICapability { /** - * Indicates whether a driver should accept all SSL certs by default. This - * capability only applies when requesting a new session. To query whether - * a driver can handle insecure SSL certs, see - * {@link webdriver.Capability.SECURE_SSL}. + * Resets this instance, clearing its queue and removing all event listeners. */ - ACCEPT_SSL_CERTS: string; - + reset(): void; /** - * The browser name. Common browser names are defined in the - * {@link webdriver.Browser} enum. + * Generates an annotated string describing the internal state of this control + * flow, including the currently executing as well as pending tasks. If + * {@code opt_includeStackTraces === true}, the string will include the + * stack trace from when each task was scheduled. + * @param {string=} opt_includeStackTraces Whether to include the stack traces + * from when each task was scheduled. Defaults to false. + * @return {string} String representation of this flow's internal state. */ - BROWSER_NAME: string; + getSchedule(opt_includeStackTraces?: boolean): string; /** - * Defines how elements should be scrolled into the viewport for interaction. - * This capability will be set to zero (0) if elements are aligned with the - * top of the viewport, or one (1) if aligned with the bottom. The default - * behavior is to align with the top of the viewport. - */ - ELEMENT_SCROLL_BEHAVIOR: string; - - /** - * Whether the driver is capable of handling modal alerts (e.g. alert, - * confirm, prompt). To define how a driver should handle alerts, - * use {@link webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR}. - */ - HANDLES_ALERTS: string; - - /** - * Key for the logging driver logging preferences. - */ - LOGGING_PREFS: string; - - /** - * Whether this session generates native events when simulating user input. - */ - NATIVE_EVENTS: string; - - /** - * Describes the platform the browser is running on. Will be one of - * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a - * session, ANY may be used to indicate no platform preference (this is - * semantically equivalent to omitting the platform capability). - */ - PLATFORM: string; - - /** - * Describes the proxy configuration to use for a new WebDriver session. - */ - PROXY: string; - - /** Whether the driver supports changing the brower's orientation. */ - ROTATABLE: string; - - /** - * Whether a driver is only capable of handling secure SSL certs. To request - * that a driver accept insecure SSL certs by default, use - * {@link webdriver.Capability.ACCEPT_SSL_CERTS}. - */ - SECURE_SSL: string; - - /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; - - /** Whether the driver supports locating elements with CSS selectors. */ - SUPPORTS_CSS_SELECTORS: string; - - /** Whether the browser supports JavaScript. */ - SUPPORTS_JAVASCRIPT: string; - - /** Whether the driver supports controlling the browser's location info. */ - SUPPORTS_LOCATION_CONTEXT: string; - - /** Whether the driver supports taking screenshots. */ - TAKES_SCREENSHOT: string; - - /** - * Defines how the driver should handle unexpected alerts. The value should - * be one of 'accept', 'dismiss', or 'ignore. - */ - UNEXPECTED_ALERT_BEHAVIOR: string; - - /** Defines the browser version. */ - VERSION: string; - } - - var Capability: ICapability; - - class Capabilities { - //region Constructors - - /** - * @param {(webdriver.Capabilities|Object)=} opt_other Another set of - * capabilities to merge into this instance. - * @constructor - */ - constructor(opt_other?: Capabilities | Object); - - //endregion - - //region Methods - - /** @return {!Object} The JSON representation of this instance. */ - toJSON(): any; - - /** - * Merges another set of capabilities into this instance. Any duplicates in - * the provided set will override those already set on this instance. - * @param {!(webdriver.Capabilities|Object)} other The capabilities to - * merge into this instance. - * @return {!webdriver.Capabilities} A self reference. - */ - merge(other: Capabilities | Object): Capabilities; - - /** - * @param {string} key The capability to set. - * @param {*} value The capability value. Capability values must be JSON - * serializable. Pass {@code null} to unset the capability. - * @return {!webdriver.Capabilities} A self reference. - */ - set(key: string, value: any): Capabilities; - - /** - * Sets the logging preferences. Preferences may be specified as a - * {@link webdriver.logging.Preferences} instance, or a as a map of log-type to - * log-level. - * @param {!(webdriver.logging.Preferences|Object.)} prefs The - * logging preferences. - * @return {!webdriver.Capabilities} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences | Object): Capabilities; - - /** - * Sets the proxy configuration for this instance. - * @param {webdriver.ProxyConfig} proxy The desired proxy configuration. - * @return {!webdriver.Capabilities} A self reference. - */ - setProxy(proxy: ProxyConfig): Capabilities; - - - /** - * Sets whether native events should be used. - * @param {boolean} enabled Whether to enable native events. - * @return {!webdriver.Capabilities} A self reference. - */ - setEnableNativeEvents(enabled: boolean): Capabilities; - - - /** - * Sets how elements should be scrolled into view for interaction. - * @param {number} behavior The desired scroll behavior: either 0 to align with - * the top of the viewport or 1 to align with the bottom. - * @return {!webdriver.Capabilities} A self reference. - */ - setScrollBehavior(behavior: number): Capabilities; - - /** - * Sets the default action to take with an unexpected alert before returning - * an error. - * @param {string} behavior The desired behavior; should be 'accept', 'dismiss', - * or 'ignore'. Defaults to 'dismiss'. - * @return {!webdriver.Capabilities} A self reference. - */ - setAlertBehavior(behavior: string): Capabilities; - - /** - * @param {string} key The capability to return. - * @return {*} The capability with the given key, or {@code null} if it has - * not been set. - */ - get(key: string): any; - - /** - * @param {string} key The capability to check. - * @return {boolean} Whether the specified capability is set. - */ - has(key: string): boolean; - - //endregion - - //region Static Methods - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for Android. - */ - static android(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for Chrome. - */ - static chrome(): Capabilities; - - /** - * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. - */ - static edge(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. - */ - static firefox(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for - * Internet Explorer. - */ - static ie(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for iPad. - */ - static ipad(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for iPhone. - */ - static iphone(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for Opera. - */ - static opera(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for - * PhantomJS. - */ - static phantomjs(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for Safari. - */ - static safari(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit. - */ - static htmlunit(): Capabilities; - - /** - * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit - * with enabled Javascript. - */ - static htmlunitwithjs(): Capabilities; - - //endregion - } - - /** - * An enumeration of valid command string. - */ - interface ICommandName { - GET_SERVER_STATUS: string; - - NEW_SESSION: string; - GET_SESSIONS: string; - DESCRIBE_SESSION: string; - - CLOSE: string; - QUIT: string; - - GET_CURRENT_URL: string; - GET: string; - GO_BACK: string; - GO_FORWARD: string; - REFRESH: string; - - ADD_COOKIE: string; - GET_COOKIE: string; - GET_ALL_COOKIES: string; - DELETE_COOKIE: string; - DELETE_ALL_COOKIES: string; - - GET_ACTIVE_ELEMENT: string; - FIND_ELEMENT: string; - FIND_ELEMENTS: string; - FIND_CHILD_ELEMENT: string; - FIND_CHILD_ELEMENTS: string; - - CLEAR_ELEMENT: string; - CLICK_ELEMENT: string; - SEND_KEYS_TO_ELEMENT: string; - SUBMIT_ELEMENT: string; - - GET_CURRENT_WINDOW_HANDLE: string; - GET_WINDOW_HANDLES: string; - GET_WINDOW_POSITION: string; - SET_WINDOW_POSITION: string; - GET_WINDOW_SIZE: string; - SET_WINDOW_SIZE: string; - MAXIMIZE_WINDOW: string; - - SWITCH_TO_WINDOW: string; - SWITCH_TO_FRAME: string; - GET_PAGE_SOURCE: string; - GET_TITLE: string; - - EXECUTE_SCRIPT: string; - EXECUTE_ASYNC_SCRIPT: string; - - GET_ELEMENT_TEXT: string; - GET_ELEMENT_TAG_NAME: string; - IS_ELEMENT_SELECTED: string; - IS_ELEMENT_ENABLED: string; - IS_ELEMENT_DISPLAYED: string; - GET_ELEMENT_LOCATION: string; - GET_ELEMENT_LOCATION_IN_VIEW: string; - GET_ELEMENT_SIZE: string; - GET_ELEMENT_ATTRIBUTE: string; - GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; - ELEMENT_EQUALS: string; - - SCREENSHOT: string; - IMPLICITLY_WAIT: string; - SET_SCRIPT_TIMEOUT: string; - SET_TIMEOUT: string; - - ACCEPT_ALERT: string; - DISMISS_ALERT: string; - GET_ALERT_TEXT: string; - SET_ALERT_TEXT: string; - - EXECUTE_SQL: string; - GET_LOCATION: string; - SET_LOCATION: string; - GET_APP_CACHE: string; - GET_APP_CACHE_STATUS: string; - CLEAR_APP_CACHE: string; - IS_BROWSER_ONLINE: string; - SET_BROWSER_ONLINE: string; - - GET_LOCAL_STORAGE_ITEM: string; - GET_LOCAL_STORAGE_KEYS: string; - SET_LOCAL_STORAGE_ITEM: string; - REMOVE_LOCAL_STORAGE_ITEM: string; - CLEAR_LOCAL_STORAGE: string; - GET_LOCAL_STORAGE_SIZE: string; - - GET_SESSION_STORAGE_ITEM: string; - GET_SESSION_STORAGE_KEYS: string; - SET_SESSION_STORAGE_ITEM: string; - REMOVE_SESSION_STORAGE_ITEM: string; - CLEAR_SESSION_STORAGE: string; - GET_SESSION_STORAGE_SIZE: string; - - SET_SCREEN_ORIENTATION: string; - GET_SCREEN_ORIENTATION: string; - - // These belong to the Advanced user interactions - an element is - // optional for these commands. - CLICK: string; - DOUBLE_CLICK: string; - MOUSE_DOWN: string; - MOUSE_UP: string; - MOVE_TO: string; - SEND_KEYS_TO_ACTIVE_ELEMENT: string; - - // These belong to the Advanced Touch API - TOUCH_SINGLE_TAP: string; - TOUCH_DOWN: string; - TOUCH_UP: string; - TOUCH_MOVE: string; - TOUCH_SCROLL: string; - TOUCH_DOUBLE_TAP: string; - TOUCH_LONG_PRESS: string; - TOUCH_FLICK: string; - - GET_AVAILABLE_LOG_TYPES: string; - GET_LOG: string; - GET_SESSION_LOGS: string; - - UPLOAD_FILE: string; - } - - var CommandName: ICommandName; - - /** - * Describes a command to be executed by the WebDriverJS framework. - * @param {!webdriver.CommandName} name The name of this command. - * @constructor - */ - class Command { - //region Constructors - - /** - * @param {!webdriver.CommandName} name The name of this command. - * @constructor - */ - constructor(name: string); - - //endregion - - //region Methods - - /** - * @return {!webdriver.CommandName} This command's name. - */ - getName(): string; - - /** - * Sets a parameter to send with this command. - * @param {string} name The parameter name. - * @param {*} value The parameter value. - * @return {!webdriver.Command} A self reference. - */ - setParameter(name: string, value: any): Command; - - /** - * Sets the parameters for this command. - * @param {!Object.<*>} parameters The command parameters. - * @return {!webdriver.Command} A self reference. - */ - setParameters(parameters: any): Command; - - /** - * Returns a named command parameter. - * @param {string} key The parameter key to look up. - * @return {*} The parameter value, or undefined if it has not been set. - */ - getParameter(key: string): any; - - /** - * @return {!Object.<*>} The parameters to send with this command. - */ - getParameters(): any; - - //endregion - } - - /** - * Handles the execution of WebDriver {@link Command commands}. - * @interface - */ - class Executor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * response object. + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. If + * the task function is a generator, the task will be executed using + * {@link promise.consume}. * - * @param {!Command} command The command to execute. - * @return {!promise.Promise} A promise that will be fulfilled with - * the command result. - */ - execute(command: Command): webdriver.promise.Promise - } - - /** - * Wraps a promised {@link Executor}, ensuring no commands are executed until - * the wrapped executor has been fully resolved. - * @implements {Executor} - */ - class DeferredExecutor { - /** - * @param {!promise.Promise} delegate The promised delegate, which - * may be provided by any promise-like thenable object. - */ - constructor(delegate: webdriver.promise.Promise); - } - - /** - * Describes an event listener registered on an {@linkplain EventEmitter}. - */ - class Listener { - /** - * @param {!Function} fn The acutal listener function. - * @param {(Object|undefined)} scope The object in whose scope to invoke the - * listener. - * @param {boolean} oneshot Whether this listener should only be used once. - */ - constructor(fn: Function, scope: Object, oneshot: boolean); - } - - /** - * Object that can emit events for others to listen for. This is used instead - * of Closure's event system because it is much more light weight. The API is - * based on Node's EventEmitters. - */ - class EventEmitter { - //region Constructors - - /** - * @constructor - */ - constructor(); - - //endregion - - //region Methods - - /** - * Fires an event and calls all listeners. - * @param {string} type The type of event to emit. - * @param {...*} var_args Any arguments to pass to each listener. - */ - emit(type: string, ...var_args: any[]): void; - - /** - * Returns a mutable list of listeners for a specific type of event. - * @param {string} type The type of event to retrieve the listeners for. - * @return {!Set} The registered listeners for the given event - * type. - */ - listeners(type: string): any; - - /** - * Registers a listener. - * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. - * @param {Object=} opt_self The object in whose scope to invoke the listener. - * @param {boolean=} opt_oneshot Whether the listener should b (e removed after - * the first event is fired. - * @return {!EventEmitter} A self reference. - * @private - */ - addListener(type: string, fn: Function, opt_scope?: any, opt_oneshot?: boolean): EventEmitter; - - - /** - * Registers a one-time listener which will be called only the first time an - * event is emitted, after which it will be removed. - * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. - * @param {Object=} opt_scope The object in whose scope to invoke the listener. - * @return {!webdriver.EventEmitter} A self reference. - */ - once(type: string, fn: any, opt_scope?: any): EventEmitter; - - /** - * An alias for {@code #addListener()}. - * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. - * @param {Object=} opt_scope The object in whose scope to invoke the listener. - * @return {!webdriver.EventEmitter} A self reference. - */ - on(type: string, fn: Function, opt_scope?: any): EventEmitter; - - /** - * Removes a previously registered event listener. - * @param {string} type The type of event to unregister. - * @param {!Function} listenerFn The handler function to remove. - * @return {!webdriver.EventEmitter} A self reference. - */ - removeListener(type: string, listenerFn: Function): EventEmitter; - - /** - * Removes all listeners for a specific type of event. If no event is - * specified, all listeners across all types will be removed. - * @param {string=} opt_type The type of event to remove listeners from. - * @return {!webdriver.EventEmitter} A self reference. - */ - removeAllListeners(opt_type?: string): EventEmitter; - - //endregion - } - - - /** - * Interface for navigating back and forth in the browser history. - */ - class Navigation { - //region Constructors - - /** - * Interface for navigating back and forth in the browser history. - * - * This class should never be instantiated directly. Insead, obtain an instance - * with - * - * webdriver.navigate() - * - * @see WebDriver#navigate() - */ - constructor(driver: WebDriver); - - //endregion - - //region Methods - - /** - * Schedules a command to navigate to a new URL. - * @param {string} url The URL to navigate to. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the URL has been loaded. - */ - to(url: string): webdriver.promise.Promise; - - /** - * Schedules a command to move backwards in the browser history. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the navigation event has completed. - */ - back(): webdriver.promise.Promise; - - /** - * Schedules a command to move forwards in the browser history. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the navigation event has completed. - */ - forward(): webdriver.promise.Promise; - - /** - * Schedules a command to refresh the current page. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the navigation event has completed. - */ - refresh(): webdriver.promise.Promise; - - //endregion - } - - interface IWebDriverOptionsCookie { - name: string; - value: string; - path?: string; - domain?: string; - secure?: boolean; - expiry?: number; - } - - /** - * Provides methods for managing browser and driver state. - */ - class Options { - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor - */ - constructor(driver: webdriver.WebDriver); - - //endregion - - //region Methods - - /** - * Schedules a command to add a cookie. - * @param {string} name The cookie name. - * @param {string} value The cookie value. - * @param {string=} opt_path The cookie path. - * @param {string=} opt_domain The cookie domain. - * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified - * as a number, should be in milliseconds since midnight, - * January 1, 1970 UTC. - * @return {!promise.Promise} A promise that will be resolved - * when the cookie has been added to the page. - */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number | Date): webdriver.promise.Promise; - - /** - * Schedules a command to delete all cookies visible to the current page. - * @return {!webdriver.promise.Promise} A promise that will be resolved when all - * cookies have been deleted. - */ - deleteAllCookies(): webdriver.promise.Promise; - - /** - * Schedules a command to delete the cookie with the given name. This command is - * a no-op if there is no cookie with the given name visible to the current - * page. - * @param {string} name The name of the cookie to delete. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been deleted. - */ - deleteCookie(name: string): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve all cookies visible to the current page. - * Each cookie will be returned as a JSON object as described by the WebDriver - * wire protocol. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * cookies visible to the current page. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object - */ - getCookies(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the cookie with the given name. Returns null - * if there is no such cookie. The cookie will be returned as a JSON object as - * described by the WebDriver wire protocol. - * @param {string} name The name of the cookie to retrieve. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * named cookie, or {@code null} if there is no such cookie. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object - */ - getCookie(name: string): webdriver.promise.Promise; - - /** - * @return {!webdriver.WebDriver.Logs} The interface for managing driver - * logs. - */ - logs(): webdriver.Logs; - - /** - * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver - * timeouts. - */ - timeouts(): webdriver.Timeouts; - - /** - * @return {!webdriver.WebDriver.Window} The interface for managing the - * current window. - */ - window(): webdriver.Window; - - //endregion - } - - /** - * An interface for managing timeout behavior for WebDriver instances. - */ - class Timeouts { - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor - */ - constructor(driver: webdriver.WebDriver); - - //endregion - - //region Methods - - /** - * Specifies the amount of time the driver should wait when searching for an - * element if it is not immediately present. - *

- * When searching for a single element, the driver should poll the page - * until the element has been found, or this timeout expires before failing - * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching - * for multiple elements, the driver should poll the page until at least one - * element has been found or this timeout has expired. - *

- * Setting the wait timeout to 0 (its default value), disables implicit - * waiting. - *

- * Increasing the implicit wait timeout should be used judiciously as it - * will have an adverse effect on test run time, especially when used with - * slower location strategies like XPath. - * - * @param {number} ms The amount of time to wait, in milliseconds. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * implicit wait timeout has been set. - */ - implicitlyWait(ms: number): webdriver.promise.Promise; - - /** - * Sets the amount of time to wait, in milliseconds, for an asynchronous script - * to finish execution before returning an error. If the timeout is less than or - * equal to 0, the script will be allowed to run indefinitely. - * - * @param {number} ms The amount of time to wait, in milliseconds. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * script timeout has been set. - */ - setScriptTimeout(ms: number): webdriver.promise.Promise; - - /** - * Sets the amount of time to wait for a page load to complete before returning - * an error. If the timeout is negative, page loads may be indefinite. - * @param {number} ms The amount of time to wait, in milliseconds. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the timeout has been set. - */ - pageLoadTimeout(ms: number): webdriver.promise.Promise; - - //endregion - } - - /** - * An interface for managing the current window. - */ - class Window { - - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor - */ - constructor(driver: webdriver.WebDriver); - - //endregion - - //region Methods - - /** - * Retrieves the window's current position, relative to the top left corner of - * the screen. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * window's position in the form of a {x:number, y:number} object literal. - */ - getPosition(): webdriver.promise.Promise; - - /** - * Repositions the current window. - * @param {number} x The desired horizontal position, relative to the left side - * of the screen. - * @param {number} y The desired vertical position, relative to the top of the - * of the screen. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * command has completed. - */ - setPosition(x: number, y: number): webdriver.promise.Promise; - - /** - * Retrieves the window's current size. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * window's size in the form of a {width:number, height:number} object - * literal. - */ - getSize(): webdriver.promise.Promise; - - /** - * Resizes the current window. - * @param {number} width The desired window width. - * @param {number} height The desired window height. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * command has completed. - */ - setSize(width: number, height: number): webdriver.promise.Promise; - - /** - * Maximizes the current window. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * command has completed. - */ - maximize(): webdriver.promise.Promise; - - //endregion - } - - /** - * Interface for managing WebDriver log records. - */ - class Logs { - - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor - */ - constructor(driver: webdriver.WebDriver); - - //endregion - - //region - - /** - * Fetches available log entries for the given type. - * - *

Note that log buffers are reset after each call, meaning that - * available log entries correspond to those entries not yet returned for a - * given log type. In practice, this means that this call will return the - * available log entries since the last call, or from the start of the - * session. - * - * @param {!webdriver.logging.Type} type The desired log type. - * @return {!webdriver.promise.Promise.>} A - * promise that will resolve to a list of log entries for the specified - * type. - */ - get(type: string): webdriver.promise.Promise; - - /** - * Retrieves the log types available to this driver. - * @return {!webdriver.promise.Promise.>} A - * promise that will resolve to a list of available log types. - */ - getAvailableLogTypes(): webdriver.promise.Promise; - - //endregion - } - - /** - * An interface for changing the focus of the driver to another frame or window. - */ - class TargetLocator { - - //region Constructors - - /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor - */ - constructor(driver: webdriver.WebDriver); - - //endregion - - //region Methods - - /** - * Schedules a command retrieve the {@code document.activeElement} element on - * the current document, or {@code document.body} if activeElement is not - * available. - * @return {!webdriver.WebElement} The active element. - */ - activeElement(): WebElementPromise; - - /** - * Schedules a command to switch focus of all future commands to the first frame - * on the page. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the default content. - */ - defaultContent(): webdriver.promise.Promise; - - /** - * Schedules a command to switch the focus of all future commands to another - * frame on the page. The target frame may be specified as one of the - * following: - * - * - A number that specifies a (zero-based) index into [window.frames]( - * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). - * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` - * DOM element. - * - The `null` value, to select the topmost frame on the page. Passing `null` - * is the same as calling {@link #defaultContent defaultContent()}. - * - * If the specified frame can not be found, the returned promise will be - * rejected with a {@linkplain error.NoSuchFrameError}. - * - * @param {(number|WebElement|null)} id The frame locator. - * @return {!promise.Promise} A promise that will be resolved - * when the driver has changed focus to the specified frame. - */ - frame(nameOrIndex: number | WebElement): webdriver.promise.Promise; - - /** - * Schedules a command to switch the focus of all future commands to another - * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@link WebDriver#getWindowHandles}). - * - * If the specified window cannot be found, the returned promise will be - * rejected with a {@linkplain error.NoSuchWindowError}. - * - * @param {string} nameOrHandle The name or window handle of the window to - * switch focus to. - * @return {!promise.Promise} A promise that will be resolved - * when the driver has changed focus to the specified window. - */ - window(nameOrHandle: string): webdriver.promise.Promise; - - /** - * Schedules a command to change focus to the active modal dialog, such as - * those opened by `window.alert()`, `window.confirm()`, and - * `window.prompt()`. The returned promise will be rejected with a - * {@linkplain error.NoSuchAlertError} if there are no open alerts. - * - * @return {!AlertPromise} The open alert. - */ - alert(): AlertPromise; - - //endregion - } - - /** - * Used with {@link webdriver.WebElement#sendKeys WebElement#sendKeys} on file - * input elements ({@code }) to detect when the entered key - * sequence defines the path to a file. - * - * By default, {@linkplain webdriver.WebElement WebElement's} will enter all - * key sequences exactly as entered. You may set a - * {@linkplain webdriver.WebDriver#setFileDetector file detector} on the parent - * WebDriver instance to define custom behavior for handling file elements. Of - * particular note is the {@link selenium-webdriver/remote.FileDetector}, which - * should be used when running against a remote - * [Selenium Server](http://docs.seleniumhq.org/download/). - */ - class FileDetector { - /** @constructor */ - constructor(); - - /** - * Handles the file specified by the given path, preparing it for use with - * the current browser. If the path does not refer to a valid file, it will - * be returned unchanged, otherwisee a path suitable for use with the current - * browser will be returned. - * - * This default implementation is a no-op. Subtypes may override this - * function for custom tailored file handling. - * - * @param {!webdriver.WebDriver} driver The driver for the current browser. - * @param {string} path The path to process. - * @return {!webdriver.promise.Promise} A promise for the processed - * file path. - * @package - */ - handleFile(driver: webdriver.WebDriver, path: string): webdriver.promise.Promise; - } - - /** - * Creates a new WebDriver client, which provides control over a browser. - * - * Every WebDriver command returns a {@code webdriver.promise.Promise} that - * represents the result of that command. Callbacks may be registered on this - * object to manipulate the command result or catch an expected error. Any - * commands scheduled with a callback are considered sub-commands and will - * execute before the next command in the current frame. For example: - * - * var message = []; - * driver.call(message.push, message, 'a').then(function() { - * driver.call(message.push, message, 'b'); - * }); - * driver.call(message.push, message, 'c'); - * driver.call(function() { - * alert('message is abc? ' + (message.join('') == 'abc')); - * }); - * - */ - class WebDriver { - //region Constructors - - /** - * @param {!(Session|promise.Promise)} session Either a - * known session or a promise that will be resolved to a session. - * @param {!command.Executor} executor The executor to use when sending - * commands to the browser. - * @param {promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - */ - constructor(session: Session | webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region StaticMethods - - /** - * Creates a new WebDriver client for an existing session. - * @param {!command.Executor} executor Command executor to use when querying - * for session details. - * @param {string} sessionId ID of the session to attach to. - * @param {promise.ControlFlow=} opt_flow The control flow all - * driver commands should execute under. Defaults to the - * {@link promise.controlFlow() currently active} control flow. - * @return {!WebDriver} A new client for the specified session. - */ - static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; - - /** - * Creates a new WebDriver session. - * @param {!command.Executor} executor The executor to create the new session - * with. - * @param {!./capabilities.Capabilities} desiredCapabilities The desired - * capabilities for the new session. - * @param {promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under, including the initial session creation. - * Defaults to the {@link promise.controlFlow() currently active} - * control flow. - * @return {!WebDriver} The driver for the newly created session. - */ - static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; - - //endregion - - //region Methods - - /** - * @return {!webdriver.promise.ControlFlow} The control flow used by this - * instance. - */ - controlFlow(): webdriver.promise.ControlFlow; - - /** - * Schedules a {@link command.Command} to be executed by this driver's - * {@link command.Executor}. - * - * @param {!command.Command} command The command to schedule. - * @param {string} description A description of the command for debugging. + * @param {function(): (T|promise.Promise)} fn The function to + * call to start the task. If the function returns a + * {@link promise.Promise}, this instance will wait for it to be + * resolved before starting the next task. + * @param {string=} opt_description A description of the task. * @return {!promise.Promise} A promise that will be resolved - * with the command result. + * with the result of the action. * @template T */ - schedule(command: Command, description: string): webdriver.promise.Promise; - + execute(fn: () => (T | Promise), opt_description?: string): Promise; /** - * Sets the {@linkplain input.FileDetector file detector} that should be - * used with this instance. - * @param {input.FileDetector} detector The detector to use or {@code null}. + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!promise.Promise} A promise that will be resolved with + * the result of the action. */ - setFileDetector(detector: FileDetector): void; - + timeout(ms: number, opt_description?: string): Promise; /** - * @return {!webdriver.promise.Promise.} A promise for this - * client's session. - */ - getSession(): webdriver.promise.Promise; - - - /** - * @return {!webdriver.promise.Promise.} A promise - * that will resolve with the this instance's capabilities. - */ - getCapabilities(): webdriver.promise.Promise; - - - /** - * Schedules a command to quit the current session. After calling quit, this - * instance will be invalidated and may no longer be used to issue commands - * against the browser. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the command has completed. - */ - quit(): webdriver.promise.Promise; - - /** - * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link actions.ActionSequence#perform} is - * called. Example: + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. * - * driver.actions(). - * mouseDown(element1). - * mouseMove(element2). - * mouseUp(). - * perform(); + * Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. * - * @return {!actions.ActionSequence} A new action sequence for this instance. - */ - actions(): ActionSequence; - - - /** - * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link actions.TouchSequence#perform} is - * called. Example: + * In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. * - * driver.touchActions(). - * tap(element1). - * doubleTap(element2). - * perform(); + * If the condition function throws, or returns a rejected promise, the + * wait task will fail. * - * @return {!actions.TouchSequence} A new touch sequence for this instance. - */ - touchActions(): TouchSequence; - - - /** - * Schedules a command to execute JavaScript in the context of the currently - * selected frame or window. The script fragment will be executed as the body - * of an anonymous function. If the script is provided as a function object, - * that function will be converted to a string for injection into the target - * window. + * If the condition is defined as a promise, the flow will wait for it to + * settle. If the timeout expires before the promise settles, the promise + * returned by this function will be rejected. * - * Any arguments provided in addition to the script will be included as script - * arguments and may be referenced using the {@code arguments} object. - * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. - * Arrays and objects may also be used as script arguments as long as each item - * adheres to the types previously mentioned. + * If this function is invoked with `timeout === 0`, or the timeout is omitted, + * the flow will wait indefinitely for the condition to be satisfied. * - * The script may refer to any variables accessible from the current window. - * Furthermore, the script will execute in the window's context, thus - * {@code document} may be used to refer to the current document. Any local - * variables will not be available once the script has finished executing, - * though global variables will persist. - * - * If the script has a return value (i.e. if the script contains a return - * statement), then the following steps will be taken for resolving this - * functions return value: - * - * - For a HTML element, the value will resolve to a - * {@link webdriver.WebElement} - * - Null and undefined return values will resolve to null - * - Booleans, numbers, and strings will resolve as is - * - Functions will resolve to their string representation - * - For arrays and objects, each member item will be converted according to - * the rules above - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the - * scripts return value. + * @param {(!promise.Promise|function())} condition The condition to poll, + * or a promise to wait on. + * @param {number=} opt_timeout How long to wait, in milliseconds, for the + * condition to hold before timing out. If omitted, the flow will wait + * indefinitely. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!promise.Promise} A promise that will be fulfilled + * when the condition has been satisified. The promise shall be rejected if + * the wait times out waiting for the condition. + * @throws {TypeError} If condition is not a function or promise or if timeout + * is not a number >= 0. * @template T */ - executeScript(script: string | Function, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to execute asynchronous JavaScript in the context of the - * currently selected frame or window. The script fragment will be executed as - * the body of an anonymous function. If the script is provided as a function - * object, that function will be converted to a string for injection into the - * target window. - * - * Any arguments provided in addition to the script will be included as script - * arguments and may be referenced using the {@code arguments} object. - * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. - * Arrays and objects may also be used as script arguments as long as each item - * adheres to the types previously mentioned. - * - * Unlike executing synchronous JavaScript with {@link #executeScript}, - * scripts executed with this function must explicitly signal they are finished - * by invoking the provided callback. This callback will always be injected - * into the executed function as the last argument, and thus may be referenced - * with {@code arguments[arguments.length - 1]}. The following steps will be - * taken for resolving this functions return value against the first argument - * to the script's callback function: - * - * - For a HTML element, the value will resolve to a - * {@link webdriver.WebElement} - * - Null and undefined return values will resolve to null - * - Booleans, numbers, and strings will resolve as is - * - Functions will resolve to their string representation - * - For arrays and objects, each member item will be converted according to - * the rules above - * - * __Example #1:__ Performing a sleep that is synchronized with the currently - * selected window: - * - * var start = new Date().getTime(); - * driver.executeAsyncScript( - * 'window.setTimeout(arguments[arguments.length - 1], 500);'). - * then(function() { - * console.log( - * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); - * }); - * - * __Example #2:__ Synchronizing a test with an AJAX application: - * - * var button = driver.findElement(By.id('compose-button')); - * button.click(); - * driver.executeAsyncScript( - * 'var callback = arguments[arguments.length - 1];' + - * 'mailClient.getComposeWindowWidget().onload(callback);'); - * driver.switchTo().frame('composeWidget'); - * driver.findElement(By.id('to')).sendKeys('dog@example.com'); - * - * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In - * this example, the inject script is specified with a function literal. When - * using this format, the function is converted to a string for injection, so it - * should not reference any symbols not defined in the scope of the page under - * test. - * - * driver.executeAsyncScript(function() { - * var callback = arguments[arguments.length - 1]; - * var xhr = new XMLHttpRequest(); - * xhr.open('GET', '/resource/data.json', true); - * xhr.onreadystatechange = function() { - * if (xhr.readyState == 4) { - * callback(xhr.responseText); - * } - * } - * xhr.send(''); - * }).then(function(str) { - * console.log(JSON.parse(str)['food']); - * }); - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the - * scripts return value. - * @template T - */ - executeAsyncScript(script: string | Function, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to execute a custom function. - * @param {function(...): (T|webdriver.promise.Promise.)} fn The function to - * execute. - * @param {Object=} opt_scope The object in whose scope to execute the function. - * @param {...*} var_args Any arguments to pass to the function. - * @return {!webdriver.promise.Promise.} A promise that will be resolved' - * with the function's result. - * @template T - */ - call(fn: (...var_args: any[]) => (T | webdriver.promise.Promise), opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to wait for a condition to hold. The condition may be - * specified by a {@link webdriver.until.Condition}, as a custom function, or - * as a {@link webdriver.promise.Promise}. - * - * For a {@link webdriver.until.Condition} or function, the wait will repeatedly - * evaluate the condition until it returns a truthy value. If any errors occur - * while evaluating the condition, they will be allowed to propagate. In the - * event a condition returns a {@link webdriver.promise.Promise promise}, the - * polling loop will wait for it to be resolved and use the resolved value for - * whether the condition has been satisified. Note the resolution time for - * a promise is factored into whether a wait has timed out. - * - * *Example:* waiting up to 10 seconds for an element to be present and visible - * on the page. - * - * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); - * button.click(); - * - * This function may also be used to block the command flow on the resolution - * of a {@link webdriver.promise.Promise promise}. When given a promise, the - * command will simply wait for its resolution before completing. A timeout may - * be provided to fail the command if the promise does not resolve before the - * timeout expires. - * - * *Example:* Suppose you have a function, `startTestServer`, that returns a - * promise for when a server is ready for requests. You can block a `WebDriver` - * client on this promise with: - * - * var started = startTestServer(); - * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); - * driver.get(getServerUrl()); - * - * @param {!(webdriver.promise.Promise| - * webdriver.until.Condition| - * function(!webdriver.WebDriver): T)} condition The condition to - * wait on, defined as a promise, condition object, or a function to - * evaluate as a condition. - * @param {number=} opt_timeout How long to wait for the condition to be true. - * @param {string=} opt_message An optional message to use if the wait times - * out. - * @return {!webdriver.promise.Promise} A promise that will be fulfilled - * with the first truthy value returned by the condition function, or - * rejected if the condition times out. - * @template T - */ - wait(condition: webdriver.promise.Promise | webdriver.until.Condition | ((driver: WebDriver) => T) | Function, timeout?: number, opt_message?: string): webdriver.promise.Promise; - - /** - * Schedules a command to make the driver sleep for the given amount of time. - * @param {number} ms The amount of time, in milliseconds, to sleep. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the sleep has finished. - */ - sleep(ms: number): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve they current window handle. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the current window handle. - */ - getWindowHandle(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the current list of available window handles. - * @return {!webdriver.promise.Promise.>} A promise that will - * be resolved with an array of window handles. - */ - getAllWindowHandles(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the current page's source. The page source - * returned is a representation of the underlying DOM: do not expect it to be - * formatted or escaped in the same way as the response sent from the web - * server. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the current page source. - */ - getPageSource(): webdriver.promise.Promise; - - /** - * Schedules a command to close the current window. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when this command has completed. - */ - close(): webdriver.promise.Promise; - - /** - * Schedules a command to navigate to the given URL. - * @param {string} url The fully qualified URL to open. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the document has finished loading. - */ - get(url: string): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the URL of the current page. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the current URL. - */ - getCurrentUrl(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the current page's title. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the current page's title. - */ - getTitle(): webdriver.promise.Promise; - - /** - * Schedule a command to find an element on the page. If the element cannot be - * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned - * by the driver. Unlike other commands, this error cannot be suppressed. In - * other words, scheduling a command to find an element doubles as an assert - * that the element is present on the page. To test whether an element is - * present on the page, use {@link #isElementPresent} instead. - * - * The search criteria for an element may be defined using one of the - * factories in the {@link webdriver.By} namespace, or as a short-hand - * {@link webdriver.By.Hash} object. For example, the following two statements - * are equivalent: - * - * var e1 = driver.findElement(By.id('foo')); - * var e2 = driver.findElement({id:'foo'}); - * - * You may also provide a custom locator function, which takes as input this - * instance and returns a {@link WebElement}, or a promise that will resolve - * to a WebElement. If the returned promise resolves to an array of - * WebElements, WebDriver will use the first element. For example, to find the - * first visible link on a page, you could write: - * - * var link = driver.findElement(firstVisibleLink); - * - * function firstVisibleLink(driver) { - * var links = driver.findElements(By.tagName('a')); - * return promise.filter(links, function(link) { - * return link.isDisplayed(); - * }); - * } - * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!WebElementPromise} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if an element is present on the page. - * - * If given a DOM element, this function will check if it belongs to the - * document the driver is currently focused on. Otherwise, the function will - * test if at least one element can be found with the given search criteria. - * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise} A promise that will resolve - * with whether the element is present on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * driver.findElements(locator).then(e => !!e.length); - */ - isElementPresent(locatorOrElement: By | Function): webdriver.promise.Promise; - - /** - * Schedule a command to search for multiple elements on the page. - * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise.>} A - * promise that will resolve to an array of WebElements. - */ - findElements(locator: By | Function): webdriver.promise.Promise; - - /** - * Schedule a command to take a screenshot. The driver makes a best effort to - * return a screenshot of the following, in order of preference: - * - * 1. Entire page - * 2. Current window - * 3. Visible portion of the current frame - * 4. The entire display containing the browser - * - * @return {!promise.Promise} A promise that will be - * resolved to the screenshot as a base-64 encoded PNG. - */ - takeScreenshot(): webdriver.promise.Promise; - - /** - * @return {!webdriver.WebDriver.Options} The options interface for this - * instance. - */ - manage(): webdriver.Options; - - /** - * @return {!webdriver.WebDriver.Navigation} The navigation interface for this - * instance. - */ - navigate(): Navigation; - - /** - * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for - * this instance. - */ - switchTo(): webdriver.TargetLocator; - - //endregion - } - - interface IWebElementId { - [ELEMENT: string]: string; - } - - /** - * Represents a DOM element. WebElements can be found by searching from the - * document root using a {@code webdriver.WebDriver} instance, or by searching - * under another {@code webdriver.WebElement}: - *


-   *   driver.get('http://www.google.com');
-   *   var searchForm = driver.findElement(By.tagName('form'));
-   *   var searchBox = searchForm.findElement(By.name('q'));
-   *   searchBox.sendKeys('webdriver');
-   * 
- * - * The WebElement is implemented as a promise for compatibility with the promise - * API. It will always resolve itself when its internal state has been fully - * resolved and commands may be issued against the element. This can be used to - * catch errors when an element cannot be located on the page: - *

-   *   driver.findElement(By.id('not-there')).then(function(element) {
-   *     alert('Found an element that was not expected to be there!');
-   *   }, function(error) {
-   *     alert('The element was not found, as expected');
-   *   });
-   * 
- */ - interface IWebElement { - //region Methods - - /** - * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the click command has completed. - */ - click(): webdriver.promise.Promise; - - /** - * Schedules a command to type a sequence on the DOM element represented by - * this instance. - * - * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is - * processed in the key sequence, that key state is toggled until one of the - * following occurs: - * - * - The modifier key is encountered again in the sequence. At this point the - * state of the key is toggled (along with the appropriate keyup/down - * events). - * - The {@link input.Key.NULL} key is encountered in the sequence. When - * this key is encountered, all modifier keys current in the down state are - * released (with accompanying keyup events). The NULL key can be used to - * simulate common keyboard shortcuts: - * - * element.sendKeys('text was', - * Key.CONTROL, 'a', Key.NULL, - * 'now text is'); - * // Alternatively: - * element.sendKeys('text was', - * Key.chord(Key.CONTROL, 'a'), - * 'now text is'); - * - * - The end of the key sequence is encountered. When there are no more keys - * to type, all depressed modifier keys are released (with accompanying - * keyup events). - * - * If this element is a file input ({@code }), the - * specified key sequence should specify the path to the file to attach to - * the element. This is analogous to the user clicking 'Browse...' and entering - * the path into the file select dialog. - * - * var form = driver.findElement(By.css('form')); - * var element = form.findElement(By.css('input[type=file]')); - * element.sendKeys('/path/to/file.txt'); - * form.submit(); - * - * For uploads to function correctly, the entered path must reference a file - * on the _browser's_ machine, not the local machine running this script. When - * running against a remote Selenium server, a {@link input.FileDetector} - * may be used to transparently copy files to the remote machine before - * attempting to upload them in the browser. - * - * __Note:__ On browsers where native keyboard events are not supported - * (e.g. Firefox on OS X), key events will be synthesized. Special - * punctuation keys will be synthesized according to a standard QWERTY en-us - * keyboard layout. - * - * @param {...(number|string|!IThenable<(number|string)>)} var_args The - * sequence of keys to type. Number keys may be referenced numerically or - * by string (1 or '1'). All arguments will be joined into a single - * sequence. - * @return {!webdriver.promise.Promise} A promise that will be resolved when all - * keys have been typed. - */ - sendKeys(...var_args: Array>): webdriver.promise.Promise; - - /** - * Schedules a command to query for the tag/node name of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's tag name. - */ - getTagName(): webdriver.promise.Promise; - - /** - * Schedules a command to query for the computed style of the element - * represented by this instance. If the element inherits the named style from - * its parent, the parent will be queried for its value. Where possible, color - * values will be converted to their hex representation (e.g. #00ff00 instead of - * rgb(0, 255, 0)). - *

- * Warning: the value returned will be as the browser interprets it, so - * it may be tricky to form a proper assertion. - * - * @param {string} cssStyleProperty The name of the CSS style property to look - * up. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * requested CSS value. - */ - getCssValue(cssStyleProperty: string): webdriver.promise.Promise; - - /** - * Schedules a command to query for the value of the given attribute of the - * element. Will return the current value even if it has been modified after the - * page has been loaded. More exactly, this method will return the value of the - * given attribute, unless that attribute is not present, in which case the - * value of the property with the same name is returned. If neither value is - * set, null is returned. The 'style' attribute is converted as best can be to a - * text representation with a trailing semi-colon. The following are deemed to - * be 'boolean' attributes and will be returned as thus: - * - *

async, autofocus, autoplay, checked, compact, complete, controls, declare, - * defaultchecked, defaultselected, defer, disabled, draggable, ended, - * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, - * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, - * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, - * selected, spellcheck, truespeed, willvalidate - * - *

Finally, the following commonly mis-capitalized attribute/property names - * are evaluated as expected: - *

    - *
  • 'class' - *
  • 'readonly' - *
- * @param {string} attributeName The name of the attribute to query. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * attribute's value. - */ - getAttribute(attributeName: string): webdriver.promise.Promise; - - /** - * Get the visible (i.e. not hidden by CSS) innerText of this element, including - * sub-elements, without any leading or trailing whitespace. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's visible text. - */ - getText(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the size of this element's bounding box, in - * pixels. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's size as a {@code {width:number, height:number}} object. - */ - getSize(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the location of this element in page space. - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * element's location as a {@code {x:number, y:number}} object. - */ - getLocation(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether the DOM element represented by this - * instance is enabled, as dicted by the {@code disabled} attribute. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently enabled. - */ - isEnabled(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether this element is selected. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently selected. - */ - isSelected(): webdriver.promise.Promise; - - /** - * Schedules a command to submit the form containing this element (or this - * element if it is a FORM element). This command is a no-op if the element is - * not contained in a form. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the form has been submitted. - */ - submit(): webdriver.promise.Promise; - - /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element - * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the element has been cleared. - */ - clear(): webdriver.promise.Promise; - - /** - * Schedules a command to test whether this element is currently displayed. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently visible on the page. - */ - isDisplayed(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the element's outer HTML. - */ - getOuterHtml(): webdriver.promise.Promise; - - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): webdriver.promise.Promise; - - //endregion - } - - interface IWebElementFinders { - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - * - *

The search criteria for an element may be defined using one of the - * factories in the {@link webdriver.By} namespace, or as a short-hand - * {@link webdriver.By.Hash} object. For example, the following two statements - * are equivalent: - *

-     * var e1 = element.findElement(By.id('foo'));
-     * var e2 = element.findElement({id:'foo'});
-     * 
- * - *

You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: - *

-     * var link = element.findElement(firstVisibleLink);
-     *
-     * function firstVisibleLink(element) {
-     *   var links = element.findElements(By.tagName('a'));
-     *   return webdriver.promise.filter(links, function(link) {
-     *     return links.isDisplayed();
-     *   }).then(function(visibleLinks) {
-     *     return visibleLinks[0];
-     *   });
-     * }
-     * 
- * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether an element could be located on the page. - */ - isElementPresent(locator: By | Function): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that - * match the given search criteria. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the elements. - * @return {!webdriver.promise.Promise.>} A - * promise that will resolve to an array of WebElements. - */ - findElements(locator: By | Function): webdriver.promise.Promise; - } - - /** - * Defines an object that can be asynchronously serialized to its WebDriver - * wire representation. - * - * @constructor - * @template T - */ - interface Serializable { - /** - * Returns either this instance's serialized represention, if immediately - * available, or a promise for its serialized representation. This function is - * conceptually equivalent to objects that have a {@code toJSON()} property, - * except the serialize() result may be a promise or an object containing a - * promise (which are not directly JSON friendly). - * - * @return {!(T|IThenable.)} This instance's serialized wire format. - */ - serialize(): T | webdriver.promise.IThenable; - } - - /** - * Represents a DOM element. WebElements can be found by searching from the - * document root using a {@link webdriver.WebDriver} instance, or by searching - * under another WebElement: - * - * driver.get('http://www.google.com'); - * var searchForm = driver.findElement(By.tagName('form')); - * var searchBox = searchForm.findElement(By.name('q')); - * searchBox.sendKeys('webdriver'); - * - * The WebElement is implemented as a promise for compatibility with the promise - * API. It will always resolve itself when its internal state has been fully - * resolved and commands may be issued against the element. This can be used to - * catch errors when an element cannot be located on the page: - * - * driver.findElement(By.id('not-there')).then(function(element) { - * alert('Found an element that was not expected to be there!'); - * }, function(error) { - * alert('The element was not found, as expected'); - * }); - * - * @extends {webdriver.Serializable.} - */ - class WebElement implements Serializable { - /** - * @param {!WebDriver} driver the parent WebDriver instance for this element. - * @param {(!IThenable|string)} id The server-assigned opaque ID for - * the underlying DOM element. - */ - constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise | string); - - /** - * @param {string} id The raw ID. - * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. - * @return {!Object} The element ID for use with WebDriver's wire protocol. - */ - static buildId(id: string, opt_noLegacy?: boolean): Object; - - /** - * Extracts the encoded WebElement ID from the object. - * - * @param {?} obj The object to extract the ID from. - * @return {string} the extracted ID. - * @throws {TypeError} if the object is not a valid encoded ID. - */ - static extractId(obj: IWebElementId): string; - - /** - * @param {?} obj the object to test. - * @return {boolean} whether the object is a valid encoded WebElement ID. - */ - static isId(obj: IWebElementId): boolean; - - /** - * Compares two WebElements for equality. - * - * @param {!WebElement} a A WebElement. - * @param {!WebElement} b A WebElement. - * @return {!promise.Promise} A promise that will be - * resolved to whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; - - /** - * @return {!webdriver.WebDriver} The parent driver for this instance. - */ - getDriver(): webdriver.WebDriver; - - /** - * @return {!promise.Promise} A promise that resolves to - * the server-assigned opaque ID assigned to this element. - */ - getId(): webdriver.promise.Promise; - - /** - * @deprecated Use {@link #getId()} instead. - */ - getRawId(): any; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@link #isElementPresent} instead. - * - * The search criteria for an element may be defined using one of the - * factories in the {@link webdriver.By} namespace, or as a short-hand - * {@link webdriver.By.Hash} object. For example, the following two statements - * are equivalent: - * - * var e1 = element.findElement(By.id('foo')); - * var e2 = element.findElement({id:'foo'}); - * - * You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: - * - * var link = element.findElement(firstVisibleLink); - * - * function firstVisibleLink(element) { - * var links = element.findElements(By.tagName('a')); - * return webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; - * }); - * } - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!WebElementPromise} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise} A promise that will be - * resolved with whether an element could be located on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * element.findElements(locator).then(e => !!e.length); - */ - isElementPresent(locator: By | Function): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that - * match the given search criteria. - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise>} A - * promise that will resolve to an array of WebElements. - */ - findElements(locator: By | Function): webdriver.promise.Promise; - - /** - * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the click command has completed. - */ - click(): webdriver.promise.Promise; - - /** - * Schedules a command to type a sequence on the DOM element represented by this - * promsieinstance. - * - * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is - * processed in the keysequence, that key state is toggled until one of the - * following occurs: - * - * - The modifier key is encountered again in the sequence. At this point the - * state of the key is toggled (along with the appropriate keyup/down events). - * - The {@link webdriver.Key.NULL} key is encountered in the sequence. When - * this key is encountered, all modifier keys current in the down state are - * released (with accompanying keyup events). The NULL key can be used to - * simulate common keyboard shortcuts: - * - * element.sendKeys('text was', - * webdriver.Key.CONTROL, 'a', webdriver.Key.NULL, - * 'now text is'); - * // Alternatively: - * element.sendKeys('text was', - * webdriver.Key.chord(webdriver.Key.CONTROL, 'a'), - * 'now text is'); - * - * - The end of the keysequence is encountered. When there are no more keys - * to type, all depressed modifier keys are released (with accompanying keyup - * events). - * - * If this element is a file input ({@code }), the - * specified key sequence should specify the path to the file to attach to - * the element. This is analgous to the user clicking 'Browse...' and entering - * the path into the file select dialog. - * - * var form = driver.findElement(By.css('form')); - * var element = form.findElement(By.css('input[type=file]')); - * element.sendKeys('/path/to/file.txt'); - * form.submit(); - * - * For uploads to function correctly, the entered path must reference a file - * on the _browser's_ machine, not the local machine running this script. When - * running against a remote Selenium server, a {@link webdriver.FileDetector} - * may be used to transparently copy files to the remote machine before - * attempting to upload them in the browser. - * - * __Note:__ On browsers where native keyboard events are not supported - * (e.g. Firefox on OS X), key events will be synthesized. Special - * punctionation keys will be synthesized according to a standard QWERTY en-us - * keyboard layout. - * - * @param {...(string|!webdriver.promise.Promise)} var_args The sequence - * of keys to type. All arguments will be joined into a single sequence. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when all keys have been typed. - */ - sendKeys(...var_args: Array>): webdriver.promise.Promise; - - /** - * Schedules a command to query for the tag/node name of this element. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the element's tag name. - */ - getTagName(): webdriver.promise.Promise; - - /** - * Schedules a command to query for the computed style of the element - * represented by this instance. If the element inherits the named style from - * its parent, the parent will be queried for its value. Where possible, color - * values will be converted to their hex representation (e.g. #00ff00 instead of - * rgb(0, 255, 0)). - * - * _Warning:_ the value returned will be as the browser interprets it, so - * it may be tricky to form a proper assertion. - * - * @param {string} cssStyleProperty The name of the CSS style property to look - * up. - * @return {!promise.Promise} A promise that will be - * resolved with the requested CSS value. - */ - getCssValue(cssStyleProperty: string): webdriver.promise.Promise; - - /** - * Schedules a command to query for the value of the given attribute of the - * element. Will return the current value, even if it has been modified after - * the page has been loaded. More exactly, this method will return the value of - * the given attribute, unless that attribute is not present, in which case the - * value of the property with the same name is returned. If neither value is - * set, null is returned (for example, the 'value' property of a textarea - * element). The 'style' attribute is converted as best can be to a - * text representation with a trailing semi-colon. The following are deemed to - * be 'boolean' attributes and will return either 'true' or null: - * - * async, autofocus, autoplay, checked, compact, complete, controls, declare, - * defaultchecked, defaultselected, defer, disabled, draggable, ended, - * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, - * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, - * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, - * selected, spellcheck, truespeed, willvalidate - * - * Finally, the following commonly mis-capitalized attribute/property names - * are evaluated as expected: - * - * - 'class' - * - 'readonly' - * - * @param {string} attributeName The name of the attribute to query. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the attribute's value. The returned value will always be - * either a string or null. - */ - getAttribute(attributeName: string): webdriver.promise.Promise; - - /** - * Get the visible (i.e. not hidden by CSS) innerText of this element, including - * sub-elements, without any leading or trailing whitespace. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the element's visible text. - */ - getText(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the size of this element's bounding box, in - * pixels. - * @return {!webdriver.promise.Promise.<{width: number, height: number}>} A - * promise that will be resolved with the element's size as a - * {@code {width:number, height:number}} object. - */ - getSize(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the location of this element in page space. - * @return {!webdriver.promise.Promise.<{x: number, y: number}>} A promise that - * will be resolved to the element's location as a - * {@code {x:number, y:number}} object. - */ - getLocation(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether the DOM element represented by this - * instance is enabled, as dicted by the {@code disabled} attribute. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether this element is currently enabled. - */ - isEnabled(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether this element is selected. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether this element is currently selected. - */ - isSelected(): webdriver.promise.Promise; - - /** - * Schedules a command to submit the form containing this element (or this - * element if it is a FORM element). This command is a no-op if the element is - * not contained in a form. - * @return {!webdriver.promise.Promise.} A promise that will be resolved - * when the form has been submitted. - */ - submit(): webdriver.promise.Promise; - - /** - * Schedules a command to clear the `value` of this element. This command has - * no effect if the underlying DOM element is neither a text INPUT element - * nor a TEXTAREA element. - * @return {!promise.Promise} A promise that will be resolved - * when the element has been cleared. - */ - clear(): webdriver.promise.Promise; - - /** - * Schedules a command to test whether this element is currently displayed. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with whether this element is currently visible on the page. - */ - isDisplayed(): webdriver.promise.Promise; - - /** - * Take a screenshot of the visible region encompassed by this element's - * bounding rectangle. - * - * @param {boolean=} opt_scroll Optional argument that indicates whether the - * element should be scrolled into view before taking a screenshot. - * Defaults to false. - * @return {!promise.Promise} A promise that will be - * resolved to the screenshot as a base-64 encoded PNG. - */ - takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!webdriver.promise.Promise.} A promise that will be - * resolved with the element's outer HTML. - */ - getOuterHtml(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): webdriver.promise.Promise; - - /** @override */ - serialize(): webdriver.promise.Promise; - } - - /** - * WebElementPromise is a promise that will be fulfilled with a WebElement. - * This serves as a forward proxy on WebElement, allowing calls to be - * scheduled without directly on this instance before the underlying - * WebElement has been fulfilled. In other words, the following two statements - * are equivalent: - *

-   *     driver.findElement({id: 'my-button'}).click();
-   *     driver.findElement({id: 'my-button'}).then(function(el) {
-   *       return el.click();
-   *     });
-   * 
- * - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!webdriver.promise.Promise.} el A promise - * that will resolve to the promised element. - * @constructor - * @extends {webdriver.WebElement} - * @implements {webdriver.promise.Thenable.} - * @final - */ - class WebElementPromise extends WebElement implements webdriver.promise.IThenable { - /** - * @param {!WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!promise.Promise} el A promise - * that will resolve to the promised element. - */ - constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); - - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. - * - * @param {string=} opt_reason The reason this promise is being cancelled. - */ - cancel(opt_reason?: string): void; - - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: WebElement) => webdriver.promise.Promise, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *

-     *   // Synchronous API:
-     *   try {
-     *     doSynchronousWork();
-     *   } catch (ex) {
-     *     console.error(ex);
-     *   }
-     *
-     *   // Asynchronous promise API:
-     *   doAsynchronousWork().thenCatch(function(ex) {
-     *     console.error(ex);
-     *   });
-     * 
- * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - thenCatch(errback: (error: any) => any): webdriver.promise.Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *

-     *   // Synchronous API:
-     *   try {
-     *     doSynchronousWork();
-     *   } finally {
-     *     cleanUp();
-     *   }
-     *
-     *   // Asynchronous promise API:
-     *   doAsynchronousWork().thenFinally(cleanUp);
-     * 
- * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *

-     *   try {
-     *     throw Error('one');
-     *   } finally {
-     *     throw Error('two');  // Hides Error: one
-     *   }
-     *
-     *   webdriver.promise.rejected(Error('one'))
-     *       .thenFinally(function() {
-     *         throw Error('two');  // Hides Error: one
-     *       });
-     * 
- * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): webdriver.promise.Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): webdriver.promise.Promise; - } - - /** - * Contains information about a WebDriver session. - */ - class Session { - - //region Constructors - - /** - * @param {string} id The session ID. - * @param {!(Object|webdriver.Capabilities)} capabilities The session - * capabilities. - * @constructor - */ - constructor(id: string, capabilities: Capabilities | Object); - - //endregion - - //region Methods - - /** - * @return {string} This session's ID. - */ - getId(): string; - - /** - * @return {!webdriver.Capabilities} This session's capabilities. - */ - getCapabilities(): webdriver.Capabilities; - - /** - * Retrieves the value of a specific capability. - * @param {string} key The capability to retrieve. - * @return {*} The capability value. - */ - getCapability(key: string): any; - - /** - * Returns the JSON representation of this object, which is just the string - * session ID. - * @return {string} The JSON representation of this Session. - */ - toJSON(): string; - - //endregion + wait(condition: Promise | Function, opt_timeout?: number, opt_message?: string): Promise; } } -export = webdriver; +export namespace until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence 'Waiting [...]' + * @param {function(!WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as + * + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|./WebElement|By| + * function(!./WebDriver): !./WebElement)} frame + * The frame identifier. + * @return {!Condition} A new condition. + */ + function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!Condition} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsDisabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsEnabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isSelected + */ + function elementIsNotSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsNotVisible(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isSelected + */ + function elementIsSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsVisible(element: WebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link ./WebDriver#findElement found} with the given locator. + * + * @param {!(By|Function)} locator The locator to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextContains(element: WebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextIs(element: WebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition} The new condition. + * @see WebDriver#getText + */ + function elementTextMatches(element: WebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link WebDriver#findElement found} with the given locator. + * + * @param {!(Locator|By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!WebElement} element The element that should become stale. + * @return {!until.Condition} The new condition. + */ + function stalenessOf(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition} The new condition. + */ + function titleIs(title: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): Condition; +} + +interface ILocation { + x: number; + y: number; +} + +interface ISize { + width: number; + height: number; +} + +interface IButton { + LEFT: string; + MIDDLE: string; + RIGHT: string; +} + +/** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ +export var Button: IButton; + +interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; + + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; + + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; + + COMMAND: string; // Apple command key + META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a 'chord'. Takes a sequence of + * keys or strings, appends each of the values to a string, + * and adds the chord termination key ({@link Key.NULL}) and returns + * the resulting string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + */ + chord: (...var_args: Array) => string; +} + +/** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ +export var Key: IKey; + +/** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); + * + */ +export class ActionSequence { + + // region Constructors + + /** + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * + * @param {(!./WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. + */ + mouseMove(location: WebElement | ILocation, opt_offset?: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseDown() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseUp() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Convenience function for performing a 'drag and drop' manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * + * @param {!./WebElement} element The element to drag. + * @param {(!./WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. + */ + dragAndDrop(element: WebElement, location: WebElement | ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).click() + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + click(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Double-clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + * + * sequence.mouseMove(element).doubleClick() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: string): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: string): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targeted at the currently focused element. + * + * @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args + * The keys to type. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: Array>): ActionSequence; + + // endregion +} + + +/** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ +export class TouchSequence { + /* + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): promise.Promise; + + + /** + * Taps an element. + * + * @param {!WebElement} elem The element to tap. + * @return {!TouchSequence} A self reference. + */ + tap(elem: WebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!WebElement} elem The element to double tap. + * @return {!TouchSequence} A self reference. + */ + doubleTap(elem: WebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!WebElement} elem The element to long press. + * @return {!TouchSequence} A self reference. + */ + longPress(elem: WebElement): TouchSequence; + + + /** + * Touch down at the given location. + * + * @param {{ x: number, y: number }} location The location to touch down at. + * @return {!TouchSequence} A self reference. + */ + tapAndHold(location: ILocation): TouchSequence; + + + /** + * Move a held {@linkplain #tapAndHold touch} to the specified location. + * + * @param {{x: number, y: number}} location The location to move to. + * @return {!TouchSequence} A self reference. + */ + move(location: ILocation): TouchSequence; + + + /** + * Release a held {@linkplain #tapAndHold touch} at the specified location. + * + * @param {{x: number, y: number}} location The location to release at. + * @return {!TouchSequence} A self reference. + */ + release(location: ILocation): TouchSequence; + + + /** + * Scrolls the touch screen by the given offset. + * + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!TouchSequence} A self reference. + */ + scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + + /** + * Flick, starting anywhere on the screen, at speed xspeed and yspeed. + * + * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each + direction, in pixels per second. + * @return {!TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!WebElement} elem The element where flick starts. + * @param {{x: number, y: number}} offset The offset to flick to. + * @param {number} speed The speed to flick at in pixels per second. + * @return {!TouchSequence} A self reference. + */ + flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; +} + +interface IOffset { + x: number; + y: number; +} + +interface ISpeed { + xspeed: number; + yspeed: number; +} + +/** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + */ +export class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); + + // region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert('hello'), then this would return 'hello'. + * @return {!promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): promise.Promise; + + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): promise.Promise; + + /** + * Accepts this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): promise.Promise; + + /** + * Dismisses this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): promise.Promise; + + // endregion + +} + +/** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + * + * driver.switchTo().alert().dismiss(); + * driver.switchTo().alert().then(function(alert) { + * return alert.dismiss(); + * }); + * + * @implements {promise.Thenable.} + * @final + */ +export class AlertPromise extends Alert implements promise.IThenable { + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: promise.Promise); + + // region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: Function, opt_errback?: Function): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } catch (ex) {
+   *     console.error(ex);
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenCatch(function(ex) {
+   *     console.error(ex);
+   *   });
+   * 
+ * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } finally {
+   *     cleanUp();
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenFinally(cleanUp);
+   * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+   *   try {
+   *     throw Error('one');
+   *   } finally {
+   *     throw Error('two');  // Hides Error: one
+   *   }
+   *
+   *   promise.rejected(Error('one'))
+   *       .thenFinally(function() {
+   *         throw Error('two');  // Hides Error: one
+   *       });
+   * 
+ * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): promise.Promise; +} + +/** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ +export class UnhandledAlertError extends error.UnexpectedAlertOpenError { +} + +/** + * Recognized browser names. + * @enum {string} + */ +interface IBrowser { + ANDROID: string; + CHROME: string; + EDGE: string; + FIREFOX: string; + IE: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; +} + +export var Browser: IBrowser; + +interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; +} + +/** + * Creates new {@link WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ +export class Builder { + + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * + * @return {!WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() + */ + build(): WebDriver; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): promise.Promise; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|Browser)} name The name of the target browser; + * common defaults are available on the {@link Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. + */ + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; + + /** + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!Capabilities} The current capabilities for this builder. + */ + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be 'accept', 'dismiss', + * or 'ignore'. Defaults to 'dismiss'. + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: promise.ControlFlow): Builder; + + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: logging.Preferences | Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; + + /** + * Sets the proxy configuration to use for WebDriver clients created by this + * builder. Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * @param {!capabilities.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Object | Capabilities): Builder; + + // endregion +} + +/** + * Describes a mechanism for locating an element on the page. + * @final + */ +export class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id='$ID']`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string | Function, ...var_args: any[]): (webdriver: WebDriver) => promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; +} + +/** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ +type ByHash = { className: string } | + { css: string } | + { id: string } | + { js: string } | + { linkText: string } | + { name: string } | + { partialLinkText: string } | + { tagName: string } | + { xpath: string }; + +/** + * Common webdriver capability keys. + * @enum {string} + */ +interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link Browser} enum. + */ + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link Capability.ACCEPT_SSL_CERTS}. + */ + SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + SUPPORTS_APPLICATION_CACHE: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of 'accept', 'dismiss', or 'ignore. + */ + UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + VERSION: string; +} + +export var Capability: ICapability; + +export class Capabilities { + // region Constructors + + /** + * @param {(Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities | Object); + + // endregion + + // region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!Capabilities} A self reference. + */ + merge(other: Capabilities | Object): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!Capabilities} A self reference. + */ + setLoggingPrefs(prefs: logging.Preferences | Object): Capabilities; + + /** + * Sets the proxy configuration for this instance. + * @param {ProxyConfig} proxy The desired proxy configuration. + * @return {!Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be 'accept', 'dismiss', + * or 'ignore'. Defaults to 'dismiss'. + * @return {!Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + // endregion + + // region Static Methods + + /** + * @return {!Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + // endregion +} + +/** + * An enumeration of valid command string. + */ +interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; +} + +export var CommandName: ICommandName; + +/** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!CommandName} name The name of this command. + * @constructor + */ +export class Command { + // region Constructors + + /** + * @param {!CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + // endregion + + // region Methods + + /** + * @return {!CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + // endregion +} + +/** + * Handles the execution of WebDriver {@link Command commands}. + * @interface + */ +export class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): promise.Promise +} + +/** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ +export class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: promise.Promise); +} + +/** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ +export class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); +} + +/** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ +export class EventEmitter { + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Set} The registered listeners for the given event + * type. + */ + listeners(type: string): any; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private + */ + addListener(type: string, fn: Function, opt_scope?: any, opt_oneshot?: boolean): EventEmitter; + + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + once(type: string, fn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + on(type: string, fn: Function, opt_scope?: any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: Function): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + // endregion +} + + +/** + * Interface for navigating back and forth in the browser history. + */ +export class Navigation { + // region Constructors + + /** + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * navigate() + * + * @see WebDriver#navigate() + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!promise.Promise.} A promise that will be resolved + * when the URL has been loaded. + */ + to(url: string): promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + back(): promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + forward(): promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + refresh(): promise.Promise; + + // endregion +} + +interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; +} + +/** + * Provides methods for managing browser and driver state. + */ +export class Options { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number | Date): promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): promise.Promise; + + /** + * @return {!Logs} The interface for managing driver + * logs. + */ + logs(): Logs; + + /** + * @return {!Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): Timeouts; + + /** + * @return {!Window} The interface for managing the + * current window. + */ + window(): Window; + + // endregion +} + +/** + * An interface for managing timeout behavior for WebDriver instances. + */ +export class Timeouts { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

+ * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

+ * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

+ * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): promise.Promise; + + // endregion +} + +/** + * An interface for managing the current window. + */ +export class Window { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): promise.Promise; + + /** + * Maximizes the current window. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): promise.Promise; + + // endregion +} + +/** + * Interface for managing WebDriver log records. + */ +export class Logs { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region + + /** + * Fetches available log entries for the given type. + * + *

Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!logging.Type} type The desired log type. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): promise.Promise; + + // endregion +} + +/** + * An interface for changing the focus of the driver to another frame or window. + */ +export class TargetLocator { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. + */ + frame(nameOrIndex: number | WebElement): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. + */ + window(nameOrHandle: string): promise.Promise; + + /** + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. + */ + alert(): AlertPromise; + + // endregion +} + +/** + * Used with {@link WebElement#sendKeys WebElement#sendKeys} on file + * input elements ({@code }) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ +export class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: WebDriver, path: string): promise.Promise; +} + +/** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ +export class WebDriver { + // region Constructors + + /** + * @param {!(Session|promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(session: Session | promise.Promise, executor: Executor, opt_flow?: promise.ControlFlow); + + // endregion + + // region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. + */ + static attachToSession(executor: Executor, sessionId: string, opt_flow?: promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link promise.controlFlow() currently active} + * control flow. + * @return {!WebDriver} The driver for the newly created session. + */ + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: promise.ControlFlow): WebDriver; + + // endregion + + // region Methods + + /** + * @return {!promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): promise.ControlFlow; + + /** + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T + */ + schedule(command: Command, description: string): promise.Promise; + + + /** + * Sets the {@linkplain input.FileDetector file detector} that should be + * used with this instance. + * @param {input.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + + /** + * @return {!promise.Promise.} A promise for this + * client's session. + */ + getSession(): promise.Promise; + + + /** + * @return {!promise.Promise.} A promise + * that will resolve with the this instance's capabilities. + */ + getCapabilities(): promise.Promise; + + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!promise.Promise.} A promise that will be resolved + * when the command has completed. + */ + quit(): promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.ActionSequence#perform} is + * called. Example: + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!actions.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + * + * - For a HTML element, the value will resolve to a + * {@link WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeScript(script: string | Function, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: + * + * - For a HTML element, the value will resolve to a + * {@link WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently + * selected window: + * + * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); + * + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open('GET', '/resource/data.json', true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeAsyncScript(script: string | Function, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {function(...): (T|promise.Promise.)} fn The function to + * execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T + */ + call(fn: (...var_args: any[]) => (T | promise.Promise), opt_scope?: any, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link until.Condition}, as a custom function, or + * as a {@link promise.Promise}. + * + * For a {@link until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(promise.Promise| + * until.Condition| + * function(!WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!promise.Promise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: promise.Promise | until.Condition | ((driver: WebDriver) => T) | Function, timeout?: number, opt_message?: string): promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!promise.Promise.} A promise that will be resolved + * when the sleep has finished. + */ + sleep(ms: number): promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!promise.Promise.} A promise that will be + * resolved with the current window handle. + */ + getWindowHandle(): promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!promise.Promise.>} A promise that will + * be resolved with an array of window handles. + */ + getAllWindowHandles(): promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!promise.Promise.} A promise that will be + * resolved with the current page source. + */ + getPageSource(): promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!promise.Promise.} A promise that will be resolved + * when this command has completed. + */ + close(): promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!promise.Promise.} A promise that will be resolved + * when the document has finished loading. + */ + get(url: string): promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!promise.Promise.} A promise that will be + * resolved with the current URL. + */ + getCurrentUrl(): promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!promise.Promise.} A promise that will be + * resolved with the current page's title. + */ + getTitle(): promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return link.isDisplayed(); + * }); + * } + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + * If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve + * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locatorOrElement: By | Function): promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + * + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): promise.Promise; + + /** + * @return {!Options} The options interface for this + * instance. + */ + manage(): Options; + + /** + * @return {!Navigation} The navigation interface for this + * instance. + */ + navigate(): Navigation; + + /** + * @return {!TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): TargetLocator; + + // endregion +} + +interface IWebElementId { + [ELEMENT: string]: string; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code WebDriver} instance, or by searching + * under another {@code WebElement}: + *


+ *   driver.get('http://www.google.com');
+ *   var searchForm = driver.findElement(By.tagName('form'));
+ *   var searchBox = searchForm.findElement(By.name('q'));
+ *   searchBox.sendKeys('webdriver');
+ * 
+ * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *

+ *   driver.findElement(By.id('not-there')).then(function(element) {
+ *     alert('Found an element that was not expected to be there!');
+ *   }, function(error) {
+ *     alert('The element was not found, as expected');
+ *   });
+ * 
+ */ +interface IWebElement { + // region Methods + + /** + * Schedules a command to click on this element. + * @return {!promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by + * this instance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the key sequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down + * events). + * - The {@link input.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys('text was', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(Key.CONTROL, 'a'), + * 'now text is'); + * + * - The end of the key sequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying + * keyup events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analogous to the user clicking 'Browse...' and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link input.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctuation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(number|string|!IThenable<(number|string)>)} var_args The + * sequence of keys to type. Number keys may be referenced numerically or + * by string (1 or '1'). All arguments will be joined into a single + * sequence. + * @return {!promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The 'style' attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be 'boolean' attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • 'class' + *
  • 'readonly' + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * @return {!promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): promise.Promise; + + // endregion +} + +interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + *

+   * var e1 = element.findElement(By.id('foo'));
+   * var e2 = element.findElement({id:'foo'});
+   * 
+ * + *

You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

+   * var link = element.findElement(firstVisibleLink);
+   *
+   * function firstVisibleLink(element) {
+   *   var links = element.findElements(By.tagName('a'));
+   *   return promise.filter(links, function(link) {
+   *     return links.isDisplayed();
+   *   }).then(function(visibleLinks) {
+   *     return visibleLinks[0];
+   *   });
+   * }
+   * 
+ * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; +} + +/** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ +interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T | promise.IThenable; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {Serializable.} + */ +export class WebElement implements Serializable { + /** + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. + */ + constructor(driver: WebDriver, id: promise.Promise | string); + + /** + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. + */ + static buildId(id: string, opt_noLegacy?: boolean): Object; + + /** + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. + */ + static extractId(obj: IWebElementId): string; + + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): promise.Promise; + + /** + * @return {!WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be + * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!promise.Promise.} A promise that will be resolved + * when the click command has completed. + */ + click(): promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * promsieinstance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys('text was', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(Key.CONTROL, 'a'), + * 'now text is'); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking 'Browse...' and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(string|!promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!promise.Promise.} A promise that will be resolved + * when all keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + * + * _Warning:_ the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be + * resolved with the requested CSS value. + */ + getCssValue(cssStyleProperty: string): promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value, even if it has been modified after + * the page has been loaded. More exactly, this method will return the value of + * the given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned (for example, the 'value' property of a textarea + * element). The 'style' attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be 'boolean' attributes and will return either 'true' or null: + * + * async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + * Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + * + * - 'class' + * - 'readonly' + * + * @param {string} attributeName The name of the attribute to query. + * @return {!promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. + */ + getAttribute(attributeName: string): promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. + */ + getSize(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. + */ + getLocation(): promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. + */ + isSelected(): promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!promise.Promise.} A promise that will be resolved + * when the form has been submitted. + */ + submit(): promise.Promise; + + /** + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved + * when the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. + */ + isDisplayed(): promise.Promise; + + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): promise.Promise; + + /** @override */ + serialize(): promise.Promise; +} + +/** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *

+ *     driver.findElement({id: 'my-button'}).click();
+ *     driver.findElement({id: 'my-button'}).then(function(el) {
+ *       return el.click();
+ *     });
+ * 
+ * + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {WebElement} + * @implements {promise.Thenable.} + * @final + */ +export class WebElementPromise extends WebElement implements promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: WebDriver, el: promise.Promise); + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => promise.Promise, opt_errback?: (error: any) => any): promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } catch (ex) {
+   *     console.error(ex);
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenCatch(function(ex) {
+   *     console.error(ex);
+   *   });
+   * 
+ * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } finally {
+   *     cleanUp();
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenFinally(cleanUp);
+   * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+   *   try {
+   *     throw Error('one');
+   *   } finally {
+   *     throw Error('two');  // Hides Error: one
+   *   }
+   *
+   *   promise.rejected(Error('one'))
+   *       .thenFinally(function() {
+   *         throw Error('two');  // Hides Error: one
+   *       });
+   * 
+ * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): promise.Promise; +} + +/** + * Contains information about a WebDriver session. + */ +export class Session { + + // region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities | Object); + + // endregion + + // region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!Capabilities} This session's capabilities. + */ + getCapabilities(): Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + // endregion +} diff --git a/selenium-webdriver/opera.d.ts b/selenium-webdriver/opera.d.ts index 0d3aee1a13..cd02889527 100644 --- a/selenium-webdriver/opera.d.ts +++ b/selenium-webdriver/opera.d.ts @@ -1,177 +1,173 @@ import * as webdriver from './index'; import * as remote from './remote'; -declare namespace opera { +/** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ +export class ServiceBuilder { /** - * Creates {@link remote.DriverService} instances that manages an - * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) - * server in a child process. + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the operadriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the operadriver - * cannot be found on the PATH. - */ - constructor(opt_exe?: string); - - /** - * Sets the port to start the OperaDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** - * Sets the path of the log file the driver should log to. If a log file is - * not specified, the driver will log to stderr. - * @param {string} path Path of the log file to use. - * @return {!ServiceBuilder} A self reference. - */ - loggingTo(path: string): ServiceBuilder; - - /** - * Enables verbose logging. - * @return {!ServiceBuilder} A self reference. - */ - enableVerboseLogging(): ServiceBuilder; - - /** - * Silence sthe drivers output. - * @return {!ServiceBuilder} A self reference. - */ - silent(): ServiceBuilder; - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; - } + constructor(opt_exe?: string); /** - * Sets the default service to use for new OperaDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. */ - function setDefaultService(service: remote.DriverService): any; + usingPort(port: number): ServiceBuilder; /** - * Returns the default OperaDriver service. If such a service has not been - * configured, one will be constructed using the default configuration for - * a OperaDriver executable found on the system PATH. - * @return {!remote.DriverService} The default OperaDriver service. + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. */ - function getDefaultService(): remote.DriverService; + loggingTo(path: string): ServiceBuilder; /** - * Class for managing {@linkplain Driver OperaDriver} specific options. + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. */ - class Options { - /** - * Extracts the OperaDriver specific options from the given capabilities - * object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The OperaDriver options. - */ - static fromCapabilities(caps: webdriver.Capabilities): Options; + enableVerboseLogging(): ServiceBuilder; - /** - * Add additional command line arguments to use when launching the Opera - * browser. Each argument may be specified with or without the '--' prefix - * (e.g. '--foo' and 'foo'). Arguments with an associated value should be - * delimited by an '=': 'foo=bar'. - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: Array): Options; + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; - /** - * Add additional extensions to install when launching Opera. Each extension - * should be specified as the path to the packed CRX file, or a Buffer for an - * extension. - * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The - * extensions to add. - * @return {!Options} A self reference. - */ - addExtensions(...var_args: Array): Options; + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; - /** - * Sets the path to the Opera binary to use. On Mac OS X, this path should - * reference the actual Opera executable, not just the application binary. The - * binary path be absolute or relative to the operadriver server executable, but - * it must exist on the machine that will launch Opera. - * - * @param {string} path The path to the Opera binary to use. - * @return {!Options} A self reference. - */ - setOperaBinaryPath(path: string): Options; + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; - /** - * Sets the logging preferences for the new session. - * @param {!./lib/logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - } - - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@link getDefaultService default service} by default. - * @param {promise.ControlFlow=} opt_flow The control flow to use, - * or {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; } -export = opera; +/** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): any; + +/** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ +export class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the '--' prefix + * (e.g. '--foo' and 'foo'). Arguments with an associated value should be + * delimited by an '=': 'foo=bar'. + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; +} + +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} diff --git a/selenium-webdriver/remote.d.ts b/selenium-webdriver/remote.d.ts index d3cadb746a..ae4f156ba7 100644 --- a/selenium-webdriver/remote.d.ts +++ b/selenium-webdriver/remote.d.ts @@ -1,71 +1,67 @@ import * as webdriver from './index'; -declare namespace remote { +/** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ +interface ServiceOptions { } + +/** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ +export class DriverService { /** - * A record object that defines the configuration options for a DriverService - * instance. - * - * @record + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. */ - interface ServiceOptions { } + constructor(executable: string, options: ServiceOptions); /** - * Manages the life and death of a native executable WebDriver server. - * - * It is expected that the driver server implements the - * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. - * Furthermore, the managed server should support multiple concurrent sessions, - * so that this class may be reused for multiple clients. + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. */ - class DriverService { - /** - * @param {string} executable Path to the executable to run. - * @param {!ServiceOptions} options Configuration options for the service. - */ - constructor(executable: string, options: ServiceOptions); + address(): webdriver.promise.Promise; - /** - * @return {!promise.Promise} A promise that resolves to - * the server's address. - * @throws {Error} If the server has not been started. - */ - address(): webdriver.promise.Promise; + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; - /** - * Returns whether the underlying process is still running. This does not take - * into account whether the process is in the process of shutting down. - * @return {boolean} Whether the underlying service process is running. - */ - isRunning(): boolean; + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; - /** - * Starts the server if it is not already running. - * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the - * server to start accepting requests. Defaults to 30 seconds. - * @return {!promise.Promise} A promise that will resolve - * to the server's base URL when it has started accepting requests. If the - * timeout expires before the server has started, the promise will be - * rejected. - */ - start(opt_timeoutMs?: number): webdriver.promise.Promise; + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; - /** - * Stops the service if it is not currently running. This function will kill - * the server immediately. To synchronize with the active control flow, use - * {@link #stop()}. - * @return {!promise.Promise} A promise that will be resolved when - * the server has been stopped. - */ - kill(): webdriver.promise.Promise; - - /** - * Schedules a task in the current control flow to stop the server if it is - * currently running. - * @return {!promise.Promise} A promise that will be resolved when - * the server has been stopped. - */ - stop(): webdriver.promise.Promise; - } + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; } - -export = remote; diff --git a/selenium-webdriver/safari.d.ts b/selenium-webdriver/safari.d.ts index 82fd835b20..7a6f1701c4 100644 --- a/selenium-webdriver/safari.d.ts +++ b/selenium-webdriver/safari.d.ts @@ -1,93 +1,89 @@ import * as webdriver from './index'; -declare namespace safari { - class Server { } +export class Server { } - /** - * @return {!Promise} A promise that will resolve with the path - * to Safari on the current system. - */ - function findSafariExecutable(): any; +/** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ +export function findSafariExecutable(): any; - /** - * @param {string} serverUrl The URL to connect to. - * @return {!Promise} A promise for the path to a file that Safari can - * open on start-up to trigger a new connection to the WebSocket server. - */ - function createConnectFile(serverUrl: string): any; +/** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ +export function createConnectFile(serverUrl: string): any; - /** - * Deletes all session data files if so desired. - * @param {!Object} desiredCapabilities . - * @return {!Array} A list of promises for the deleted files. - */ - function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; +/** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ +export function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; - /** @return {string} . */ - function getRandomString(): string; +/** @return {string} . */ +export function getRandomString(): string; - /** - * @implements {command.Executor} - */ - class CommandExecutor { - } - - /** - * Configuration options specific to the {@link Driver SafariDriver}. - */ - class Options { - /** - * Extracts the SafariDriver specific options from the given capabilities - * object. - * @param {!Capabilities} capabilities The capabilities object. - * @return {!Options} The ChromeDriver options. - */ - static fromCapabilities(capabilities: webdriver.Capabilities): Options; - - /** - * Sets whether to force Safari to start with a clean session. Enabling this - * option will cause all global browser data to be deleted. - * @param {boolean} clean Whether to make sure the session has no cookies, - * cache entries, local storage, or databases. - * @return {!Options} A self reference. - */ - setCleanSession(clean: boolean): Options; - - /** - * Sets the logging preferences for the new session. - * @param {!./lib/logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Converts this options instance to a {@link Capabilities} object. - * @param {Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - - /** - * A WebDriver client for Safari. This class should never be instantiated - * directly; instead, use the {@linkplain ./builder.Builder Builder}: - * - * var driver = new Builder() - * .forBrowser('safari') - * .build(); - * - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(Options|Capabilities)=} opt_config The configuration - * options for the new session. - * @param {promise.ControlFlow=} opt_flow The control flow to create - * the driver under. - */ - constructor(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - - } +/** + * @implements {command.Executor} + */ +export class CommandExecutor { } -export = safari; +/** + * Configuration options specific to the {@link Driver SafariDriver}. + */ +export class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + +} diff --git a/selenium-webdriver/test/chrome.ts b/selenium-webdriver/test/chrome.ts index 2fce6bf6ca..de358656bc 100644 --- a/selenium-webdriver/test/chrome.ts +++ b/selenium-webdriver/test/chrome.ts @@ -52,7 +52,7 @@ function TestServiceBuilder() { builder = builder.setUrlBasePath('path'); builder = builder.setStdio('config'); builder = builder.setStdio(['A', 'B']); - builder = builder.withEnvironment({ 'A': 'a', 'B': 'b' }); + builder = builder.withEnvironment({ A: 'a', B: 'b' }); } function TestChromeModule() { diff --git a/selenium-webdriver/test/firefox.ts b/selenium-webdriver/test/firefox.ts index 7ebe0aa856..8b329c8e73 100644 --- a/selenium-webdriver/test/firefox.ts +++ b/selenium-webdriver/test/firefox.ts @@ -8,7 +8,7 @@ function TestBinary() { binary.addArguments('A', 'B', 'C'); var promise: webdriver.promise.Promise = binary.kill(); - binary.launch('profile').then(function (result: any) { }); + binary.launch('profile').then((result: any) => {}); } function TestFirefoxDriver() { @@ -38,7 +38,7 @@ function TestFirefoxProfile() { var bool: boolean = profile.acceptUntrustedCerts(); profile.addExtension('ext'); bool = profile.assumeUntrustedCertIssuer(); - profile.encode().then(function (prof: string) { }); + profile.encode().then((prof: string) => {}); var num: number = profile.getPort(); var anything: any = profile.getPreference('key'); bool = profile.nativeEventsEnabled(); diff --git a/selenium-webdriver/test/index.ts b/selenium-webdriver/test/index.ts index ba2acb91ef..5d32724b15 100644 --- a/selenium-webdriver/test/index.ts +++ b/selenium-webdriver/test/index.ts @@ -28,7 +28,7 @@ function TestBuilder() { builder = builder.setEnableNativeEvents(true); builder = builder.setFirefoxOptions(new firefox.Options()); builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); - builder = builder.setLoggingPrefs({ 'key': 'value' }); + builder = builder.setLoggingPrefs({ key: 'value' }); builder = builder.setProxy({ proxyType: 'type' }); builder = builder.setScrollBehavior(1); builder = builder.usingServer('http://someserver'); @@ -89,7 +89,7 @@ function TestActionSequence() { sequence = sequence.sendKeys('A', 'B', 'C'); sequence = sequence.sendKeys('A', webdriver.Key.NULL); - sequence.perform().then(function () { }); + sequence.perform().then(() => {}); } function TestTouchSequence() { @@ -111,7 +111,7 @@ function TestTouchSequence() { sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); - sequence.perform().then(function () { }); + sequence.perform().then(() => {}); } function TestAlert() { @@ -121,10 +121,10 @@ function TestAlert() { var alert: webdriver.Alert = driver.switchTo().alert(); - alert.accept().then(function () { }); - alert.dismiss().then(function () { }); - alert.getText().then(function (text: string) { }); - alert.sendKeys('ABC').then(function () { }); + alert.accept().then(() => {}); + alert.dismiss().then(() => {}); + alert.getText().then((text: string) => {}); + alert.sendKeys('ABC').then(() => {}); } function TestBrowser() { @@ -164,7 +164,7 @@ function TestCapabilities() { capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); capabilities = capabilities.set(webdriver.Capability.VERSION, null); capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences()); - capabilities = capabilities.setLoggingPrefs({ 'key': 'value' }); + capabilities = capabilities.setLoggingPrefs({ key: 'value' }); capabilities = capabilities.setProxy({ proxyType: 'Type' }); capabilities = capabilities.setEnableNativeEvents(true); capabilities = capabilities.setScrollBehavior(1); @@ -328,7 +328,7 @@ function TestCommandName() { function TestEventEmitter() { var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); - var callback = function (a: number, b: number, c: number) { }; + var callback = (a: number, b: number, c: number) => {}; emitter = emitter.addListener('ABC', callback); emitter = emitter.addListener('ABC', callback, this); @@ -453,7 +453,7 @@ function TestBy() { locatorHash = { tagName: 'tag' }; locatorHash = { xpath: 'xpath' }; - webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); + webdriver.By.js('script', 1, 2, 3)(driver).then((abc: number) => {}); } function TestSession() { @@ -470,11 +470,11 @@ function TestSession() { } function TestUnhandledAlertError() { - var someFunc = function (error: webdriver.UnhandledAlertError) { + var someFunc = (error: webdriver.UnhandledAlertError) => { var baseError: Error = error; var str: string = error.getAlertText(); str = error.toString(); - } + }; } function TestWebDriverFileDetector() { @@ -484,7 +484,7 @@ function TestWebDriverFileDetector() { var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); - fileDetector.handleFile(driver, 'path/to/file').then(function (path: string) { }); + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => {}); } function TestWebDriverLogs() { @@ -494,8 +494,8 @@ function TestWebDriverLogs() { var logs: webdriver.Logs = new webdriver.Logs(driver); - logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; - logs.getAvailableLogTypes().then(function (types: string[]) { }); + logs.get(webdriver.logging.Type.BROWSER).then((entries: webdriver.logging.Entry[]) => {}); + logs.getAvailableLogTypes().then((types: string[]) => {}); } function TestWebDriverNavigation() { @@ -505,10 +505,10 @@ function TestWebDriverNavigation() { var navigation: webdriver.Navigation = new webdriver.Navigation(driver); - navigation.back().then(function () { }); - navigation.forward().then(function () { }); - navigation.refresh().then(function () { }); - navigation.to('http://google.com').then(function () { }); + navigation.back().then(() => {}); + navigation.forward().then(() => {}); + navigation.refresh().then(() => {}); + navigation.to('http://google.com').then(() => {}); } function TestWebDriverOptions() { @@ -529,8 +529,8 @@ function TestWebDriverOptions() { promise = options.deleteAllCookies(); promise = options.deleteCookie('name'); - options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); - options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); + options.getCookie('name').then((cookies: webdriver.IWebDriverOptionsCookie) => {}); + options.getCookies().then((cookies: webdriver.IWebDriverOptionsCookie[]) => {}); var logs: webdriver.Logs = options.logs(); var timeouts: webdriver.Timeouts = options.timeouts(); @@ -600,10 +600,10 @@ function TestWebDriver() { var touchActions: webdriver.TouchSequence = driver.touchActions(); // call - stringPromise = driver.call(function () { return 'value'; }); - stringPromise = driver.call(function () { return stringPromise; }); - stringPromise = driver.call(function () { var d: any = this; return 'value'; }, driver); - stringPromise = driver.call(function (a: number) { return 'value'; }, driver, 1); + stringPromise = driver.call(() => 'value'); + stringPromise = driver.call(() => stringPromise); + stringPromise = driver.call(() => { var d: any = this; return 'value'; }, driver); + stringPromise = driver.call((a: number) => 'value', driver, 1); voidPromise = driver.close(); flow = driver.controlFlow(); @@ -611,14 +611,14 @@ function TestWebDriver() { // executeAsyncScript stringPromise = driver.executeAsyncScript('function(){}'); stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); - stringPromise = driver.executeAsyncScript(function () { }); - stringPromise = driver.executeAsyncScript(function (a: number) { }, 1); + stringPromise = driver.executeAsyncScript(() => {}); + stringPromise = driver.executeAsyncScript((a: number) => {}, 1); // executeScript stringPromise = driver.executeScript('function(){}'); stringPromise = driver.executeScript('function(){}', 1, 2, 3); - stringPromise = driver.executeScript(function () { }); - stringPromise = driver.executeScript(function (a: number) { }, 1); + stringPromise = driver.executeScript(() => {}); + stringPromise = driver.executeScript((a: number) => {}, 1); // findElement var element: webdriver.WebElement; @@ -626,15 +626,15 @@ function TestWebDriver() { element = driver.findElement(webdriver.By.js('function(){}')); // findElements - driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); + driver.findElements(webdriver.By.js('function(){}')).then((elements: webdriver.WebElement[]) => {}); voidPromise = driver.get('http://www.google.com'); - driver.getAllWindowHandles().then(function (handles: string[]) { }); - driver.getCapabilities().then(function (caps: webdriver.Capabilities) { }); + driver.getAllWindowHandles().then((handles: string[]) => {}); + driver.getCapabilities().then((caps: webdriver.Capabilities) => {}); stringPromise = driver.getCurrentUrl(); - stringPromise = driver.getPageSource() - driver.getSession().then(function (session: webdriver.Session) { });; + stringPromise = driver.getPageSource(); + driver.getSession().then((session: webdriver.Session) => {}); stringPromise = driver.getTitle(); stringPromise = driver.getWindowHandle(); @@ -656,8 +656,8 @@ function TestWebDriver() { var booleanCondition: webdriver.until.Condition; booleanPromise = driver.wait(booleanPromise); booleanPromise = driver.wait(booleanCondition); - booleanPromise = driver.wait(function (driver: webdriver.WebDriver) { return true; }); - let conditionFunction: Function; + booleanPromise = driver.wait((driver: webdriver.WebDriver) => true); + let conditionFunction: Function; // tslint:disable-line:prefer-const booleanPromise = driver.wait(conditionFunction); booleanPromise = driver.wait(booleanPromise, 123); booleanPromise = driver.wait(booleanPromise, 123, 'Message'); @@ -690,16 +690,16 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + element.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); driver = element.getDriver(); stringPromise = element.getInnerHtml(); - element.getLocation().then(function (location: webdriver.ILocation) { }); + element.getLocation().then((location: webdriver.ILocation) => {}); stringPromise = element.getOuterHtml(); - element.getSize().then(function (size: webdriver.ISize) { }); + element.getSize().then((size: webdriver.ISize) => {}); stringPromise = element.getTagName(); stringPromise = element.getText(); booleanPromise = element.isDisplayed(); @@ -711,9 +711,9 @@ function TestWebElement() { voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.sendKeys('A', 1, webdriver.Key.BACK_SPACE, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: string) { }); - element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: webdriver.IWebElementId) { }); + element.getId().then((id: string) => {}); + element.getRawId().then((id: string) => {}); + element.serialize().then((id: webdriver.IWebElementId) => {}); booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); } @@ -731,13 +731,13 @@ function TestWebElementPromise() { var bool: boolean = elementPromise.isPending(); elementPromise.then(); - elementPromise.then(function (element: webdriver.WebElement) { }); - elementPromise.then(function (element: webdriver.WebElement) { }, function (error: any) { }); - elementPromise.then(function (element: webdriver.WebElement) { return 'foo'; }, function (error: any) { }).then(function (result: string) { }); + elementPromise.then((element: webdriver.WebElement) => {}); + elementPromise.then((element: webdriver.WebElement) => {}, (error: any) => {}); + elementPromise.then((element: webdriver.WebElement) => 'foo', (error: any) => {}).then((result: string) => {}); - elementPromise.thenCatch(function (error: any) { }).then(function (value: any) { }); + elementPromise.thenCatch((error: any) => {}).then((value: any) => {}); - elementPromise.thenFinally(function () { }); + elementPromise.thenFinally(() => {}); } function TestLogging() { @@ -794,52 +794,51 @@ function TestPromiseModule() { var booleanPromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; - webdriver.promise.all([stringPromise]).then(function (values: string[]) { }); + webdriver.promise.all([stringPromise]).then((values: string[]) => {}); - webdriver.promise.asap('abc', function (value: any) { return true; }); - webdriver.promise.asap('abc', function (value: any) { }, function (err: any) { return 'ABC'; }); + webdriver.promise.asap('abc', (value: any) => true); + webdriver.promise.asap('abc', (value: any) => {}, (err: any) => 'ABC'); - stringPromise = webdriver.promise.checkedNodeCall(function (err: any, value: any) { return 'abc'; }); + stringPromise = webdriver.promise.checkedNodeCall((err: any, value: any) => 'abc'); - webdriver.promise.consume(function () { + webdriver.promise.consume(() => { return 5; - }).then(function (value: number) { }); - webdriver.promise.consume(function () { + }).then((value: number) => {}); + webdriver.promise.consume(() => { return 5; - }, this).then(function (value: number) { }); - webdriver.promise.consume(function (a: number, b: number, c: number) { - return 5; - }, this, 1, 2, 3).then(function (value: number) { }); + }, this).then((value: number) => {}); + webdriver.promise.consume((a: number, b: number, c: number) => 5, this, 1, 2, 3) + .then((value: number) => {}); - var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => { return true; }); - numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => { return true; }, this); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => { return true; }, this); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => { return true; }); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => { return true; }, this); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => { return true; }, this); var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); - stringPromise = webdriver.promise.createFlow(function (newFlow: webdriver.promise.ControlFlow) { return 'ABC' }); + stringPromise = webdriver.promise.createFlow((newFlow: webdriver.promise.ControlFlow) => 'ABC'); var deferred: webdriver.promise.Deferred; deferred = webdriver.promise.defer(); @@ -857,14 +856,14 @@ function TestPromiseModule() { stringPromise = webdriver.promise.fullyResolved('abc'); - var bool: boolean = webdriver.promise.isGenerator(function () { }); + var bool: boolean = webdriver.promise.isGenerator(() => {}); var isPromise: boolean = webdriver.promise.isPromise('ABC'); stringPromise = webdriver.promise.rejected('{a: 123}'); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); - numberPromise = webdriver.promise.when('abc', function (value: any) { return 123; }, function (err: Error) { return 123; }); + numberPromise = webdriver.promise.when('abc', (value: any) => 123, (err: Error) => 123); } function TestUntilModule() { @@ -872,7 +871,7 @@ function TestUntilModule() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', (driver: webdriver.WebDriver) => true); var conditionBBase: webdriver.until.Condition = conditionB; var conditionWebElement: webdriver.until.Condition; var conditionWebElements: webdriver.until.Condition; @@ -912,9 +911,9 @@ function TestControlFlow() { eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; var stringPromise: webdriver.promise.Promise; - stringPromise = flow.execute(function () { return 'value'; }); - stringPromise = flow.execute(function () { return stringPromise; }); - stringPromise = flow.execute(function () { return stringPromise; }, 'Description'); + stringPromise = flow.execute(() => 'value'); + stringPromise = flow.execute(() => stringPromise); + stringPromise = flow.execute(() => stringPromise, 'Description'); var schedule: string; schedule = flow.toString(); @@ -928,9 +927,9 @@ function TestControlFlow() { stringPromise = flow.wait(stringPromise); - voidPromise = flow.wait(function () { return true; }); - voidPromise = flow.wait(function () { return true; }, 123); - voidPromise = flow.wait(function () { return stringPromise; }, 123, 'Timeout Message'); + voidPromise = flow.wait(() => true); + voidPromise = flow.wait(() => true, 123); + voidPromise = flow.wait(() => stringPromise, 123, 'Timeout Message'); } function TestDeferred() { @@ -952,28 +951,22 @@ function TestDeferred() { function TestPromiseClass() { var controlFlow: webdriver.promise.ControlFlow; var promise: webdriver.promise.Promise; - promise = new webdriver.promise.Promise(function ( - resolve: (value: string) => void, - reject: () => void) { }); - promise = new webdriver.promise.Promise(function ( - resolve: (value: webdriver.promise.Promise) => void, - reject: () => void) { }); - promise = new webdriver.promise.Promise(function ( - resolve: (value: string) => void, - reject: () => void) { }, controlFlow); + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: webdriver.promise.Promise) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}, controlFlow); promise.cancel('Abort'); var isPending: boolean = promise.isPending(); promise = promise.then(); - promise = promise.then(function (a: string) { return 'cde'; }); - promise = promise.then(function (a: string) { return 'cde'; }, function (e: any) { }); - promise = promise.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); + promise = promise.then((a: string) => 'cde'); + promise = promise.then((a: string) => 'cde', (e: any) => {}); + promise = promise.then((a: string) => 'cde', (e: any) => 123); - promise = promise.thenCatch(function (error: any) { }); + promise = promise.thenCatch((error: any) => {}); - promise.thenFinally(function () { }); + promise.thenFinally(() => {}); } function TestThenableClass() { @@ -985,13 +978,13 @@ function TestThenableClass() { var isPending: boolean = thenable.isPending(); - thenable = thenable.then(function (a: string) { return 'cde'; }); - thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); - thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); + thenable = thenable.then((a: string) => 'cde'); + thenable = thenable.then((a: string) => 'cde', (e: any) => {}); + thenable = thenable.then((a: string) => 'cde', (e: any) => 123); - thenable = thenable.thenCatch(function (error: any) { }); + thenable = thenable.thenCatch((error: any) => {}); - thenable.thenFinally(function () { }); + thenable.thenFinally(() => {}); } function TestErrorCode() { @@ -1029,29 +1022,29 @@ async function TestAsyncAwaitable() { } function TestTestingModule() { - testing.before(function () { + testing.before(() => { }); - testing.beforeEach(function () { + testing.beforeEach(() => { }); - testing.describe('My test suite', function () { - testing.it('My test', function () { + testing.describe('My test suite', () => { + testing.it('My test', () => { }); - testing.iit('My exclusive test.', function () { + testing.iit('My exclusive test.', () => { }); }); - testing.xdescribe('My disabled suite', function () { - testing.xit('My disabled test.', function () { + testing.xdescribe('My disabled suite', () => { + testing.xit('My disabled test.', () => { }); }); - testing.after(function () { + testing.after(() => { }); - testing.afterEach(function () { + testing.afterEach(() => { }); } diff --git a/selenium-webdriver/testing.d.ts b/selenium-webdriver/testing.d.ts index e17c8e0f21..34d72e4627 100644 --- a/selenium-webdriver/testing.d.ts +++ b/selenium-webdriver/testing.d.ts @@ -1,63 +1,59 @@ -declare namespace testing { - /** - * Registers a new test suite. - * @param name The suite name. - * @param fn The suite function, or {@code undefined} to define a pending test suite. - */ - function describe(name: string, fn: Function): void; +/** +* Registers a new test suite. +* @param name The suite name. +* @param fn The suite function, or {@code undefined} to define a pending test suite. +*/ +export function describe(name: string, fn: Function): void; - /** - * Defines a suppressed test suite. - * @param name The suite name. - * @param fn The suite function, or {@code undefined} to define a pending test suite. - */ - function xdescribe(name: string, fn: Function): void; +/** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ +export function xdescribe(name: string, fn: Function): void; - /** - * Register a function to call after the current suite finishes. - * @param fn - */ - function after(fn: Function): void; +/** + * Register a function to call after the current suite finishes. + * @param fn + */ +export function after(fn: Function): void; - /** - * Register a function to call after each test in a suite. - * @param fn - */ - function afterEach(fn: Function): void; +/** + * Register a function to call after each test in a suite. + * @param fn + */ +export function afterEach(fn: Function): void; - /** - * Register a function to call before the current suite starts. - * @param fn - */ - function before(fn: Function): void; +/** + * Register a function to call before the current suite starts. + * @param fn + */ +export function before(fn: Function): void; - /** - * Register a function to call before each test in a suite. - * @param fn - */ - function beforeEach(fn: Function): void; +/** + * Register a function to call before each test in a suite. + * @param fn + */ +export function beforeEach(fn: Function): void; - /** - * Add a test to the current suite. - * @param name The test name. - * @param fn The test function, or {@code undefined} to define a pending test case. - */ - function it(name: string, fn: Function): void; +/** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function it(name: string, fn: Function): void; - /** - * An alias for {@link #it()} that flags the test as the only one that should - * be run within the current suite. - * @param name The test name. - * @param fn The test function, or {@code undefined} to define a pending test case. - */ - function iit(name: string, fn: Function): void; +/** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function iit(name: string, fn: Function): void; - /** - * Adds a test to the current suite while suppressing it so it is not run. - * @param name The test name. - * @param fn The test function, or {@code undefined} to define a pending test case. - */ - function xit(name: string, fn: Function): void; -} - -export = testing; \ No newline at end of file +/** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function xit(name: string, fn: Function): void; diff --git a/selenium-webdriver/tsconfig.json b/selenium-webdriver/tsconfig.json index a16c018a47..50c76c7b28 100644 --- a/selenium-webdriver/tsconfig.json +++ b/selenium-webdriver/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/selenium-webdriver/tslint.json b/selenium-webdriver/tslint.json new file mode 100644 index 0000000000..eb0befd093 --- /dev/null +++ b/selenium-webdriver/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "forbidden-types": false, + "interface-name": false, + "no-empty-interface": false, + "unified-signatures": false + } +} diff --git a/semantic-ui/index.d.ts b/semantic-ui/index.d.ts new file mode 100644 index 0000000000..bdfa5c2249 --- /dev/null +++ b/semantic-ui/index.d.ts @@ -0,0 +1,5434 @@ +// Type definitions for Semantic UI 2.2 +// Project: http://semantic-ui.com/ +// Definitions by: Leonard Thieu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + // TODO: Do all modules have a 'setting' behavior? + + // region Modules + + // region Accordion + + /** + * Refreshes all cached selectors and data + */ + accordion(behavior: 'refresh'): JQuery; + /** + * Opens accordion content at index + */ + accordion(behavior: 'open', index: number): JQuery; + /** + * Closes accordion content that are not active + */ + accordion(behavior: 'close others'): JQuery; + /** + * Closes accordion content at index + */ + accordion(behavior: 'close', index: number): JQuery; + /** + * Toggles accordion content at index + */ + accordion(behavior: 'toggle', index: number): JQuery; + accordion(settings: SemanticUI.AccordionSettings): JQuery; + accordion(): JQuery; + + // endregion + + // region Checkbox + + /** + * Switches a checkbox from current state + */ + checkbox(behavior: 'toggle'): JQuery; + /** + * Set a checkbox state to checked + */ + checkbox(behavior: 'check'): JQuery; + /** + * Set a checkbox state to unchecked + */ + checkbox(behavior: 'uncheck'): JQuery; + /** + * Set as indeterminate checkbox + */ + checkbox(behavior: 'indeterminate'): JQuery; + /** + * Set as determinate checkbox + */ + checkbox(behavior: 'determinate'): JQuery; + /** + * Enable interaction with a checkbox + */ + checkbox(behavior: 'enable'): JQuery; + /** + * Set a checkbox state to checked without callbacks + */ + checkbox(behavior: 'set checked'): JQuery; + /** + * Set a checkbox state to unchecked without callbacks + */ + checkbox(behavior: 'set unchecked'): JQuery; + /** + * Set as indeterminate checkbox without callbacks + */ + checkbox(behavior: 'set indeterminate'): JQuery; + /** + * Set as determinate checkbox without callbacks + */ + checkbox(behavior: 'set determinate'): JQuery; + /** + * Enable interaction with a checkbox without callbacks + */ + checkbox(behavior: 'set enabled'): JQuery; + /** + * Disable interaction with a checkbox without callbacks + */ + checkbox(behavior: 'set disabled'): JQuery; + /** + * Attach checkbox events to another element + */ + checkbox(behavior: 'attach events', selector: string, event: string): JQuery; + /** + * Returns whether element is radio selection + */ + checkbox(behavior: 'is radio'): boolean; + /** + * Returns whether element is currently checked + */ + checkbox(behavior: 'is checked'): boolean; + /** + * Returns whether element is not checked + */ + checkbox(behavior: 'is unchecked'): boolean; + /** + * Returns whether element is able to be changed + */ + checkbox(behavior: 'can change'): boolean; + /** + * Returns whether element can be checked (checking if already checked or `beforeChecked` would cancel) + */ + checkbox(behavior: 'should allow check'): boolean; + /** + * Returns whether element can be unchecked (checking if already unchecked or `beforeUnchecked` would cancel) + */ + checkbox(behavior: 'should allow uncheck'): boolean; + /** + * Returns whether element can be determinate (checking if already determinate or `beforeDeterminate` would cancel) + */ + checkbox(behavior: 'should allow determinate'): boolean; + /** + * Returns whether element can be indeterminate (checking if already indeterminate or `beforeIndeterminate` would cancel) + */ + checkbox(behavior: 'should allow indeterminate'): boolean; + /** + * Returns whether element is able to be unchecked + */ + checkbox(behavior: 'can uncheck'): boolean; + checkbox(settings: SemanticUI.CheckboxSettings): JQuery; + checkbox(): JQuery; + + // endregion + + // region Dimmer + + /** + * Detaches a given element from DOM and reattaches element inside dimmer + */ + dimmer(behavior: 'add content', element: SemanticUI.Selector): JQuery; + /** + * Shows dimmer + */ + dimmer(behavior: 'show'): JQuery; + /** + * Hides dimmer + */ + dimmer(behavior: 'hide'): JQuery; + /** + * Toggles current dimmer visibility + */ + dimmer(behavior: 'toggle'): JQuery; + /** + * Changes dimmer opacity + */ + dimmer(behavior: 'set opacity', opacity: number): JQuery; + /** + * Creates a new dimmer in dimmable context + */ + dimmer(behavior: 'create'): JQuery; + /** + * Returns current duration for show or hide event depending on current visibility + */ + dimmer(behavior: 'get duration'): number; + /** + * Returns DOM element for dimmer + */ + dimmer(behavior: 'get dimmer'): JQuery; + /** + * Returns whether current dimmable has a dimmer + */ + dimmer(behavior: 'has dimmer'): boolean; + /** + * Whether section's dimmer is active + */ + dimmer(behavior: 'is active'): boolean; + /** + * Whether dimmer is animating + */ + dimmer(behavior: 'is animating'): boolean; + /** + * Whether current element is a dimmer + */ + dimmer(behavior: 'is dimmer'): boolean; + /** + * Whether current element is a dimmable section + */ + dimmer(behavior: 'is dimmable'): boolean; + /** + * Whether dimmer is disabled + */ + dimmer(behavior: 'is disabled'): boolean; + /** + * Whether dimmer is not disabled + */ + dimmer(behavior: 'is enabled'): boolean; + /** + * Whether dimmable section is body + */ + dimmer(behavior: 'is page'): boolean; + /** + * Whether dimmer is a page dimmer + */ + dimmer(behavior: 'is page dimmer'): boolean; + /** + * Sets page dimmer to active + */ + dimmer(behavior: 'set active'): JQuery; + /** + * Sets an element as a dimmable section + */ + dimmer(behavior: 'set dimmable'): JQuery; + /** + * Sets a dimmable section as dimmed + */ + dimmer(behavior: 'set dimmed'): JQuery; + /** + * Sets current dimmer as a page dimmer + */ + dimmer(behavior: 'set page dimmer'): JQuery; + /** + * Sets a dimmer as disabled + */ + dimmer(behavior: 'set disabled'): JQuery; + dimmer(settings: SemanticUI.DimmerSettings): JQuery; + dimmer(): JQuery; + + // endregion + + // region Dropdown + + // TODO: Should 'value'/'values' parameters be of type 'string' instead of 'any'? + + /** + * Recreates dropdown menu from select option values. + */ + dropdown(behavior: 'setup menu'): JQuery; + /** + * Refreshes all cached selectors and data + */ + dropdown(behavior: 'refresh'): JQuery; + /** + * Toggles current visibility of dropdown + */ + dropdown(behavior: 'toggle'): JQuery; + /** + * Shows dropdown + */ + dropdown(behavior: 'show'): JQuery; + /** + * Hides dropdown + */ + dropdown(behavior: 'hide'): JQuery; + /** + * Clears dropdown of selection + */ + dropdown(behavior: 'clear'): JQuery; + /** + * Hides all other dropdowns that is not current dropdown + */ + dropdown(behavior: 'hide others'): JQuery; + /** + * Restores dropdown text and value to its value on page load + */ + dropdown(behavior: 'restore defaults'): JQuery; + /** + * Restores dropdown text to its value on page load + */ + dropdown(behavior: 'restore default text'): JQuery; + /** + * Restores dropdown text to its prompt, placeholder text + */ + dropdown(behavior: 'restore placeholder text'): JQuery; + /** + * Restores dropdown value to its value on page load + */ + dropdown(behavior: 'restore default value'): JQuery; + /** + * Saves current text and value as new defaults (for use with restore) + */ + dropdown(behavior: 'save defaults'): JQuery; + /** + * Sets value as selected + */ + dropdown(behavior: 'set selected', value: any): JQuery; + /** + * Remove value from selected + */ + dropdown(behavior: 'remove selected', value: any): JQuery; + /** + * Adds a group of values as selected + */ + dropdown(behavior: 'set selected', values: any[]): JQuery; + /** + * Sets selected values to exactly specified values, removing current selection + */ + dropdown(behavior: 'set exactly', values: any[]): JQuery; + /** + * Sets dropdown text to a value + */ + dropdown(behavior: 'set text', text: string): JQuery; + /** + * Sets dropdown input to value (does not update display state) + */ + dropdown(behavior: 'set value', value: any): JQuery; + /** + * Returns current dropdown text + */ + dropdown(behavior: 'get text'): string; + /** + * Returns current dropdown input value + */ + dropdown(behavior: 'get value'): any; + /** + * Returns DOM element that matches a given input value + */ + dropdown(behavior: 'get item', value: any): JQuery; + /** + * Adds touch events to element + */ + dropdown(behavior: 'bind touch events'): JQuery; + /** + * Adds mouse events to element + */ + dropdown(behavior: 'bind mouse events'): JQuery; + /** + * Binds a click to document to determine if you click away from a dropdown + */ + dropdown(behavior: 'bind intent'): JQuery; + /** + * Unbinds document intent click + */ + dropdown(behavior: 'unbind intent'): JQuery; + /** + * Returns whether event occurred inside dropdown + */ + dropdown(behavior: 'determine intent'): boolean; + /** + * Triggers preset item selection action based on settings passing text/value + */ + dropdown(behavior: 'determine select action', text: string, value: any): JQuery; + /** + * Sets dropdown to active state + */ + dropdown(behavior: 'set active'): JQuery; + /** + * Sets dropdown to visible state + */ + dropdown(behavior: 'set visible'): JQuery; + /** + * Removes dropdown active state + */ + dropdown(behavior: 'remove active'): JQuery; + /** + * Removes dropdown visible state + */ + dropdown(behavior: 'remove visible'): JQuery; + /** + * Returns whether dropdown is a selection dropdown + */ + dropdown(behavior: 'is selection'): boolean; + /** + * Returns whether dropdown is animated + */ + dropdown(behavior: 'is animated'): boolean; + /** + * Returns whether dropdown is visible + */ + dropdown(behavior: 'is visible'): boolean; + /** + * Returns whether dropdown is hidden + */ + dropdown(behavior: 'is hidden'): boolean; + /** + * Returns dropdown value as set on page load + */ + dropdown(behavior: 'get default text'): string; + /** + * Returns placeholder text + */ + dropdown(behavior: 'get placeholder text'): string; + dropdown(settings: SemanticUI.DropdownSettings): JQuery; + dropdown(): JQuery; + + // endregion + + // region Embed + + /** + * Changes iframe to a new content source + */ + embed(behavior: 'change', source: string, id: string, url: string): JQuery; + /** + * Removes embed and shows placeholder content if available + */ + embed(behavior: 'reset'): JQuery; + /** + * Shows embed content + */ + embed(behavior: 'show'): JQuery; + /** + * Hides embed content and shows placeholder content + */ + embed(behavior: 'hide'): JQuery; + /** + * Returns current content id + */ + embed(behavior: 'get id'): string; + /** + * Returns placeholder image url + */ + embed(behavior: 'get placeholder'): string; + /** + * Returns source name + */ + embed(behavior: 'get sources'): string; + /** + * Returns source type + */ + embed(behavior: 'get type'): string; + /** + * Returns URL with all parameters added + */ + embed(behavior: 'get url'): string; + /** + * Returns whether embed content has placeholder + */ + embed(behavior: 'has placeholder'): boolean; + /** + * Destroys instance and removes all events + */ + embed(behavior: 'destroy'): JQuery; + embed(settings: SemanticUI.EmbedSettings): JQuery; + embed(): JQuery; + + // endregion + + // region Modal + + /** + * Shows the modal + */ + modal(behavior: 'show'): JQuery; + /** + * Hides the modal + */ + modal(behavior: 'hide'): JQuery; + /** + * Toggles the modal + */ + modal(behavior: 'toggle'): JQuery; + /** + * Refreshes centering of modal on page + */ + modal(behavior: 'refresh'): JQuery; + /** + * Shows associated page dimmer + */ + modal(behavior: 'show dimmer'): JQuery; + /** + * Hides associated page dimmer + */ + modal(behavior: 'hide dimmer'): JQuery; + /** + * Hides all modals not selected modal in a dimmer + */ + modal(behavior: 'hide others'): JQuery; + /** + * Hides all visible modals in the same dimmer + */ + modal(behavior: 'hide all'): JQuery; + /** + * Caches current modal size + */ + modal(behavior: 'cache sizes'): JQuery; + /** + * Returns whether the modal can fit on the page + */ + modal(behavior: 'can fit'): boolean; + /** + * Returns whether the modal is active + */ + modal(behavior: 'is active'): boolean; + /** + * Sets modal to active + */ + modal(behavior: 'set active'): JQuery; + modal(behavior: 'attach events', selector: SemanticUI.Selector, event?: string): JQuery; + modal(behavior: 'setting', name: string, value: any): JQuery; + modal(settings: SemanticUI.ModalSettings): JQuery; + modal(): JQuery; + + // endregion + + // region Nag + + // TODO: Documentation is lacking. Is it possible to infer intended behaviors? + + nag(behavior: 'show'): JQuery; + /** + * Clears cookie so nag shows again + */ + nag(behavior: 'clear'): JQuery; + nag(settings: SemanticUI.NagSettings): JQuery; + + // endregion + + // region Popup + + /** + * Shows popup + */ + popup(behavior: 'show'): JQuery; + /** + * Hides popup + */ + popup(behavior: 'hide'): JQuery; + /** + * Hides all visible pop ups on the page + */ + popup(behavior: 'hide all'): JQuery; + /** + * Returns current popup dom element + */ + popup(behavior: 'get popup'): JQuery; + /** + * Changes current popup content + */ + popup(behavior: 'change content', html: string): JQuery; + /** + * Toggles visibility of popup + */ + popup(behavior: 'toggle'): JQuery; + /** + * Returns whether popup is visible + */ + popup(behavior: 'is visible'): boolean; + /** + * Returns whether popup is hidden + */ + popup(behavior: 'is hidden'): boolean; + /** + * Returns whether popup is created and inserted into the page + */ + popup(behavior: 'exists'): boolean; + /** + * Adjusts popup when content size changes (only necessary for centered popups) + */ + popup(behavior: 'reposition'): JQuery; + /** + * Repositions a popup + */ + popup(behavior: 'set position', position: string): JQuery; + /** + * Removes popup from the page and removes all events + */ + popup(behavior: 'destroy'): JQuery; + /** + * Removes popup from the page + */ + popup(behavior: 'remove popup'): JQuery; + popup(settings: SemanticUI.PopupSettings): JQuery; + popup(): JQuery; + + // endregion + + // region Progress + + /** + * Sets current percent of progress to value. If using a total will convert from percent to estimated value. + */ + progress(behavior: 'set percent', percent: number): JQuery; + /** + * Sets progress to specified value. Will automatically calculate percent from total. + */ + progress(behavior: 'set progress', value: number): JQuery; + /** + * Increments progress by increment value, if not passed a value will use random amount specified in settings + */ + progress(behavior: 'increment', incrementValue: number): JQuery; + /** + * Decrements progress by decrement value, if not passed a value will use random amount specified in settings + */ + progress(behavior: 'decrement', decrementValue: number): JQuery; + /** + * Immediately updates progress to value, ignoring progress animation interval delays + */ + progress(behavior: 'update progress', value: number): JQuery; + /** + * Finishes progress and sets loaded to 100% + */ + progress(behavior: 'complete'): JQuery; + /** + * Resets progress to zero + */ + progress(behavior: 'reset'): JQuery; + /** + * Set total to a new value + */ + progress(behavior: 'set total', total: number): JQuery; + /** + * Replaces templated string with value, total, percent left and percent. + */ + progress(behavior: 'get text', text: string): string; + /** + * Returns normalized value inside acceptable range specified by total. + */ + progress(behavior: 'get normalized value', value: number): number; + /** + * Returns percent as last specified + */ + progress(behavior: 'get percent'): number; + /** + * Returns current progress value + */ + progress(behavior: 'get value'): number; + /** + * Returns total + */ + progress(behavior: 'get total'): number; + /** + * Returns whether progress is completed + */ + progress(behavior: 'is complete'): boolean; + /** + * Returns whether progress was a success + */ + progress(behavior: 'is success'): boolean; + /** + * Returns whether progress is in warning state + */ + progress(behavior: 'is warning'): boolean; + /** + * Returns whether progress is in error state + */ + progress(behavior: 'is error'): boolean; + /** + * Returns whether progress is in active state + */ + progress(behavior: 'is active'): boolean; + /** + * Sets progress to active state + */ + progress(behavior: 'set active'): JQuery; + /** + * Sets progress to warning state + */ + progress(behavior: 'set warning'): JQuery; + /** + * Sets progress to success state + */ + progress(behavior: 'set success'): JQuery; + /** + * Sets progress to error state + */ + progress(behavior: 'set error'): JQuery; + /** + * Changes progress animation speed + */ + progress(behavior: 'set duration', value: number): JQuery; + /** + * Sets progress exterior label to text + */ + progress(behavior: 'set label', text: string): JQuery; + /** + * Sets progress bar label to text + */ + progress(behavior: 'set bar label', text: string): JQuery; + /** + * Removes progress to active state + */ + progress(behavior: 'remove active'): JQuery; + /** + * Removes progress to warning state + */ + progress(behavior: 'remove warning'): JQuery; + /** + * Removes progress to success state + */ + progress(behavior: 'remove success'): JQuery; + /** + * Removes progress to error state + */ + progress(behavior: 'remove error'): JQuery; + progress(settings: SemanticUI.ProgressSettings): JQuery; + progress(): JQuery; + + // endregion + + // region Rating + + /** + * Sets rating programmatically + */ + rating(behavior: 'set rating', rating: number): JQuery; + /** + * Gets current rating + */ + rating(behavior: 'get rating'): number; + /** + * Disables interactive rating mode + */ + rating(behavior: 'disable'): JQuery; + /** + * Enables interactive rating mode + */ + rating(behavior: 'enable'): JQuery; + /** + * Clears current rating + */ + rating(behavior: 'clear rating'): JQuery; + rating(settings: SemanticUI.RatingSettings): JQuery; + rating(): JQuery; + + // endregion + + // region Search + + /** + * Search for value currently set in search input + */ + search(behavior: 'query'): JQuery; + /** + * Displays message in search results with text, using template matching type + */ + search(behavior: 'display message', text: string, type: string): JQuery; + /** + * Cancels current remote search query + */ + search(behavior: 'cancel query'): JQuery; + /** + * Search local object for specified query and display results + */ + search(behavior: 'search local', query: string): JQuery; + /** + * Whether has minimum characters + */ + search(behavior: 'has minimum characters'): boolean; + /** + * Search remote endpoint for specified query and display results + */ + search(behavior: 'search remote', query: string): JQuery; + /** + * Search object for specified query and return results + */ + search(behavior: 'search object', query: string, object: any, searchFields: string[]): any; + /** + * Cancels current remote search request + */ + search(behavior: 'cancel query'): JQuery; + /** + * Whether search is currently focused + */ + search(behavior: 'is focused'): boolean; + /** + * Whether search results are visible + */ + search(behavior: 'is visible'): boolean; + /** + * Whether search results are empty + */ + search(behavior: 'is empty'): boolean; + /** + * Returns current search value + */ + search(behavior: 'get value'): any; + /** + * Returns JSON object matching searched title or id (see above) + */ + search(behavior: 'get result', value: any): any; + /** + * Sets search input to value + */ + search(behavior: 'set value', value: any): JQuery; + /** + * Reads cached results for query + */ + search(behavior: 'read cache', query: string): JQuery; + /** + * Clears value from cache, if no parameter passed clears all cache + */ + search(behavior: 'clear cache', query?: string): JQuery; + /** + * Writes cached results for query + */ + search(behavior: 'write cache', query: string): JQuery; + /** + * Adds HTML to results and displays + */ + search(behavior: 'add results', html: string): JQuery; + /** + * Shows results container + */ + search(behavior: 'show results'): JQuery; + /** + * Hides results container + */ + search(behavior: 'hide results'): JQuery; + /** + * Generates results using parser specified by settings.template + */ + search(behavior: 'generate results', response: any): JQuery; + /** + * Removes all events + */ + search(behavior: 'destroy'): JQuery; + search(settings: SemanticUI.SearchSettings): JQuery; + search(): JQuery; + + // endregion + + // region Shape + + /** + * Flips the shape upward + */ + shape(behavior: 'flip up'): JQuery; + /** + * Flips the shape downward + */ + shape(behavior: 'flip down'): JQuery; + /** + * Flips the shape right + */ + shape(behavior: 'flip right'): JQuery; + /** + * Flips the shape left + */ + shape(behavior: 'flip left'): JQuery; + /** + * Flips the shape over clock-wise + */ + shape(behavior: 'flip over'): JQuery; + /** + * Flips the shape over counter-clockwise + */ + shape(behavior: 'flip back'): JQuery; + /** + * Set the next side to a specific selector + */ + shape(behavior: 'set next side', selector: SemanticUI.Selector): JQuery; + /** + * Returns whether shape is currently animating + */ + shape(behavior: 'is animating'): boolean; + /** + * Removes all inline styles + */ + shape(behavior: 'reset'): JQuery; + /** + * Queues an animation until after current animation + */ + shape(behavior: 'queue', animation: string): JQuery; + /** + * Forces a reflow on element + */ + shape(behavior: 'repaint'): JQuery; + /** + * Set the next side to next sibling to active element + */ + shape(behavior: 'set default side'): JQuery; + /** + * Sets shape to the content size of the next side + */ + shape(behavior: 'set stage size'): JQuery; + /** + * Refreshes the selector cache for element sides + */ + shape(behavior: 'refresh'): JQuery; + /** + * Returns translation for next side staged below + */ + shape(behavior: 'get transform down'): SemanticUI.Translation; + /** + * Returns translation for next side staged left + */ + shape(behavior: 'get transform left'): SemanticUI.Translation; + /** + * Returns translation for next side staged right + */ + shape(behavior: 'get transform right'): SemanticUI.Translation; + /** + * Returns translation for next side staged up + */ + shape(behavior: 'get transform up'): SemanticUI.Translation; + /** + * Returns translation for next side staged down + */ + shape(behavior: 'get transform down'): SemanticUI.Translation; + shape(settings: SemanticUI.ShapeSettings): JQuery; + shape(): JQuery; + + // endregion + + // region Sidebar + + /** + * Attaches sidebar action to given selector. Default event if none specified is toggle + */ + sidebar(behavior: 'attach events', selector: string, event?: string): JQuery; + /** + * Shows sidebar + */ + sidebar(behavior: 'show'): JQuery; + /** + * Hides sidebar + */ + sidebar(behavior: 'hide'): JQuery; + /** + * Toggles visibility of sidebar + */ + sidebar(behavior: 'toggle'): JQuery; + /** + * Returns whether sidebar is visible + */ + sidebar(behavior: 'is visible'): boolean; + /** + * Returns whether sidebar is hidden + */ + sidebar(behavior: 'is hidden'): boolean; + /** + * Pushes page content to be visible alongside sidebar + */ + sidebar(behavior: 'push page'): JQuery; + /** + * Returns direction of current sidebar + */ + sidebar(behavior: 'get direction'): string; + /** + * Returns page content to original position + */ + sidebar(behavior: 'pull page'): JQuery; + /** + * Adds stylesheet to page head to trigger sidebar animations + */ + sidebar(behavior: 'add body CSS'): JQuery; + /** + * Removes any inline stylesheets for sidebar animation + */ + sidebar(behavior: 'remove body CSS'): JQuery; + /** + * Returns vendor prefixed transition end event + */ + sidebar(behavior: 'get transition event'): string; + sidebar(settings: SemanticUI.SidebarSettings): JQuery; + sidebar(): JQuery; + + // endregion + + // region Sticky + + /** + * recalculates offsets + */ + sticky(behavior: 'refresh'): JQuery; + sticky(settings: SemanticUI.StickySettings): JQuery; + sticky(): JQuery; + + // endregion + + // region Tab + + /** + * Attaches tab action to given selector. Default event if none specified is toggle + */ + tab(behavior: 'attach events', selector: string, event?: string): JQuery; + /** + * Changes tab to path + */ + tab(behavior: 'change tab', path: string): JQuery; + /** + * Sets current path to state + */ + tab(behavior: 'set state', path: string): JQuery; + /** + * Returns current path + */ + tab(behavior: 'get path'): string; + /** + * Returns whether tab exists + */ + tab(behavior: 'is tab'): boolean; + /** + * Returns cached HTML for path + */ + tab(behavior: 'cache read', path: string): string | false; + /** + * Sets cached HTML for path + */ + tab(behavior: 'cache add', path: string, html: string): JQuery; + /** + * Removes cached HTML for path + */ + tab(behavior: 'cache remove', path: string): JQuery; + tab(settings: SemanticUI.TabSettings): JQuery; + tab(): JQuery; + + // endregion + + // region Transition + + /** + * Stop current animation and preserve queue + */ + transition(behavior: 'stop'): JQuery; + /** + * Stop current animation and queued animations + */ + transition(behavior: 'stop all'): JQuery; + /** + * Clears all queued animations + */ + transition(behavior: 'clear queue'): JQuery; + /** + * Stop current animation and show element + */ + transition(behavior: 'show'): JQuery; + /** + * Stop current animation and hide element + */ + transition(behavior: 'hide'): JQuery; + /** + * Toggles between hide and show + */ + transition(behavior: 'toggle'): JQuery; + /** + * Forces reflow using a more expensive but stable method + */ + transition(behavior: 'force repaint'): JQuery; + /** + * Triggers reflow on element + */ + transition(behavior: 'repaint'): JQuery; + /** + * Resets all conditions changes during transition + */ + transition(behavior: 'reset'): JQuery; + /** + * Enables animation looping + */ + transition(behavior: 'looping'): JQuery; + /** + * Removes looping state from element + */ + transition(behavior: 'remove looping'): JQuery; + /** + * Adds disabled state (stops ability to animate) + */ + transition(behavior: 'disable'): JQuery; + /** + * Removes disabled state + */ + transition(behavior: 'enable'): JQuery; + /** + * Modifies element animation duration + */ + transition(behavior: 'set duration', duration: number): JQuery; + /** + * Saves all class names and styles to cache to be retrieved after animation + */ + transition(behavior: 'save conditions'): JQuery; + /** + * Adds back cached names and styles to element + */ + transition(behavior: 'restore conditions'): JQuery; + /** + * Returns vendor prefixed animation property for animationname + */ + transition(behavior: 'get animation name'): string; + /** + * Returns vendor prefixed animation property for animationend + */ + transition(behavior: 'get animation event'): string; + /** + * Returns whether element is currently visible + */ + transition(behavior: 'is visible'): boolean; + /** + * Returns whether transition is currently occurring + */ + transition(behavior: 'is animating'): boolean; + /** + * Returns whether animation looping is set + */ + transition(behavior: 'is looping'): boolean; + /** + * Returns whether animations are supported + */ + transition(behavior: 'is supported'): boolean; + transition(transition: string): JQuery; + transition(settings: SemanticUI.TransitionSettings): JQuery; + transition(): JQuery; + + // endregion + + // endregion + + // region Behaviors + + // region API + + /** + * Execute query using existing API settings + */ + api(behavior: 'query'): JQuery; + /** + * Adds data to existing templated url and returns full url string + */ + api(behavior: 'add url data', url: string, data: any): string; + /** + * Gets promise for current API request + */ + api(behavior: 'get request'): JQueryDeferred | false; + /** + * Aborts current API request + */ + api(behavior: 'abort'): JQuery; + /** + * Removes loading and error state from element + */ + api(behavior: 'reset'): JQuery; + /** + * Returns whether last request was cancelled + */ + api(behavior: 'was cancelled'): boolean; + /** + * Returns whether last request was failure + */ + api(behavior: 'was failure'): boolean; + /** + * Returns whether last request was successful + */ + api(behavior: 'was successful'): boolean; + /** + * Returns whether last request was completed + */ + api(behavior: 'was complete'): boolean; + /** + * Returns whether element is disabled + */ + api(behavior: 'is disabled'): boolean; + /** + * Returns whether element response is mocked + */ + api(behavior: 'is mocked'): boolean; + /** + * Returns whether element is loading + */ + api(behavior: 'is loading'): boolean; + /** + * Sets loading state to element + */ + api(behavior: 'set loading'): JQuery; + /** + * Sets error state to element + */ + api(behavior: 'set error'): JQuery; + /** + * Removes loading state to element + */ + api(behavior: 'remove loading'): JQuery; + /** + * Removes error state to element + */ + api(behavior: 'remove error'): JQuery; + /** + * Gets event that API request will occur on + */ + api(behavior: 'get event'): string; + /** + * Returns encodeURIComponent value only if value passed is not already encoded + */ + api(behavior: 'get url encoded value', value: any): string; + /** + * Reads a locally cached response for a URL + */ + api(behavior: 'read cached response', url: string): any; + /** + * Writes a cached response for a URL + */ + api(behavior: 'write cached response', url: string, response: any): JQuery; + /** + * Creates new cache, removing all locally cached URLs + */ + api(behavior: 'create cache'): JQuery; + /** + * Removes API settings from the page and all events + */ + api(behavior: 'destroy'): JQuery; + api(settings: SemanticUI.ApiSettings): JQuery; + api(): JQuery; + + // endregion + + // region Form Validation + + /** + * Submits selected form + */ + form(behavior: 'submit'): JQuery; + /** + * Returns true/false whether a form passes its validation rules + */ + form(behavior: 'is valid'): boolean; + /** + * Validates form and calls onSuccess or onFailure + */ + form(behavior: 'validate form'): JQuery; + /** + * gets browser property change event + */ + form(behavior: 'get change event'): string; + /** + * Returns element with matching name, id, or data-validate metadata to ID + */ + form(behavior: 'get field', id: string): JQuery; + /** + * Returns value of element with id + */ + form(behavior: 'get value', id: string): any; + /** + * Returns object of element values that match array of ids. If no IDS are passed will return all fields + */ + form(behavior: 'get values', ids?: string[]): any; + /** + * Sets value of element with id + */ + form(behavior: 'set value', id: string): JQuery; + /** + * Sets key/value pairs from passed values object to matching ids + */ + form(behavior: 'set values', values: any): JQuery; + /** + * Returns validation rules for a given jQuery-referenced input field + */ + form(behavior: 'get validation', element: JQuery): any; + /** + * Returns whether a field exists + */ + form(behavior: 'has field', identifier: string): boolean; + /** + * Adds errors to form, given an array errors + */ + form(behavior: 'add errors', errors: string[]): JQuery; + form(settings: SemanticUI.FormSettings): JQuery; + form(): JQuery; + + // endregion + + // region Visibility + + /** + * Disable callbacks temporarily. This is useful if you need to adjust scroll position and do not want to trigger callbacks during the position change. + */ + visibility(behavior: 'disable callbacks'): JQuery; + /** + * Re-enable callbacks + */ + visibility(behavior: 'enable callbacks'): JQuery; + /** + * Returns whether element is on screen + */ + visibility(behavior: 'is on screen'): boolean; + /** + * Returns whether element is off screen + */ + visibility(behavior: 'is off screen'): boolean; + /** + * Returns number of pixels passed in current element from top of element + */ + visibility(behavior: 'get pixels passed'): number; + /** + * Returns element calculations as object + */ + visibility(behavior: 'get element calculations'): SemanticUI.ElementCalculations; + /** + * Returns screen calculations as object + */ + visibility(behavior: 'get screen calculations'): SemanticUI.ScreenCalculations; + /** + * Returns screen size as object + */ + visibility(behavior: 'get screen size'): SemanticUI.ScreenSize; + visibility(settings: SemanticUI.VisibilitySettings): JQuery; + visibility(): JQuery; + + // endregion + + // endregion +} + +declare namespace SemanticUI { + type Selector = string | JQuery; + + /** + * These settings are native to all modules, and define how the component ties content to DOM attributes, and debugging settings for the module. + */ + interface ComponentSettings { + // region DOM Settings + + /** + * Event namespace. Makes sure module teardown does not effect other events attached to an element. + */ + namespace?: string; + + // endregion + + // region Debug Settings + + /** + * Name used in log statements + */ + name?: string; + /** + * Silences all console output including error messages, regardless of other debug settings. + */ + silent?: boolean; + /** + * Debug output to console + */ + debug?: boolean; + /** + * Show console.table output with performance metrics + */ + performance?: boolean; + /** + * Debug output includes all internal behaviors + */ + verbose?: boolean; + + // endregion + } + + // region Modules + + // region Accordion + + /** + * @see {@link http://semantic-ui.com/modules/accordion.html#/settings} + */ + interface AccordionSettings extends ComponentSettings { + // region Behavior + + /** + * Only allow one section open at a time + * + * @default true + */ + exclusive?: boolean; + /** + * Event on title that will cause accordion to open + * + * @default 'click' + */ + on?: string; + /** + * Whether child content opacity should be animated (may cause performance issues with many child elements) + * + * @default true + */ + animateChildren?: boolean; + /** + * Close open nested accordion content when an element closes + * + * @default true + */ + closeNested?: boolean; + /** + * Allow active sections to collapse + * + * @default true + */ + collapsible?: boolean; + /** + * Duration in ms of opening animation + * + * @default 500 + */ + duration?: number; + /** + * Easing of opening animation. EaseInOutQuint is included with accordion, for additional options you must include easing equations. + * + * @default 'easeInOutQuint' + * @see {@link http://gsgd.co.uk/sandbox/jquery/easing/} + */ + easing?: string; + // TODO: Undocumented but probably intended to be public? + // observeChanges?: boolean; + + // endregion + + // region Callbacks + + /** + * Callback before element opens + */ + onOpening?: (this: JQuery) => void; + /** + * Callback after element is open + */ + onOpen?: (this: JQuery) => void; + /** + * Callback before element closes + */ + onClosing?: (this: JQuery) => void; + /** + * Callback after element is closed + */ + onClose?: (this: JQuery) => void; + /** + * Callback on element open or close + */ + onChange?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + /** + * Selectors used to find parts of a module + */ + selector?: { + /** + * @default '.accordion' + */ + accordion?: string; + /** + * @default '.title' + */ + title?: string; + /** + * @default '.title' + */ + trigger?: string; + /** + * @default '.content' + */ + content?: string; + }; + /** + * Class names used to determine element state + */ + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'animating' + */ + animating?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Checkbox + + /** + * @see {@link http://semantic-ui.com/modules/checkbox.html#/settings} + */ + interface CheckboxSettings extends ComponentSettings { + // region Behavior + + /** + * Setting to true/false will determine whether an input will allow no selection. Auto will set disallow this behavior only for radio boxes + * + * @default 'auto' + */ + uncheckable?: 'auto' | boolean; + /** + * Whether callbacks for checked status should be fired on init as well as change + * + * @default false + */ + fireOnInit?: boolean; + + // endregion + + // region Callbacks + + /** + * Callback after a checkbox is either checked or unchecked. + */ + onChange?: (this: HTMLElement) => void; + /** + * Callback after a checkbox is checked. + */ + onChecked?: (this: HTMLElement) => void; + /** + * Callback after a checkbox is set to undeterminate. + */ + onIndeterminate?: (this: HTMLElement) => void; + /** + * Callback after a checkbox is set to determinate. + */ + onDeterminate?: (this: HTMLElement) => void; + /** + * Callback after a checkbox is unchecked. + */ + onUnchecked?: (this: HTMLElement) => void; + /** + * Callback before a checkbox is checked. Can cancel change by returning false + */ + beforeChecked?: (this: HTMLElement) => boolean; + /** + * Callback before a checkbox is set to undeterminate. Can cancel change by returning false + */ + beforeIndeterminate?: (this: HTMLElement) => boolean; + /** + * Callback before a checkbox is set to determinate. Can cancel change by returning false + */ + beforeDeterminate?: (this: HTMLElement) => boolean; + /** + * Callback before a checkbox is unchecked. Can cancel change by returning false + */ + beforeUnchecked?: (this: HTMLElement) => boolean; + /** + * Callback after a checkbox is enabled. + */ + onEnable?: (this: HTMLElement) => void; + /** + * Callback after a checkbox is disabled. + */ + onDisable?: (this: HTMLElement) => void; + /** + * Callback after a checkbox is enabled. + * + * @deprecated + */ + onEnabled?: (this: HTMLElement) => void; + /** + * Callback after a checkbox is disabled. + * + * @deprecated + */ + onDisabled?: (this: HTMLElement) => void; + + // endregion + + // region DOM Settings + + /** + * Selectors used to find parts of a module + */ + selector?: { + /** + * @default 'input[type=checkbox], input[type=radio]' + */ + input?: string; + /** + * @default 'label' + */ + label?: string; + }; + /** + * Class names used to determine element state + */ + className?: { + /** + * @default 'checked' + */ + checked?: string; + /** + * @default 'disabled' + */ + disabled?: string; + /** + * @default 'radio' + */ + radio?: string; + /** + * @default 'read-only' + */ + readOnly?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Dimmer + + /** + * @see {@link http://semantic-ui.com/modules/dimmer.html#/settings} + */ + interface DimmerSettings extends ComponentSettings { + // region Behavior + + /** + * Dimmers opacity from 0-1. Defaults to auto which uses the CSS specified opacity. + * + * @default 'auto' + */ + opacity?: 'auto' | number; + /** + * Specify a variation to add when generating dimmer, like inverted + * + * @default false + */ + variation?: false | string; + /** + * If initializing a dimmer on a dimmable context, you can use dimmerName to distinguish between multiple dimmers in that context. + * + * @default false + */ + dimmerName?: false | string; + /** + * Whether clicking on the dimmer should hide the dimmer (Defaults to auto, closable only when settings.on is not hover + * + * @default 'auto' + */ + closable?: 'auto' | boolean; + /** + * Can be set to hover or click to show/hide dimmer on dimmable event + * + * @default false + */ + on?: false | 'hover' | 'click'; + /** + * Whether to dim dimmers using CSS transitions. + * + * @default true + */ + useCSS?: boolean; + /** + * Animation duration of dimming. If an integer is used, that value will apply to both show and hide animations. + */ + duration?: number | { + /** + * @default 500 + */ + show?: number; + /** + * @default 500 + */ + hide?: number; + }; + /** + * Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions + * + * @default 'fade' + * @see {@link http://semantic-ui.com/modules/transition.html} + */ + transition?: string; + + // endregion + + // region Callbacks + + /** + * Callback on element show + */ + onShow?: (this: JQuery) => void; + /** + * Callback on element hide + */ + onHide?: (this: JQuery) => void; + /** + * Callback on element show or hide + */ + onchange?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + /** + * Object containing selectors used by module. + */ + selector?: { + /** + * @default '.dimmable' + */ + dimmable?: string; + /** + * @default '.ui.dimmer' + */ + dimmer?: string; + /** + * @default '.ui.dimmer > .content, .ui.dimmer > .content > .center' + */ + content?: string; + }; + /** + * Templates used to generate dimmer content + */ + template?: { + dimmer?: () => JQuery; + }; + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'dimmable' + */ + dimmable?: string; + /** + * @default 'dimmed' + */ + dimmed?: string; + /** + * @default 'disabled' + */ + disabled?: string; + /** + * @default 'page' + */ + pageDimmer?: string; + /** + * @default 'hide' + */ + hide?: string; + /** + * @default 'show' + */ + show?: string; + /** + * @default 'transition' + */ + transition?: string; + }; + + // endregion + + // region Debug Settings + + /** + * Error messages displayed to console + */ + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Dropdown + + /** + * @see {@link http://semantic-ui.com/modules/dropdown.html#/settings} + */ + interface DropdownSettings extends ComponentSettings { + // TODO: Should 'value'/'values' parameters be of type 'string' instead of 'any'? + + // region Frequently Used Settings + + /** + * Event used to trigger dropdown (Hover, Click, Custom Event) + * + * @default 'click' + */ + on?: string; + /** + * When set to true will fire onChange even when the value a user select matches the currently selected value. + * + * @default false + */ + allowReselection?: boolean; + /** + * Whether search selection should allow users to add their own selections, works for single or multi-select. + * + * @default false + */ + allowAdditions?: boolean; + /** + * When disabled user additions will appear in the results menu using a specially formatted selection item formatted by templates.addition. + * + * @default true + */ + hideAdditions?: boolean; + /** + * Sets a default action to occur. (See usage guide) + * + * @default 'activate' + * @see {@link http://semantic-ui.com/modules/dropdown.html#/usage} + */ + action?: 'activate' | 'select' | 'combo' | 'nothing' | 'hide' | ((this: JQuery, text: string, value: string | false, element: JQuery) => void); + /** + * The minimum characters for a search to begin showing results + * + * @default 1 + */ + minCharacters?: number; + /** + * When using search selection specifies how to match values. + * + * @default 'both' + */ + match?: 'both' | 'value' | 'text'; + /** + * Whether dropdown should select new option when using keyboard shortcuts. Setting to false will require enter or left click to confirm a choice. + * + * @default true + */ + selectOnKeydown?: boolean; + /** + * Whether search selection will force currently selected choice when element is blurred. + * + * @default true + */ + forceSelection?: boolean; + /** + * Whether menu items with sub-menus (categories) should be selectable + * + * @default false + */ + allowCategorySelection?: boolean; + /** + * @default 'auto' + */ + placeholder?: 'auto' | 'value' | false; + + // endregion + + // region Remote Settings + + /** + * Can be set to an object to specify API settings for retrieving remote selection menu content from an API endpoint + * + * @default false + * @see {@link http://semantic-ui.com/behaviors/api.html} + */ + apiSettings?: false | ApiSettings; + /** + * List mapping dropdown content to JSON Property when using API + */ + fields?: { + /** + * grouping for api results + * + * @default 'results' + */ + remoteValues?: string; + /** + * grouping for all dropdown values + * + * @default 'values' + */ + values?: string; + /** + * displayed dropdown text + * + * @default 'name' + */ + name?: string; + /** + * actual dropdown value + * + * @default 'value' + */ + value?: string; + }; + /** + * When enabled will automatically store selected name/value pairs in sessionStorage to preserve user selection on page refresh. Disabling will clear remote dropdown values on refresh. + * + * @default true + */ + saveRemoteData?: boolean; + + // endregion + + // region Multiple Select Settings + + /** + * Whether multiselect should use labels. Must be set to true when allowAdditions is true + * + * @default true + */ + useLabels?: boolean; + /** + * When set to a number, sets the maximum number of selections + * + * @default false + */ + maxSelections?: boolean; + /** + * Maximum glyph width, used to calculate search size. This is usually size of a "W" in your font in em + * + * @default 1.0714 + */ + glyphWidth?: number; + /** + * Allows customization of multi-select labels + */ + label?: { + /** + * @default 'horizontal flip' + */ + transition?: string; + /** + * @default 200 + */ + duration?: number; + /** + * @default false + */ + variation?: false | string; + }; + + // endregion + + // region Additional Settings + + /** + * When set to auto determines direction based on whether dropdown can fit on screen. Set to upward or downward to always force a direction. + * + * @default 'auto' + */ + direction?: 'auto' | 'upward' | 'downward'; + /** + * Whether dropdown should try to keep itself on screen by checking whether menus display position in its context (Default context is page). + * + * @default true + */ + keepOnScreen?: boolean; + /** + * Element context to use when checking whether can show when keepOnScreen: true + * + * @default 'window' + */ + context?: Selector; + /** + * Specifying to "true" will use a fuzzy full text search, setting to "exact" will force the exact search to be matched somewhere in the string + * + * @default false + */ + fullTextSearch?: boolean | 'exact'; + /** + * Whether HTML included in dropdown values should be preserved. (Allows icons to show up in selected value) + * + * @default true + */ + preserveHTML?: boolean; + /** + * Whether to sort values when creating a dropdown automatically from a select element. + * + * @default false + */ + sortSelect?: boolean; + /** + * Whether to show dropdown menu automatically on element focus. + * + * @default true + */ + showOnFocus?: boolean; + /** + * Whether to allow the element to be navigable by keyboard, by automatically creating a tabindex + * + * @default true + */ + allowTab?: boolean; + /** + * Named transition to use when animating menu in and out. + * Defaults to slide down or slide up depending on dropdown direction. + * Fade and slide down are available without including ui transitions + * + * @default 'auto' + * @see {@link http://semantic-ui.com/modules/transition.html} + */ + transition?: 'auto' | string; + /** + * Duration of animation events + * + * @default 200 + */ + duration?: number; + /** + * The keycode used to represent keyboard shortcuts. To avoid issues with some foreign languages, you can pass false for comma delimiter's value + */ + keys?: { + /** + * @default 8 + */ + backspace?: number; + /** + * @default 188 + */ + delimiter?: number | false; + /** + * @default 46 + */ + deleteKey?: number; + /** + * @default 13 + */ + enter?: number; + /** + * @default 27 + */ + escape?: number; + /** + * @default 33 + */ + pageUp?: number; + /** + * @default 34 + */ + pageDown?: number; + /** + * @default 37 + */ + leftArrow?: number; + /** + * @default 38 + */ + upArrow?: number; + /** + * @default 39 + */ + rightArrow?: number; + /** + * @default 40 + */ + downArrow?: number; + }; + /** + * Time in milliseconds to debounce show or hide behavior when on: hover is used, or when touch is used. + */ + delay?: { + /** + * @default 300 + */ + hide?: number; + /** + * @default 200 + */ + show?: number; + /** + * @default 50 + */ + search?: number; + /** + * @default 50 + */ + touch?: number; + }; + + // endregion + + // region Callbacks + + /** + * Is called after a dropdown value changes. Receives the name and value of selection and the active menu element + */ + onChange?: (this: JQuery, value: any, text: string, $choice: JQuery) => void; + /** + * Is called after a dropdown selection is added using a multiple select dropdown, only receives the added value + */ + onAdd?: (this: JQuery, addedValue: any, addedText: string, $addedChoice: JQuery) => void; + /** + * Is called after a dropdown selection is removed using a multiple select dropdown, only receives the removed value + */ + onRemove?: (this: JQuery, removedValue: any, removedText: string, $removedChoice: JQuery) => void; + /** + * Allows you to modify a label before it is added. Expects the jQ DOM element for a label to be returned. + */ + onLabelCreate?: (this: JQuery, value: any, text: string) => JQuery; + /** + * Called when a label is remove, return false; will prevent the label from being removed. + */ + onLabelRemove?: (this: JQuery, value: any) => false | void; + /** + * Is called after a label is selected by a user + */ + onLabelSelect?: (this: JQuery, $selectedLabels: JQuery) => void; + /** + * Is called after a dropdown is searched with no matching values + */ + onNoResults?: (this: JQuery, searchValue: any) => void; + /** + * Is called before a dropdown is shown. If false is returned, dropdown will not be shown. + */ + onShow?: (this: JQuery) => false | void; + /** + * Is called before a dropdown is hidden. If false is returned, dropdown will not be hidden. + */ + onHide?: (this: JQuery) => false | void; + + // endregion + + // region DOM Settings + + /** + * You can specify site wide messages by modifying $.fn.dropdown.settings.message that will apply on any dropdown if it appears in the page. + */ + message?: { + /** + * @default 'Add {term}' + */ + addResult?: string; + /** + * @default '{count} selected' + */ + count?: string; + /** + * @default 'Max {maxCount} selections' + */ + maxSelections?: string; + /** + * 'No results found.' + */ + noResults?: string; + }; + selector?: { + /** + * @default '.addition' + */ + addition?: string; + /** + * @default '.ui.dropdown' + */ + dropdown?: string; + /** + * @default '> .dropdown.icon' + */ + icon?: string; + /** + * @default '> input[type="hidden"], > select' + */ + input?: string; + /** + * @default '.item' + */ + item?: string; + /** + * @default '> .label' + */ + label?: string; + /** + * @default '> .label > .delete.icon' + */ + remove?: string; + /** + * @default '.label' + */ + siblingLabel?: string; + /** + * @default '.menu' + */ + menu?: string; + /** + * @default '.message' + */ + message?: string; + /** + * @default '.dropdown.icon' + */ + menuIcon?: string; + /** + * @default 'input.search, .menu > .search > input' + */ + search?: string; + /** + * @default '> .text:not(.icon)' + */ + text?: string; + }; + regExp?: { + /** + * @default /[-[\]{}()*+?.,\\^$|#\s]/g + */ + escape?: RegExp; + }; + metadata?: { + /** + * @default 'defaultText' + */ + defaultText?: string; + /** + * @default 'defaultValue' + */ + defaultValue?: string; + /** + * @default 'placeholderText' + */ + placeholderText?: string; + /** + * @default 'text' + */ + text?: string; + /** + * @default 'value' + */ + value?: string; + }; + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'addition' + */ + addition?: string; + /** + * @default 'animating' + */ + animating?: string; + /** + * @default 'disabled' + */ + disabled?: string; + /** + * @default 'ui dropdown' + */ + dropdown?: string; + /** + * @default 'filtered' + */ + filtered?: string; + /** + * @default 'hidden transition' + */ + hidden?: string; + /** + * @default 'item' + */ + item?: string; + /** + * @default 'ui label' + */ + label?: string; + /** + * @default 'loading' + */ + loading?: string; + /** + * @default 'menu' + */ + menu?: string; + /** + * @default 'message' + */ + message?: string; + /** + * @default 'multiple' + */ + multiple?: string; + /** + * @default 'default' + */ + placeholder?: string; + /** + * @default 'search' + */ + search?: string; + /** + * @default 'selected' + */ + selected?: string; + /** + * @default 'selection' + */ + selection?: string; + /** + * @default 'upward' + */ + upward?: string; + /** + * @default 'visible' + */ + visible?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'You called a dropdown action that was not defined' + */ + action?: string; + /** + * @default 'Once a select has been initialized behaviors must be called on the created ui dropdown' + */ + alreadySetup?: string; + /** + * @default 'Allowing user additions currently requires the use of labels.' + */ + labels?: string; + /** + * @default 'The method you called is not defined.' + */ + method?: string; + /** + * @default 'This module requires ui transitions ' + */ + noTransition?: string; + }; + + // endregion + } + + // endregion + + // region Embed + + /** + * @see {@link http://semantic-ui.com/modules/embed.html#/settings} + */ + interface EmbedSettings extends ComponentSettings { + /** + * Specifies a url to use for embed + * + * @default false + */ + url?: false | string; + + // region Embed Settings + + /** + * Specifies an icon to use with placeholder content + * + * @default false + */ + icon?: false | string; + /** + * Specifies a source to use, if no source is provided it will be determined from the domain of a specified url. + * + * @default false + */ + source?: false | string; + /** + * Specifies an id value to replace with the {id} value found in templated urls + * + * @default false + */ + id?: false | string; + /** + * Specify an object containing key/value pairs to add to the iframes GET parameters + * + * @default false + */ + parameters?: false | any; + + // endregion + + // region Video Settings + + /** + * Default setting auto will only autoplay content when a placeholder is specified. Setting to true or false will force autoplay. + * + * @default 'auto' + */ + autoplay?: 'auto' | boolean; + /** + * Specifies a default chrome color with Vimeo or YouTube. + * + * @default '#444444' + */ + color?: string; + /** + * Whether to prefer HD content + * + * @default true + */ + hd?: boolean; + /** + * Whether to show networks branded UI like title cards, or after video calls to action. + * + * @default false + */ + brandedUI?: boolean; + + // endregion + + // region Callbacks + + /** + * Callback when iframe is generated + */ + onCreate?: (this: JQuery, url: string) => void; + /** + * Whenever an iframe contents is shown + */ + onDisplay?: (this: JQuery) => void; + /** + * Callback immediately before Embed is removed from DOM + */ + onPlaceholderDisplay?: (this: JQuery) => void; + /** + * Callback when module parameters are determined. Allows you to adjust parameters at run time by returning a new parameters object. + */ + onEmbed?: (this: JQuery, parameters: any) => any; + + // endregion + + // region DOM Settings + + /** + * DOM Selectors used internally + */ + selector?: { + /** + * @default '.embed' + */ + embed?: string; + /** + * @default '.placeholder' + */ + placeholder?: string; + /** + * @default '.play' + */ + play?: string; + }; + /** + * HTML Data attributes used to store data + */ + metadata?: { + /** + * @default 'id' + */ + id?: string; + /** + * @default 'icon' + */ + icon?: string; + /** + * @default 'placeholder' + */ + placeholder?: string; + /** + * @default 'source' + */ + source?: string; + /** + * @default 'url' + */ + url?: string; + }; + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'embed' + */ + embed?: string; + }; + templates?: { + /** + * returns html for iframe + */ + iframe?: (url: string, parameters: string) => string; + /** + * returns html for placeholder element + */ + placeholder?: (image: string, icon: string) => string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'No URL specified' + */ + noURL?: string; + /** + * @default 'The method you called is not defined' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Modal + + /** + * @see {@link http://semantic-ui.com/modules/modal.html#/settings} + */ + interface ModalSettings extends ComponentSettings { + // region Modal Settings + + /** + * If set to false will prevent the modal from being moved to inside the dimmer + * + * @default true + */ + detachable?: boolean; + /** + * When true, the first form input inside the modal will receive focus when shown. Set this to false to prevent this behavior. + * + * @default true + */ + autofocus?: boolean; + /** + * Whether any change in modal DOM should automatically refresh cached positions + * + * @default false + */ + observeChanges?: boolean; + /** + * If set to true will not close other visible modals when opening a new one + * + * @default false + */ + allowMultiple?: boolean; + /** + * Whether to automatically bind keyboard shortcuts + * + * @default true + */ + keyboardShortcuts?: boolean; + /** + * A vertical offset to allow for content outside of modal, for example a close button, to be centered. + * + * @default 0 + */ + offset?: number; + /** + * Selector or jquery object specifying the area to dim + * + * @default 'body' + */ + context?: Selector; + /** + * Setting to false will not allow you to close the modal by clicking on the dimmer + * + * @default true + */ + closable?: boolean; + /** + * You can specify custom settings to extend UI dimmer + * + * @see {@link http://semantic-ui.com/modules/dimmer.html} + */ + dimmerSettings?: DimmerSettings; + /** + * Named transition to use when animating menu in and out, full list can be found in ui transitions docs. + * + * @default 'scale' + * @see {@link http://semantic-ui.com/modules/transition.html} + */ + transition?: string; + /** + * Duration of animation + * + * @default 400 + */ + duration?: number; + /** + * Whether additional animations should queue + * + * @default false + */ + queue?: boolean; + + // endregion + + // region Callbacks + + /** + * Is called when a modal starts to show. + */ + onShow?: (this: JQuery) => void; + /** + * Is called after a modal has finished showing animating. + */ + onVisible?: (this: JQuery) => void; + /** + * Is called after a modal starts to hide. If the function returns false, the modal will not hide. + */ + onHide?: (this: JQuery, $element: JQuery) => false | void; + /** + * Is called after a modal has finished hiding animation. + */ + onHidden?: (this: JQuery) => void; + /** + * Is called after a positive, approve or ok button is pressed. If the function returns false, the modal will not hide. + */ + onApprove?: (this: JQuery, $element: JQuery) => false | void; + /** + * Is called after a negative, deny or cancel button is pressed. If the function returns false the modal will not hide. + */ + onDeny?: (this: JQuery, $element: JQuery) => false | void; + + // endregion + + // region DOM Settings + + selector?: { + /** + * @default '.close, .actions .button' + */ + close?: string; + /** + * @default '.actions .positive, .actions .approve, .actions .ok' + */ + approve?: string; + /** + * @default '.actions .negative, .actions .deny, .actions .cancel' + */ + deny?: string; + }; + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'scrolling' + */ + scrolling?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Nag + + /** + * @see {@link http://semantic-ui.com/modules/nag.html} + */ + interface NagSettings extends ComponentSettings { + // region Behavior + + /** + * allows cookie to be overridden + * + * @default false + */ + persist?: boolean; + /** + * set to zero to require manually dismissal, otherwise hides on its own + * + * @default 0 + */ + displayTime?: number; + animation?: { + /** + * @default 'slide' + */ + show?: string; + /** + * @default 'slide' + */ + hide?: string; + }; + /** + * @default false + */ + context?: false | Selector; + /** + * @default false + */ + detachable?: boolean; + + /** + * @default 30 + */ + expires?: number; + /** + * @default false + */ + domain?: false | string; + /** + * @default '/' + */ + path?: string; + + /** + * type of storage to use + * + * @default 'cookie' + */ + storageMethod?: 'cookie' | 'localstorage' | 'sessionstorage'; + + /** + * @default 'nag' + */ + key?: any; + /** + * @default 'dismiss' + */ + value?: any; + + /** + * @default 500 + */ + speed?: number; + /** + * @default 'easeOutQuad' + */ + easing?: string; + + // endregion + + // region Callbacks + + onHide?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + className?: { + /** + * @default 'bottom' + */ + bottom?: string; + /** + * @default 'fixed' + */ + fixed?: string; + }; + selector?: { + /** + * @default '.close.icon' + */ + close?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default '$.cookie is not included. A storage solution is required.' + */ + noCookieStorage?: string; + /** + * @default 'Neither $.cookie or store is defined. A storage solution is required for storing state' + */ + noStorage?: string; + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Popup + + /** + * @see {@link http://semantic-ui.com/modules/popup.html#/settings} + */ + interface PopupSettings extends ComponentSettings { + // region Popup Settings + + /** + * Can specify a DOM element that should be used as the popup. This is useful for including a pre-formatted popup. + * + * @default false + */ + popup?: false | Selector; + /** + * Whether all other popups should be hidden when this popup is opened + * + * @default false + */ + exclusive?: boolean; + /** + * Whether to move popup to same offset container as target element when popup already exists on the page. + * Using a popup inside of an element without overflow:visible, like a sidebar, may require you to set this to false + * + * @default true + */ + movePopup?: boolean; + /** + * Whether popup should attach mutationObservers to automatically run destroy when the element is removed from the page's DOM. + * + * @default true + */ + observeChanges?: boolean; + /** + * When the popup surpasses the boundary of this element, it will attempt to find another display position. + */ + boundary?: Selector; + /** + * Selector or jquery object specifying where the popup should be created. + * + * @default 'body' + */ + context?: Selector; + /** + * Will automatically hide a popup on scroll event in this context + */ + scrollContext?: Selector; + /** + * Number of pixels that a popup is allowed to appear outside the boundaries of its context. + * This allows for permissible rounding errors when an element is against the edge of its context. + * + * @default 2 + */ + jitter?: number; + /** + * Position that the popup should appear + * + * @default 'top left' + */ + position?: string; + /** + * If a popup is inline it will be created next to current element, allowing for local css rules to apply. + * It will not be removed from the DOM after being hidden. + * Otherwise popups will appended to body and removed after being hidden. + * + * @default false + */ + inline?: boolean; + /** + * Whether popup contents should be preserved in the page after being hidden, allowing it to re-appear slightly faster on subsequent loads. + * + * @default false + */ + preserve?: boolean; + /** + * Can be set to adjacent or opposite to prefer adjacent or opposite position if popup cannot fit on screen + * + * @default 'adjacent' + */ + prefer?: 'adjacent' | 'opposite'; + /** + * When set to false, a popup will not appear and produce an error message if it cannot entirely fit on page. + * Setting this to a position like, right center forces the popup to use this position as a last resort even if it is partially offstage. + * Setting this to true will use the last attempted position. + * + * @default false + */ + lastResort?: boolean | string; + /** + * Event used to trigger popup. Can be either focus, click, hover, or manual. Manual popups must be triggered with $('.element').popup('show'); + * + * @default 'hover' + */ + on?: 'focus' | 'click' | 'hover' | 'manual'; + /** + * Delay in milliseconds before showing or hiding a popup on hover or focus + */ + delay?: { + show?: number; + hide?: number; + }; + /** + * Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions + * + * @default 'slide down' + * @see {@link http://semantic-ui.com/modules/transition.html} + */ + transition?: string; + /** + * Duration of animation events + * + * @default 200 + */ + duration?: number; + /** + * Whether popup should set fluid popup variation width on load to avoid width: 100% including padding + * + * @default true + */ + setFluidWidth?: boolean; + /** + * Whether popup should not close on hover (useful for popup navigation menus) + * + * @default false + */ + hoverable?: boolean; + /** + * When using on: 'click' specifies whether clicking the page should close the popup + * + * @default true + */ + closable?: boolean; + /** + * When using on: 'hover' whether touchstart events should be added to allow the popup to be triggered + */ + addTouchEvents?: boolean; + /** + * Whether popup should hide on scroll or touchmove, auto only hides for popups without on: 'click'. + * Set this to false to prevent mobile browsers from closing popups when you tap inside input fields. + * + * @default 'auto' + */ + hideOnScroll?: 'auto' | false; + /** + * If a selector or jQuery object is specified this allows the popup to be positioned relative to that element. + * + * @default false + */ + target?: false | Selector; + /** + * Offset for distance of popup from element + * + * @default 0 + */ + distanceAway?: number; + /** + * Offset in pixels from calculated position + * + * @default 0 + */ + offset?: number; + /** + * Number of iterations before giving up search for popup position when a popup cannot fit on screen + * + * @default 10 + */ + maxSearchDepth?: number; + + // endregion + + // region Callbacks + + /** + * Callback on popup element creation, with created popup + */ + onCreate?: (this: JQuery, $module: JQuery) => void; + /** + * Callback immediately before Popup is removed from DOM + */ + onRemove?: (this: JQuery, $module: JQuery) => void; + /** + * Callback before popup is shown. Returning false from this callback will cancel the popup from showing. + */ + onShow?: (this: JQuery, $module: JQuery) => false | void; + /** + * Callback after popup is shown + */ + onVisible?: (this: JQuery, $module: JQuery) => void; + /** + * Callback before popup is hidden. Returning false from this callback will cancel the popup from hiding. + */ + onHide?: (this: JQuery, $module: JQuery) => false | void; + /** + * Callback after popup is hidden + */ + onHidden?: (this: JQuery, $module: JQuery) => void; + /** + * Callback after popup cannot be placed on screen + */ + onUnplaceable?: (this: JQuery, $module: JQuery) => void; + + // endregion + + // region Content Settings + + /** + * Popup variation to use, can use multiple variations with a space delimiter + */ + variation?: string; + /** + * Content to display + */ + content?: string; + /** + * Title to display alongside content + */ + title?: string; + /** + * HTML content to display instead of preformatted title and content + */ + html?: string; + + // endregion + + // region DOM Settings + + /** + * DOM Selectors used internally + */ + selector?: { + /** + * @default '.ui.popup' + */ + popup?: string; + }; + /** + * HTML Data attributes used to store data + */ + metadata?: { + /** + * @default 'content' + */ + content?: string; + /** + * @default 'html' + */ + html?: string; + /** + * @default 'offset' + */ + offset?: string; + /** + * @default 'position' + */ + position?: string; + /** + * @default 'title' + */ + title?: string; + /** + * @default 'variation' + */ + variation?: string; + }; + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'loading' + */ + loading?: string; + /** + * @default 'ui popup' + */ + popup?: string; + /** + * @default 'top left center bottom right' + */ + position?: string; + /** + * @default 'visible' + */ + visible?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The position you specified is not a valid position' + */ + invalidPosition?: string; + /** + * @default 'Popup does not fit within the boundaries of the viewport' + */ + cannotPlace?: string; + /** + * @default 'The method you called is not defined.' + */ + method?: string; + /** + * @default 'This module requires ui transitions ' + */ + noTransition?: string; + /** + * @default 'The target or popup you specified does not exist on the page' + */ + notFound?: string; + }; + + // endregion + } + + // endregion + + // region Progress + + /** + * @see {@link http://semantic-ui.com/modules/progress.html#/settings} + */ + interface ProgressSettings extends ComponentSettings { + // region Progress Settings + + /** + * Whether success state should automatically trigger when progress completes + * + * @default true + */ + autoSuccess?: boolean; + /** + * Whether progress should automatically show activity when incremented + * + * @default true + */ + showActivity?: boolean; + /** + * When set to true, values that calculate to above 100% or below 0% will be adjusted. + * When set to false, inappropriate values will produce an error. + * + * @default true + */ + limitValues?: boolean; + /** + * Can be set to either to display progress as percent or ratio. Matches up to corresponding text template with the same name. + * + * @default 'percent' + */ + label?: 'percent' | 'ratio'; + /** + * When incrementing without value, sets range for random increment value + */ + random?: { + /** + * @default 2 + */ + min?: number; + /** + * @default 5 + */ + max?: number; + }; + /** + * Decimal point precision for calculated progress + * + * @default 1 + */ + precision?: number; + /** + * Setting a total value will make each call to increment get closer to this total (i.e. 1/20, 2/20 etc) + * + * @default false + */ + total?: false | number; + /** + * Sets current value, when total is specified, this is used to calculate a ratio of the total, with percent this should be the overall percent + * + * @default false + */ + value?: false | number; + + // endregion + + // region Callbacks + + /** + * Callback on percentage change + */ + onChange?: (this: JQuery, percent: number, value: number, total: number) => void; + /** + * Callback on success state + */ + onSuccess?: (this: JQuery, total: number) => void; + /** + * Callback on active state + */ + onActive?: (this: JQuery, value: number, total: number) => void; + /** + * Callback on error state + */ + onError?: (this: JQuery, value: number, total: number) => void; + /** + * Callback on warning state + */ + onWarning?: (this: JQuery, value: number, total: number) => void; + + // endregion + + // region DOM Settings + + /** + * Text content for each state, uses simple templating with {percent}, {value}, {total} + */ + text?: { + /** + * @default false + */ + active?: false | string; + /** + * @default false + */ + error?: false | string; + /** + * @default false + */ + success?: false | string; + /** + * @default false + */ + warning?: false | string; + /** + * @default '{percent}%' + */ + percent?: false | string; + /** + * @default '{value} of {total}' + */ + ratio?: false | string; + }; + /** + * Regular expressions used by module + */ + regExp?: { + /** + * @default /\{\$*[A-z0-9]+\}/g + */ + variable?: RegExp; + }; + /** + * Selectors used by module + */ + selector?: { + /** + * @default '> .bar + */ + bar?: string; + /** + * @default '> .label' + */ + label?: string; + /** + * @default '.bar > .progress' + */ + progress?: string; + }; + /** + * DOM metadata used by module + */ + metadata?: { + /** + * @default 'percent' + */ + percent?: string; + /** + * @default 'total' + */ + total?: string; + /** + * @default 'value' + */ + value?: string; + }; + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'error' + */ + error?: string; + /** + * @default 'success' + */ + success?: string; + /** + * @default 'warning' + */ + warning?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + /** + * @default 'Progress value is non numeric' + */ + nonNumeric?: string; + }; + + // endregion + } + + // endregion + + // region Rating + + /** + * @see {@link http://semantic-ui.com/modules/rating.html#/settings} + */ + interface RatingSettings extends ComponentSettings { + // region Rating Settings + + /** + * A number representing the default rating to apply + * + * @default 0 + */ + initialRating?: number; + /** + * Whether callbacks like onRate should fire immediately after initializing with the current value. + * + * @default false + */ + fireOnInit?: boolean; + /** + * By default a rating will be only clearable if there is 1 icon. Setting to true/false will allow or disallow a user to clear their rating + * + * @default 'auto' + */ + clearable?: 'auto' | boolean; + /** + * Whether to enable user's ability to rate + * + * @default true + */ + interactive?: boolean; + + // endregion + + // region Callbacks + + /** + * Is called after user selects a new rating + */ + onRate?: (this: JQuery, value: number) => void; + + // endregion + + // region DOM Settings + + selector?: { + /** + * @default '.icon' + */ + icon?: string; + }; + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'hover' + */ + hover?: string; + /** + * @default 'loading' + */ + loading?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'You called a rating action that was not defined' + */ + action?: string; + }; + + // endregion + } + + // endregion + + // region Search + + /** + * @see {@link http://semantic-ui.com/modules/search.html#/settings} + */ + interface SearchSettings extends ComponentSettings { + // region Behavior + + /** + * Settings for API call. + * + * @see {@link http://semantic-ui.com/behaviors/api.html#/usage} + */ + apiSettings?: ApiSettings; + /** + * Minimum characters to query for results + * + * @default 1 + */ + minCharacters?: number; + /** + * Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions + * + * @default 'fade' + * @see {@link http://semantic-ui.com/modules/transition.html} + */ + transition?: string; + /** + * Duration of animation events + * + * @default 300 + */ + duration?: number; + /** + * Maximum results to display when using local and simple search, maximum category count for category search + * + * @default 7 + */ + maxResults?: number; + /** + * Caches results locally to avoid requerying server + * + * @default true + */ + cache?: boolean; + /** + * Specify a Javascript object which will be searched locally + * + * @default false + */ + source?: false | any; + /** + * Whether the search should automatically select the first search result after searching + * + * @default false + */ + selectFirstResult?: boolean; + /** + * Whether a "no results" message should be shown if no results are found. (These messages can be modified using the template object specified below) + * + * @default false + */ + showNoResults?: boolean; + /** + * Return local results that match anywhere inside your content + * + * @default true + */ + searchFullText?: boolean; + /** + * List mapping display content to JSON property, either with API or source. + */ + fields?: { + /** + * array of categories (category view) + * + * @default 'results' + */ + categories?: string; + /** + * name of category (category view) + * + * @default 'name' + */ + categoryName?: string; + /** + * array of results (category view) + * + * @default 'results' + */ + categoryResults?: string; + /** + * result description + * + * @default 'description' + */ + description?: string; + /** + * result image + * + * @default 'image' + */ + image?: string; + /** + * result price + * + * @default 'price' + */ + price?: string; + /** + * array of results (standard) + * + * @default 'results' + */ + results?: string; + /** + * result title + * + * @default 'title' + */ + title?: string; + /** + * "view more" object name + * + * @default 'action' + */ + action?: string; + /** + * "view more" text + * + * @default 'text' + */ + actionText?: string; + /** + * "view more" url + * + * @default 'url' + */ + actionURL?: string; + }; + /** + * Specify object properties inside local source object which will be searched + */ + searchFields?: string[]; + /** + * Delay before hiding results after search blur + * + * @default 0 + */ + hideDelay?: number; + /** + * Delay before querying results on inputchange + * + * @default 100 + */ + searchDelay?: number; + /** + * Easing equation when using fallback Javascript animation + * + * @default 'easeOutExpo' + */ + easing?: string; + + // endregion + + // region Callbacks + + /** + * Callback on element selection by user. + * The first parameter includes the filtered response results for that element. + * The function should return false to prevent default action (closing search results and selecting value). + */ + onSelect?: (this: JQuery, result: any, response: any) => false | void; + /** + * Callback after processing element template to add HTML to results. Function should return false to prevent default actions. + */ + onResultsAdd?: (this: JQuery, html: string) => false | void; + /** + * Callback on search query + */ + onSearchQuery?: (this: JQuery, query: string) => void; + /** + * Callback on server response + */ + onResults?: (this: JQuery, response: any) => void; + /** + * Callback when results are opened + */ + onResultsOpen?: (this: JQuery) => void; + /** + * Callback when results are closed + */ + onResultsClose?: (this: JQuery) => void; + + // endregion + + // region Templates + + templates?: { + escape?: (string: string) => string; + message?: (message: string, type: string) => string; + category?: (response: any) => string; + standard?: (response: any) => string; + }; + + // endregion + + // region DOM Settings + + /** + * Regular expressions used for matching + */ + regExp?: { + /** + * @default /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g + */ + escape?: RegExp; + /** + * @default '(?:\s|^)' + */ + beginsWith?: string; + }; + /** + * Selectors used to find parts of a module + */ + selector?: { + /** + * @default '.prompt' + */ + prompt?: string; + /** + * @default '.search.button' + */ + searchButton?: string; + /** + * @default '.results' + */ + results?: string; + /** + * @default '.category' + */ + category?: string; + /** + * @default '.result' + */ + result?: string; + }; + /** + * HTML5 metadata attributes used internally + */ + metadata?: { + /** + * @default 'cache' + */ + cache?: string; + /** + * @default 'results' + */ + results?: string; + }; + /** + * Class names used to determine element state + */ + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'empty' + */ + empty?: string; + /** + * @default 'focus' + */ + focus?: string; + /** + * @default 'loading' + */ + loading?: string; + /** + * @default 'down' + */ + pressed?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'Cannot search. No source used, and Semantic API module was not included' + */ + source?: string; + /** + * @default 'Your search returned no results' + */ + noResults?: string; + /** + * @default 'Error in debug logging, exiting.' + */ + logging?: string; + /** + * @default 'A valid template name was not specified.' + */ + noTemplate?: string; + /** + * @default 'There was an issue with querying the server.' + */ + serverError?: string; + /** + * @default 'Results must be an array to use maxResults setting' + */ + maxResults?: string; + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Shape + + /** + * @see {@link http://semantic-ui.com/modules/shape.html#/settings} + */ + interface ShapeSettings extends ComponentSettings { + // region Shape Settings + + /** + * Duration of side change animation + * + * @default 700 + */ + duration?: number; + /** + * When set to next will use the width of the next side during the shape's animation. + * When set to initial it will use the width of the shape at initialization. + * When set to a specific pixel height, will force the width to that height. + * + * @default 'initial' + * @since 2.2 + */ + width?: 'next' | 'initial' | number; + /** + * When set to next will use the height of the next side during the shape's animation. + * When set to initial it will use the height of the shape at initialization. + * When set to a specific pixel height, will force the height to that height. + * + * @default 'initial' + * @since 2.2 + */ + height?: 'next' | 'initial' | number; + + // endregion + + // region Callbacks + + /** + * Is called before side change + */ + beforeChange?: (this: JQuery) => void; + /** + * Is called after visible side change + */ + onChange?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + selector?: { + /** + * @default '.sides' + */ + sides?: string; + /** + * @default '.side' + */ + side?: string; + }; + className?: { + /** + * @default 'animating' + */ + animating?: string; + /** + * @default 'hidden' + */ + hidden?: string; + /** + * @default 'loading' + */ + loading?: string; + /** + * @default 'active' + */ + active?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'You tried to switch to a side that does not exist.' + */ + side?: string; + /** + * @default 'The method you called is not defined' + */ + method?: string; + }; + + // endregion + } + + interface Translation { + transform: string; + } + + // endregion + + // region Sidebar + + /** + * @see {@link http://semantic-ui.com/modules/sidebar.html#/settings} + */ + interface SidebarSettings extends ComponentSettings { + // region Behavior + + /** + * Context which sidebar will appear inside + * + * @default 'body' + */ + context?: Selector; + /** + * Whether multiple sidebars can be open at once + * + * @default false + */ + exclusive?: boolean; + /** + * Whether sidebar can be closed by clicking on page + * + * @default true + */ + closable?: boolean; + /** + * Whether to dim page contents when sidebar is visible + * + * @default true + */ + dimPage?: boolean; + /** + * Whether to lock page scroll when sidebar is visible + * + * @default false + */ + scrollLock?: boolean; + /** + * Whether to return to original scroll position when sidebar is hidden, automatically occurs with transition: scale + * + * @default false + */ + returnScroll?: boolean; + /** + * When sidebar is initialized without the proper HTML, using this option will defer creation of DOM to use requestAnimationFrame. + * + * @default false + */ + delaySetup?: boolean; + + // endregion + + // region Animation + + /** + * Named transition to use when animating sidebar. Defaults to 'auto' which selects transition from defaultTransition based on direction. + * + * @default 'auto' + */ + transition?: string; + /** + * Named transition to use when animating when detecting mobile device. Defaults to 'auto' which selects transition from defaultTransition based on direction. + * + * @default 'auto' + */ + mobileTransition?: string; + /** + * Default transitions for each direction and screen size, used with transition: auto + */ + defaultTransition?: { + computer?: { + /** + * @default 'uncover' + */ + left?: string; + /** + * @default 'uncover' + */ + right?: string; + /** + * @default 'overlay' + */ + top?: string; + /** + * @default 'overlay' + */ + bottom?: string; + }; + mobile?: { + /** + * @default 'uncover' + */ + left?: string; + /** + * @default 'uncover' + */ + right?: string; + /** + * @default 'overlay' + */ + top?: string; + /** + * @default 'overlay' + */ + bottom?: string; + }; + }; + /** + * Whether Javascript animations should be used. Defaults to false. Setting to auto will use legacy animations only for browsers that do not support CSS transforms + * + * @default false + */ + useLegacy?: 'auto' | boolean; + /** + * Duration of sidebar animation when using legacy Javascript animation + * + * @default 500 + */ + duration?: number; + /** + * Easing to use when using legacy Javascript animation + * + * @default 'easeInOutQuint' + */ + easing?: string; + + // endregion + + // region Callbacks + + /** + * Is called when a sidebar begins animating in. + */ + onVisible?: (this: JQuery) => void; + /** + * Is called when a sidebar has finished animating in. + */ + onShow?: (this: JQuery) => void; + /** + * Is called when a sidebar begins to hide or show + */ + onChange?: (this: JQuery) => void; + /** + * Is called before a sidebar begins to animate out. + */ + onHide?: (this: JQuery) => void; + /** + * Is called after a sidebar has finished animating out. + */ + onHidden?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'animating' + */ + animating?: string; + /** + * @default 'dimmed' + */ + dimmed?: string; + /** + * @default 'ios' + */ + ios?: string; + /** + * @default 'pushable' + */ + pushable?: string; + /** + * @default 'pushed' + */ + pushed?: string; + /** + * @default 'right' + */ + right?: string; + /** + * @default 'top' + */ + top?: string; + /** + * @default 'left' + */ + left?: string; + /** + * @default 'bottom' + */ + bottom?: string; + /** + * @default 'visible' + */ + visible?: string; + }; + regExp?: { + /** + * @default /(iPad|iPhone|iPod)/g + */ + ios?: RegExp; + /** + * @default /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g + */ + mobile?: RegExp; + }; + selector?: { + /** + * @default '.fixed' + */ + fixed?: string; + /** + * @default 'script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed' + */ + omitted?: string; + /** + * @default '.pusher' + */ + pusher?: string; + /** + * @default '.ui.sidebar' + */ + sidebar?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + /** + * @default 'Had to add pusher element. For optimal performance make sure body content is inside a pusher element' + */ + pusher?: string; + /** + * @default 'Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag' + */ + movedSidebar?: string; + /** + * @default 'The overlay setting is no longer supported, use animation: overlay' + */ + overlay?: string; + /** + * @default 'There were no elements that matched the specified selector' + */ + notFound?: string; + }; + + // endregion + } + + // endregion + + // region Sticky + + /** + * @see {@link http://semantic-ui.com/modules/sticky.html#/settings} + */ + interface StickySettings extends ComponentSettings { + // region Sticky Settings + + /** + * Whether element should be "pushed" by the viewport, attaching to the bottom of the screen when scrolling up + * + * @default false + */ + pushing?: boolean; + /** + * Sticky container height will only be set if the difference between heights of container and context is larger than this jitter value. + * + * @default 5 + */ + jitter?: number; + /** + * Whether any change in context DOM should automatically refresh cached sticky positions + * + * @default false + */ + observeChanges?: boolean; + /** + * Context which sticky element should stick to + * + * @default false + */ + context?: false | Selector; + /** + * Context which sticky should attach onscroll events. + * + * @default 'window' + */ + scrollContext?: Selector; + /** + * Offset in pixels from the top of the screen when fixing element to viewport + * + * @default 0 + */ + offset?: number; + /** + * Offset in pixels from the bottom of the screen when fixing element to viewport + * + * @default 0 + */ + bottomOffset?: number; + + // endregion + + // region Callbacks + + /** + * Callback when element is repositioned from layout change + */ + onReposition?: (this: JQuery) => void; + /** + * Callback when requestAnimationFrame fires from scroll handler. + */ + onScroll?: (this: JQuery) => void; + /** + * Callback when element is fixed to page + */ + onStick?: (this: JQuery) => void; + /** + * Callback when element is unfixed from page + */ + onUnstick?: (this: JQuery) => void; + /** + * Callback when element is bound to top of parent container + */ + onTop?: (this: JQuery) => void; + /** + * Callback when element is bound to bottom of parent container + */ + onBottom?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'bound' + */ + bound?: string; + /** + * @default 'fixed' + */ + fixed?: string; + /** + * @default 'native' + */ + supported?: string; + /** + * @default 'top' + */ + top?: string; + /** + * @default 'bottom' + */ + bottom?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'Sticky element must be inside a relative container' + */ + container?: string; + /** + * @default 'Element is hidden, you must call refresh after element becomes visible' + */ + visible?: string; + /** + * @default 'The method you called is not defined.' + */ + method?: string; + /** + * @default 'Context specified does not exist' + */ + invalidContext?: string; + /** + * @default 'Sticky element is larger than its container, cannot create sticky.' + */ + elementSize?: string; + }; + + // endregion + } + + // endregion + + // region Tab + + /** + * @see {@link http://semantic-ui.com/modules/tab.html#/settings} + */ + interface TabSettings extends ComponentSettings { + // region Tab Settings + + /** + * Whether tab should load remote content as same url as history + * + * @default false + */ + auto?: boolean; + /** + * When set to siblings will only deactivate elements that are DOM siblings with the activated element. + * When set to all the component will deactivate all other elements initialized at the same time. + * + * @default 'siblings' + * @since 2.2 + */ + deactivate?: 'siblings' | 'all'; + /** + * Whether to record history events for tab changes + * + * @default false + */ + history?: boolean; + /** + * Do not load content remotely on first tab load. Useful when open tab is rendered on server. + * + * @default false + */ + ignoreFirstLoad?: boolean; + /** + * Whether inline scripts in tab HTML should be parsed on tab load. + * Defaults to once, parsing only on first load. + * Can also be set to true or false to always parse or never parse inline scripts. + * + * @default 'once' + */ + evaluateScripts?: 'once' | boolean; + /** + * Tab should reload content every time it is opened + */ + alwaysRefresh?: boolean; + /** + * Can be set to either response, DOM or html. + * Using DOM will cache the a clone of the DOM tree, preserving all events as they existed on render. + * response will cache the original response on load, this way callbacks always receive the same content. + * Using html will cache the resulting html after all callbacks, making sure any changes to content are preserved. + * + * @default 'response' + */ + cacheType?: 'response' | 'DOM' | 'html'; + /** + * Tab should cache content after loading locally to avoid server trip on second load + * + * @default true + */ + cache?: boolean; + /** + * Settings object for $.api call + * + * @default false + * @see {@link http://semantic-ui.com/behaviors/api.html} + */ + apiSettings?: ApiSettings; + /** + * Can be set to hash or state. + * Hash will use an in-page link to create history events. + * State will use DOM History and load pages from server on refresh. + * + * @default 'hash' + * @see {@link https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history} + */ + historyType?: 'hash' | 'state'; + /** + * When using historyType state you must specify the base URL for all internal links. + * + * @default false + */ + path?: false | string; + /** + * Tabs are limited to those found inside this context + * + * @default false + */ + context?: false | Selector; + /** + * If enabled limits tabs to children of passed context + * + * @default false + */ + childrenOnly?: boolean; + /** + * Maximum amount of nested tabs allowed (avoids recursion) + * + * @default 25 + */ + maxDepth?: number; + + // endregion + + // region Callbacks + + /** + * Callback only the first time a tab is loaded + */ + onFirstLoad?: (this: JQuery, tabPath: string, parameterArray: any[], historyEvent: any) => void; + /** + * Callback every time a tab is loaded + */ + onLoad?: (this: JQuery, tabPath: string, parameterArray: any[], historyEvent: any) => void; + /** + * Called when a tab begins loading remote content + */ + onRequest?: (this: JQuery, tabPath: string) => void; + /** + * Called after a tab becomes visible + */ + onVisible?: (this: JQuery, tabPath: string) => void; + + // endregion + + // region DOM Settings + + /** + * Functions used to return content + */ + templates?: { + /** + * returns page title + */ + determineTitle?: (tabArray: any[]) => string; + }; + /** + * Selectors used by module + */ + selector?: { + /** + * @default '.ui.tab' + */ + tabs?: string; + /** + * @default '.ui:not(.menu)' + */ + parent?: string; + }; + /** + * DOM metadata used by module + */ + metadata?: { + /** + * @default 'tab' + */ + tab?: string; + /** + * @default 'loaded' + */ + loaded?: string; + /** + * @default 'promise' + */ + promise?: string; + }; + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'loading' + */ + loading?: string; + /** + * @default 'active' + */ + active?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'You attempted to load content without API module' + */ + api?: string; + /** + * @default 'The method you called is not defined' + */ + method?: string; + /** + * @default 'Activated tab cannot be found for this context.' + */ + missingTab?: string; + /** + * @default 'The tab you specified is missing a content url.' + */ + noContent?: string; + /** + * @default 'History enabled, but no path was specified' + */ + path?: string; + /** + * @default 'Max recursive depth reached' + */ + recursion?: string; + /** + * @default 'The state library has not been initialized' + */ + state?: string; + }; + + // endregion + } + + // endregion + + // region Transition + + /** + * @see {@link http://semantic-ui.com/modules/transition.html#/settings} + */ + interface TransitionSettings extends ComponentSettings { + // region Transition Settings + + /** + * Named animation event to used. Must be defined in CSS. + * + * @default 'fade' + */ + animation?: string; + /** + * Interval in MS between each elements transition + * + * @default 0 + */ + interval?: number; + /** + * When an interval is specified, sets order of animations. auto reverses only animations that are hiding. + * + * @default 'auto' + */ + reverse?: 'auto' | boolean; + /** + * Specify the final display type (block, inline-block etc) so that it doesn't have to be calculated. + * + * @default false + */ + displayType?: false | string; + /** + * Duration of the CSS transition animation + * + * @default 500 + */ + duration?: number; + /** + * If enabled a timeout will be added to ensure animationend callback occurs even if element is hidden + */ + useFailSafe?: boolean; + /** + * If enabled will allow same animation to be queued while it is already occurring + */ + allowRepeats?: boolean; + /** + * Whether to automatically queue animation if another is occurring + */ + queue?: boolean; + + // endregion + + // region Callbacks + + /** + * Callback on each transition that changes visibility to shown + */ + onShow?: (this: JQuery) => void; + /** + * Callback on each transition that changes visibility to hidden + */ + onHide?: (this: JQuery) => void; + /** + * Callback on animation start, useful for queued animations + */ + onStart?: (this: JQuery) => void; + /** + * Callback on each transition complete + */ + onComplete?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'animating' + */ + animating?: string; + /** + * @default 'disabled' + */ + disabled?: string; + /** + * @default 'hidden' + */ + hidden?: string; + /** + * @default 'in' + */ + inward?: string; + /** + * @default 'loading' + */ + loading?: string; + /** + * @default 'looping' + */ + looping?: string; + /** + * @default 'out' + */ + outward?: string; + /** + * @default 'transition' + */ + transition?: string; + /** + * @default 'visible' + */ + visible?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'There is no CSS animation matching the one you specified.' + */ + noAnimation?: string; + /** + * @default 'The method you called is not defined' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // endregion + + // region Behaviors + + // region API + + /** + * @see {@link http://semantic-ui.com/behaviors/api.html#/settings} + */ + interface ApiSettings extends ComponentSettings { + // region Behavior + + /** + * When API event should occur + * + * @default 'auto' + */ + on?: string; + /** + * Can be set to 'local' to cache successful returned AJAX responses when using a JSON API. + * This helps avoid server round trips when API endpoints will return the same results when accessed repeatedly. + * Setting to false, will add cache busting parameters to the URL. + * + * @default true + */ + cache?: 'local' | boolean; + /** + * UI state will be applied to this element, defaults to triggering element. + */ + stateContext?: Selector; + /** + * Whether to encode parameters with encodeURIComponent before adding into url string + * + * @default true + */ + encodeParameters?: boolean; + /** + * Whether to automatically include default data like {value} and {text} + * + * @default true + */ + defaultData?: boolean; + /** + * Whether to serialize closest form and include in request + * + * @default false + */ + serializeForm?: boolean; + /** + * How long to wait when a request is made before triggering request, useful for rate limiting oninput + * + * @default 0 + */ + throttle?: number; + /** + * When set to false will not delay the first request made, when no others are queued + * + * @default true + */ + throttleFirstRequest?: boolean; + /** + * Whether an API request can occur while another request is still pending + * + * @default false + */ + interruptRequests?: boolean; + /** + * Minimum duration to show loading indication + * + * @default 0 + */ + loadingDuration?: number; + /** + * The default auto will automatically remove error state after error duration, unless the element is a form + * + * @default 'auto' + */ + hideError?: 'auto' | boolean; + /** + * Setting to true, will not remove error. + * Setting to a duration in milliseconds to show error state after request error. + * + * @default 2000 + */ + errorDuration?: true | number; + + // endregion + + // region Request Settings + + /** + * Named API action for query, originally specified in $.fn.settings.api + */ + action?: string | false; + /** + * Templated URL for query, will override specified action + */ + url?: string | false; + /** + * Variables to use for replacement + */ + urlData?: any | false; + /** + * Can be set to a Javascript object which will be returned automatically instead of requesting JSON from server + */ + response?: any | false; + /** + * When specified, this function can be used to retrieve content from a server and return it asynchronously instead of a standard AJAX call. + * The callback function should return the server response. + * + * @default false + */ + responseAsync?: ((settings: ApiSettings, callback: (response: any) => void) => void) | false; + /** + * @see response + */ + mockResponse?: any | false; + /** + * @see responseAsync + */ + mockResponseAsync?: ((settings: ApiSettings, callback: (response: any) => void) => void) | false; + /** + * Method for transmitting request to server + */ + method?: 'post' | 'get'; + /** + * Expected data type of response + */ + dataType?: 'xml' | 'json' | 'jsonp' | 'script' | 'html' | 'text'; + /** + * POST/GET Data to Send with Request + */ + data?: any; + + // endregion + + // region Callbacks + + /** + * Allows modifying settings before request, or cancelling request + */ + beforeSend?: (settings: ApiSettings) => any; + /** + * Allows modifying XHR object for request + */ + beforeXHR?: (xhrObject: JQueryXHR) => 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; + /** + * Allows modifying the server's response before parsed by other callbacks to determine API event success + */ + onResponse?: (response: any) => void; + /** + * Determines whether completed JSON response should be treated as successful + * + * @see {@link http://semantic-ui.com/behaviors/api.html#determining-json-success} + */ + successTest?: (response: any) => boolean; + /** + * Callback after successful response, JSON response must pass successTest + */ + onSuccess?: (response: any, element: JQuery, xhr: JQueryXHR) => void; + /** + * Callback on request complete regardless of conditions + */ + onComplete?: (response: any, element: JQuery, xhr: JQueryXHR) => void; + /** + * Callback on failed response, or JSON response that fails successTest + */ + onFailure?: (response: any, element: JQuery) => void; + /** + * Callback on server error from returned status code, or XHR failure. + */ + onError?: (errorMessage: string, element: JQuery, xhr: JQueryXHR) => void; + /** + * Callback on abort caused by user clicking a link or manually cancelling request. + */ + onAbort?: (errorMessage: string, element: JQuery, xhr: JQueryXHR) => void; + + // endregion + + // region DOM Settings + + /** + * Regular expressions used for template matching + */ + regExp?: { + /** + * @default /\{\$*[A-z0-9]+\}/g + */ + required?: RegExp; + /** + * @default /\{\/\$*[A-z0-9]+\}/g + */ + optional?: RegExp; + }; + /** + * Selectors used to find parts of a module + */ + selector?: { + /** + * @default '.disabled' + */ + disabled?: string; + /** + * @default 'form' + */ + form?: string; + }; + /** + * Class names used to determine element state + */ + className?: { + /** + * @default 'loading' + */ + loading?: string; + /** + * @default 'error' + */ + error?: string; + }; + /** + * Metadata used to store XHR and response promise + */ + metadata?: { + /** + * @default 'action' + */ + action?: string; + /** + * @default 'url' + */ + url?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The before send function has aborted the request' + */ + beforeSend?: string; + /** + * @default 'There was an error with your request' + */ + error?: string; + /** + * @default 'API Request Aborted. Exit conditions met' + */ + exitConditions?: string; + /** + * @default 'JSON could not be parsed during error handling' + */ + JSONParse?: string; + /** + * @default 'You are using legacy API success callback names' + */ + legacyParameters?: string; + /** + * @default 'API action used but no url was defined' + */ + missingAction?: string; + /** + * @default 'Required dependency jquery-serialize-object missing, using basic serialize' + */ + missingSerialize?: string; + /** + * @default 'No URL specified for API event' + */ + missingURL?: string; + /** + * @default 'The beforeSend callback must return a settings object, beforeSend ignored.' + */ + noReturnedValue?: string; + /** + * @default 'There was an error parsing your request' + */ + parseError?: string; + /** + * @default 'Missing a required URL parameter: ' + */ + requiredParameter?: string; + /** + * @default 'Server gave an error: ' + */ + statusMessage?: string; + /** + * @default 'Your request timed out' + */ + timeout?: string; + }; + + // endregion + } + + // endregion + + // region Form Validation + + /** + * @see {@link http://semantic-ui.com/behaviors/form.html#/settings} + */ + interface FormSettings extends ComponentSettings { + // region Form Settings + + /** + * Adds keyboard shortcuts for enter and escape keys to submit form and blur fields respectively + * + * @default true + */ + keyboardShortcuts?: boolean; + /** + * Event used to trigger validation. Can be either submit, blur or change. + * + * @default 'submit' + */ + on?: 'submit' | 'blur' | 'change'; + /** + * If set to true will revalidate fields with errors on input change + * + * @default true + */ + revalidate?: boolean; + /** + * Delay from last typed letter to validate a field when using on: change or when revalidating a field. + * + * @default true + */ + delay?: boolean; + /** + * Adds inline error on field validation error + * + * @default false + */ + inline?: boolean; + /** + * Named transition to use when animating validation errors. Fade and slide down are available without including ui transitions + * + * @default 'scale' + * @see {@link http://semantic-ui.com/modules/transition.html} + */ + transition?: string; + /** + * Animation speed for inline prompt + * + * @default 150 + */ + duration?: number; + + // endregion + + // region Form Prompts + + text?: { + /** + * @default 'Please enter a valid value' + */ + unspecifiedRule?: string; + /** + * @default 'This field' + */ + unspecifiedField?: string; + }; + prompt?: { + /** + * @default '{name} must have a value' + */ + empty?: string; + /** + * @default '{name} must be checked' + */ + checked?: string; + /** + * @default '{name} must be a valid e-mail' + */ + email?: string; + /** + * @default '{name} must be a valid url' + */ + url?: string; + /** + * @default '{name} is not formatted correctly' + */ + regExp?: string; + /** + * @default '{name} must be an integer' + */ + integer?: string; + /** + * @default '{name} must be a decimal number' + */ + decimal?: string; + /** + * @default '{name} must be set to a number' + */ + number?: string; + /** + * @default '{name} must be \'{ruleValue}\'' + */ + is?: string; + /** + * @default '{name} must be exactly \'{ruleValue}\'' + */ + isExactly?: string; + /** + * @default '{name} cannot be set to \'{ruleValue}\'' + */ + not?: string; + /** + * @default '{name} cannot be set to exactly \'{ruleValue}\'' + */ + notExactly?: string; + /** + * @default '{name} cannot contain \'{ruleValue}\'' + */ + contain?: string; + /** + * @default '{name} cannot contain exactly \'{ruleValue}\'' + */ + containExactly?: string; + /** + * @default '{name} must contain \'{ruleValue}\'' + */ + doesntContain?: string; + /** + * @default '{name} must contain exactly \'{ruleValue}\'' + */ + doesntContainExactly?: string; + /** + * @default '{name} must be at least {ruleValue} characters' + */ + minLength?: string; + /** + * @default '{name} must be at least {ruleValue} characters' + */ + length?: string; + /** + * @default '{name} must be exactly {ruleValue} characters' + */ + exactLength?: string; + /** + * @default '{name} cannot be longer than {ruleValue} characters' + */ + maxLength?: string; + /** + * @default '{name} must match {ruleValue} field' + */ + match?: string; + /** + * @default '{name} must have a different value than {ruleValue} field' + */ + different?: string; + /** + * @default '{name} must be a valid credit card number' + */ + creditCard?: string; + /** + * @default '{name} must have at least {ruleValue} choices' + */ + minCount?: string; + /** + * @default '{name} must have exactly {ruleValue} choices' + */ + exactCount?: string; + /** + * @default '{name} must have {ruleValue} or less choices' + */ + maxCount?: string; + }; + + // endregion + + // region Callbacks + + /** + * Callback on each valid field + */ + onValid?: (this: JQuery) => void; + /** + * Callback on each invalid field + */ + onInvalid?: (this: JQuery) => void; + /** + * Callback if a form is all valid + */ + onSuccess?: (this: JQuery, event: JQueryEventObject, fields: any) => void; + /** + * Callback if any form field is invalid + */ + onFailure?: (this: JQuery, formErrors: string[], fields: any) => void; + + // endregion + + // region DOM Settings + + /** + * Selectors used to match functionality to DOM + */ + selector?: { + /** + * @default '.error.message' + */ + message?: string; + /** + * @default 'input, textarea, select' + */ + field?: string; + /** + * @default '.field' + */ + group?: string; + /** + * @default 'input' + */ + input?: string; + /** + * @default '.prompt' + */ + prompt?: string; + /** + * @default '.submit' + */ + submit?: string; + }; + /** + * HTML5 metadata attributes + */ + metadata?: { + /** + * @default 'validate' + */ + validate?: string; + }; + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'active' + */ + active?: string; + /** + * @default 'default' + */ + placeholder?: string; + /** + * @default 'disabled' + */ + disabled?: string; + /** + * @default 'visible' + */ + visible?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + // endregion + + // region Visibility + + /** + * @see {@link http://semantic-ui.com/behaviors/visibility.html#/settings} + */ + interface VisibilitySettings extends ComponentSettings { + // region Functionality + + /** + * When set to false a callback will occur each time an element passes the threshold for a condition. + * + * @default true + */ + once?: boolean; + /** + * When set to true a callback will occur anytime an element passes a condition not just immediately after the threshold is met. + * + * @default false + */ + continuous?: boolean; + /** + * Set to image to load images when on screen. Set to fixed to add class name fixed when passed. + * + * @default false + */ + type?: false | 'image' | 'fixed'; + /** + * Whether visibility conditions should be checked immediately on init + * + * @default true + */ + initialCheck?: boolean; + /** + * The scroll context visibility should use. + * + * @default 'window' + */ + context?: Selector; + /** + * Whether visibility conditions should be checked on window load. This ensures that after images load content positions will be updated correctly. + * + * @default true + */ + refreshOnLoad?: boolean; + /** + * Whether visibility conditions should be checked on window resize. Useful when content resizes causes continuous changes in position + * + * @default true + */ + refreshOnResize?: boolean; + /** + * Whether visibility conditions should be checked on calls to refresh. + * These calls can be triggered from either resize, load or manually calling $('.foo').visibility('refresh') + * + * @default true + */ + checkOnRefresh?: boolean; + /** + * Specify a z-index when using type: 'fixed'. + * + * @default 1 + * @since 2.2 + */ + zIndex?: number; + /** + * Value that context scrollTop should be adjusted in pixels. Useful for making content appear below content fixed to the page. + * + * @default 0 + */ + offset?: number; + /** + * Whether element calculations should include its margin + * + * @default false + */ + includeMargin?: boolean; + /** + * When set to an integer, scroll position will be debounced using this ms value. false will debounce with requestAnimationFrame. + * + * @default false + */ + throttle?: false | number; + /** + * Whether to automatically refresh content when changes are made to the element's DOM subtree + * + * @default true + */ + observeChanges?: boolean; + /** + * When using type: image allows you to specify transition when showing a loaded image + * + * @default false + */ + transition?: false | string; + /** + * When using type: image allows you to specify transition duration + * + * @default 1000 + */ + duration?: number; + + // endregion + + // region Visibility Callbacks + + /** + * Element's top edge has passed bottom of screen + */ + onTopVisible?: (this: JQuery) => void; + /** + * Element's top edge has passed top of the screen + */ + onTopPassed?: (this: JQuery) => void; + /** + * Element's bottom edge has passed bottom of screen + */ + onBottomVisible?: (this: JQuery) => void; + /** + * Any part of an element is visible on screen + */ + onPassing?: (this: JQuery) => void; + /** + * Element's bottom edge has passed top of screen + */ + onBottomPassed?: (this: JQuery) => void; + /** + * Element's top edge has not passed bottom of screen + */ + onTopVisibleReverse?: (this: JQuery) => void; + /** + * Element's top edge has not passed top of the screen + */ + onTopPassedReverse?: (this: JQuery) => void; + /** + * Element's bottom edge has not passed bottom of screen + */ + onBottomVisibleReverse?: (this: JQuery) => void; + /** + * Element's top has not passed top of screen but bottom has + */ + onPassingReverse?: (this: JQuery) => void; + /** + * Element's bottom edge has not passed top of screen + */ + onBottomPassedReverse?: (this: JQuery) => void; + + // endregion + + // region Image Callbacks + + /** + * Occurs after an image has completed loading + * + * @since 2.2 + */ + onLoad?: (this: JQuery) => void; + /** + * Occurs after all img initialized at the same time have loaded. + * + * @since 2.2 + */ + onAllLoaded?: (this: JQuery) => void; + + // endregion + + // region Fixed Callbacks + + /** + * Occurs after element has been assigned position fixed + * + * @since 2.2 + */ + onFixed?: (this: JQuery) => void; + /** + * Occurs after element has been removed from fixed position + * + * @since 2.2 + */ + onUnfixed?: (this: JQuery) => void; + + // endregion + + // region Utility Callbacks + + /** + * Occurs each time an elements calculations are updated + */ + onUpdate?: (this: JQuery, calculations: ElementCalculations) => void; + /** + * Occurs whenever element's visibility is refreshed + */ + onRefresh?: (this: JQuery) => void; + + // endregion + + // region DOM Settings + + /** + * Class names used to attach style to state + */ + className?: { + /** + * @default 'fixed' + */ + fixed?: string; + }; + + // endregion + + // region Debug Settings + + error?: { + /** + * @default 'The method you called is not defined.' + */ + method?: string; + }; + + // endregion + } + + interface ElementPosition { + fits: boolean; + offset: JQueryCoordinates; + width: number; + height: number; + } + + interface ElementCalculations extends ElementPosition { + margin?: { + top: number; + bottom: number; + }; + top: number; + bottom: number; + + topVisible: boolean; + topPassed: boolean; + bottomVisible: boolean; + bottomPassed: boolean; + pixelsPassed: number; + percentagePassed: number; + + onScreen: boolean; + passing: boolean; + offScreen: boolean; + } + + interface ScreenCalculations { + top: number; + bottom: number; + } + + interface ScreenSize { + height: number; + } + + // endregion + + // endregion +} diff --git a/semantic-ui/semantic-ui-tests.ts b/semantic-ui/semantic-ui-tests.ts new file mode 100644 index 0000000000..f116507459 --- /dev/null +++ b/semantic-ui/semantic-ui-tests.ts @@ -0,0 +1,140 @@ +function test_Accordion() { + const selector = '.ui.accordion'; + $(selector).accordion('refresh'); + $(selector).accordion('open', 0); + $(selector).accordion('close others'); + $(selector).accordion('close', 0); + $(selector).accordion('toggle', 0); + $(selector).accordion({ + selector: { + trigger: '.title .icon' + } + }); + $(selector).accordion(); +} +test_Accordion(); + +function test_Checkbox() { + const selector = '.ui.checkbox'; + $(selector).checkbox({}); + $(selector).checkbox(); +} +test_Checkbox(); + +function test_Dimmer() { + const selector = '.ui.dimmer'; + $(selector).dimmer({}); + $(selector).dimmer(); +} +test_Dimmer(); + +function test_Dropdown() { + const selector = '.ui.dropdown'; + $(selector).dropdown({}); + $(selector).dropdown(); +} +test_Dropdown(); + +function test_Embed() { + const selector = '.ui.embed'; + $(selector).embed({}); + $(selector).embed(); +} +test_Embed(); + +function test_Modal() { + const selector = '.ui.modal'; + $(selector).modal({}); + $(selector).modal(); +} +test_Modal(); + +function test_Nag() { + const selector = '.ui.nag'; + $(selector).nag({}); +} +test_Nag(); + +function test_Popup() { + const selector = '.ui.popup'; + $(selector).popup({}); + $(selector).popup(); +} +test_Popup(); + +function test_Progress() { + const selector = '.ui.progress'; + $(selector).progress({}); + $(selector).progress(); +} +test_Progress(); + +function test_Rating() { + const selector = '.ui.rating'; + $(selector).rating({}); + $(selector).rating(); +} +test_Rating(); + +function test_Search() { + const selector = '.ui.search'; + $(selector).search({}); + $(selector).search(); +} +test_Search(); + +function test_Shape() { + const selector = '.ui.shape'; + $(selector).shape({}); + $(selector).shape(); +} +test_Shape(); + +function test_Sidebar() { + const selector = '.ui.sidebar'; + $(selector).sidebar({}); + $(selector).sidebar(); +} +test_Sidebar(); + +function test_Sticky() { + const selector = '.ui.sticky'; + $(selector).sticky({}); + $(selector).sticky(); +} +test_Sticky(); + +function test_Tab() { + const selector = '.ui.tab'; + $(selector).tab({}); + $(selector).tab(); +} +test_Tab(); + +function test_Transition() { + const selector = '.ui.transition'; + $(selector).transition({}); + $(selector).transition(); +} +test_Transition(); + +function test_Api() { + const selector = '.ui.api'; + $(selector).api({}); + $(selector).api(); +} +test_Api(); + +function test_Form() { + const selector = '.ui.form'; + $(selector).form({}); + $(selector).form(); +} +test_Form(); + +function test_Visibility() { + const selector = '.ui.visibility'; + $(selector).visibility({}); + $(selector).visibility(); +} +test_Visibility(); diff --git a/semantic-ui/tsconfig.json b/semantic-ui/tsconfig.json new file mode 100644 index 0000000000..510c5ecd05 --- /dev/null +++ b/semantic-ui/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", + "semantic-ui-tests.ts" + ] +} \ No newline at end of file diff --git a/semantic-ui/tslint.json b/semantic-ui/tslint.json new file mode 100644 index 0000000000..68d10d72a6 --- /dev/null +++ b/semantic-ui/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "unified-signatures": false + } +} diff --git a/semver-diff/semver-diff-tests.ts b/semver-diff/semver-diff-tests.ts index fca7d8552e..e3ad74c462 100644 --- a/semver-diff/semver-diff-tests.ts +++ b/semver-diff/semver-diff-tests.ts @@ -1,15 +1,15 @@ import semverDiff = require('semver-diff'); -semverDiff('1.1.1', '1.1.2'); //=> 'patch' +semverDiff('1.1.1', '1.1.2'); // => 'patch' -semverDiff('0.0.1', '1.0.0'); //=> 'major' +semverDiff('0.0.1', '1.0.0'); // => 'major' -semverDiff('0.0.1', '0.1.0'); //=> 'minor' +semverDiff('0.0.1', '0.1.0'); // => 'minor' -semverDiff('0.0.1-foo', '0.0.1-foo.bar'); //=> 'prerelease' +semverDiff('0.0.1-foo', '0.0.1-foo.bar'); // => 'prerelease' -semverDiff('0.1.0', '0.1.0+foo'); //=> 'build' +semverDiff('0.1.0', '0.1.0+foo'); // => 'build' -semverDiff('0.0.1', '0.0.1'); //=> null +semverDiff('0.0.1', '0.0.1'); // => null -semverDiff('0.0.2', '0.0.1'); //=> null +semverDiff('0.0.2', '0.0.1'); // => null diff --git a/sequelize-fixtures/index.d.ts b/sequelize-fixtures/index.d.ts index 2810e7b2ea..b865d91d0c 100644 --- a/sequelize-fixtures/index.d.ts +++ b/sequelize-fixtures/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/domasx2/sequelize-fixtures // Definitions by: Christian Schwarz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/sequelize/index.d.ts b/sequelize/index.d.ts index a2a9b6380c..85283ff468 100644 --- a/sequelize/index.d.ts +++ b/sequelize/index.d.ts @@ -2,6 +2,7 @@ // Project: http://sequelizejs.com // Definitions by: samuelneff , Peter Harris , Ivan Drinchev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 // Based on original work by: samuelneff @@ -3318,38 +3319,25 @@ declare namespace sequelize { /** * Options for Model.findOrInitialize method */ - interface FindOrInitializeOptions extends LoggingOptions { - - /** - * A hash of search attributes. - */ - where: string | WhereOptions; + interface FindOrInitializeOptions extends FindOptions { /** * Default values to use if building a new instance */ defaults?: TAttributes; - /** - * Transaction to run query under - */ - transaction?: Transaction; } /** - * Options for Model.findOrInitialize method + * Options for Model.findOrInitialize method */ - interface FindCreateFindOptions { + interface FindCreateFindOptions extends FindOptions { /** - * A hash of search attributes. - */ - where: string | WhereOptions; - - /** - * Default values to use if building a new instance + * Default values to use if building a new instance */ defaults?: TAttributes; + } /** diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 973f98076c..9a54ea6d64 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -977,6 +977,7 @@ let findOrRetVal: Promise<[AnyInstance, boolean]>; findOrRetVal = User.findOrInitialize( { where : { username : 'foo' } } ); findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, paranoid : false } ); findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); @@ -989,7 +990,6 @@ findOrRetVal = User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults findOrRetVal = User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); findOrRetVal = User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); findOrRetVal = User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); -findOrRetVal = User.findOrCreate( { where : 'c', defaults : {} } ); User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); diff --git a/sequelize/v3/index.d.ts b/sequelize/v3/index.d.ts index 8b22524878..9142dc9a6c 100644 --- a/sequelize/v3/index.d.ts +++ b/sequelize/v3/index.d.ts @@ -2,6 +2,7 @@ // Project: http://sequelizejs.com // Definitions by: samuelneff , Peter Harris , Ivan Drinchev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 // Based on original work by: samuelneff @@ -3818,8 +3819,8 @@ declare namespace sequelize { * Find a row that matches the query, or build (but don't save) the row if none is found. * The successfull result of the promise will be (instance, initialized) - Make sure to use .spread() */ - findOrInitialize(options: FindOrInitializeOptions): Promise; - findOrBuild(options: FindOrInitializeOptions): Promise; + findOrInitialize(options: FindOrInitializeOptions): Promise<[TInstance, boolean]>; + findOrBuild(options: FindOrInitializeOptions): Promise<[TInstance, boolean]>; /** * Find a row that matches the query, or build and save the row if none is found @@ -3832,13 +3833,13 @@ declare namespace sequelize { * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint * will be created instead, and any unique constraint violation will be handled internally. */ - findOrCreate(options: FindOrInitializeOptions): Promise; + findOrCreate(options: FindOrInitializeOptions): Promise<[TInstance, boolean]>; /** * A more performant findOrCreate that will not work under a transaction (at least not in postgres) * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again */ - findCreateFind(options: FindCreateFindOptions): Promise; + findCreateFind(options: FindCreateFindOptions): Promise<[TInstance, boolean]>; /** * Insert or update a single row. An update will be executed if a row which matches the supplied values on diff --git a/serialport/index.d.ts b/serialport/index.d.ts index 60c240bbda..d94ab9d79f 100644 --- a/serialport/index.d.ts +++ b/serialport/index.d.ts @@ -1,24 +1,24 @@ -// Type definitions for serialport 4.0.1 +// Type definitions for serialport 4.0 // Project: https://github.com/EmergingTechnologyAdvisors/node-serialport // Definitions by: Jeremy Foster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'serialport' { class SerialPort { - constructor(path: string, options?: Object, openImmediately?: boolean, callback?: (err: string) => void) - isOpen: boolean; + constructor(path: string, options?: Object, openImmediately?: boolean, callback?: (err: any) => void) + isOpen(): boolean; on(event: string, callback?: (data?: any) => void): void; - open(callback?: () => void): void; - write(buffer: any, callback?: (err: string, bytesWritten: number) => void): void + open(callback?: (err: any) => void): void; + write(buffer: any, callback?: (err: any, bytesWritten: number) => void): void pause(): void; resume(): void; disconnected(err: Error): void; - close(callback?: (err:any) => void): void; - flush(callback?: (err:any) => void): void; - set(options: SerialPort.setOptions, callback: () => void): void; - drain(callback?: (err:any) => void): void; - update(options: SerialPort.updateOptions, callback?: () => void): void; - static list(callback: (err: string, ports: SerialPort.portConfig[]) => void): void; + close(callback?: (err: any) => void): void; + flush(callback?: (err: any) => void): void; + set(options: SerialPort.setOptions, callback: (err: any) => void): void; + drain(callback?: (err: any) => void): void; + update(options: SerialPort.updateOptions, callback?: (err: any) => void): void; + static list(callback: (err: any, ports: SerialPort.portConfig[]) => void): void; static parsers: { readline: (delimiter: string) => void, raw: (emitter: any, buffer: string) => void @@ -49,5 +49,5 @@ declare module 'serialport' { } } - export = SerialPort + export = SerialPort; } diff --git a/service_worker_api/service_worker_api-tests.ts b/service_worker_api/service_worker_api-tests.ts index b2e183aa05..5cfae785cc 100644 --- a/service_worker_api/service_worker_api-tests.ts +++ b/service_worker_api/service_worker_api-tests.ts @@ -1,14 +1,14 @@ var OFFLINE_CACHE = "cache_test"; var OFFLINE_URL = "localhost"; -self.addEventListener('fetch', function(event: FetchEvent) { +self.addEventListener('fetch', (event: FetchEvent) => { if (event.request.method === 'GET' && event.request.headers.get('accept').indexOf('text/html') !== -1) { console.log('Handling fetch event for', event.request.url); event.respondWith( - self.fetch(event.request).catch(function(e) { + self.fetch(event.request).catch(e => { console.error('Fetch failed; returning offline page instead.', e); - return self.caches.open(OFFLINE_CACHE).then(function(cache: Cache) { + return self.caches.open(OFFLINE_CACHE).then((cache: Cache) => { return cache.match(OFFLINE_URL); }); }) @@ -16,25 +16,25 @@ self.addEventListener('fetch', function(event: FetchEvent) { } }); -self.caches.open('v1').then(function(cache: Cache) { - cache.matchAll('/images/').then(function(response: Response[]) { - response.forEach(function(element, index, array) { +self.caches.open('v1').then((cache: Cache) => { + cache.matchAll('/images/').then((response: Response[]) => { + response.forEach((element, index, array) => { cache.delete(element.url); }); }); }); -self.addEventListener('install', function(event: InstallEvent) { +self.addEventListener('install', (event: InstallEvent) => { event.waitUntil( - self.caches.open('v1').then(function(cache: Cache) { + self.caches.open('v1').then((cache: Cache) => { return cache.add('/sw-test/index.html'); }) ); }); -self.addEventListener('install', function(event: InstallEvent) { +self.addEventListener('install', (event: InstallEvent) => { event.waitUntil( - self.caches.open('v1').then(function(cache) { + self.caches.open('v1').then(cache => { return cache.addAll([ '/sw-test/', '/sw-test/index.html', @@ -51,50 +51,50 @@ self.addEventListener('install', function(event: InstallEvent) { ); }); -self.addEventListener('fetch', function(event: FetchEvent) { - var cachedResponse = self.caches.match(event.request).then(function(response: Response) { +self.addEventListener('fetch', (event: FetchEvent) => { + var cachedResponse = self.caches.match(event.request).then(response => { if (response) { return response; } - }).catch(function() { - return self.fetch(event.request).then(function(response: Response) { - return self.caches.open('v1').then(function(cache) { + }).catch(() => { + return self.fetch(event.request).then(response => { + return self.caches.open('v1').then(cache => { cache.put(event.request, response.clone()); return response; }); }); - }).catch(function() { + }).catch(() => { return self.caches.match('/sw-test/gallery/myLittleVader.jpg'); }); event.respondWith(cachedResponse); }); -self.caches.open('v1').then(function(cache) { - cache.match('/images/image.png').then(function(response: Response) { +self.caches.open('v1').then(cache => { + cache.match('/images/image.png').then(response => { cache.delete(response.url); }); }); -self.caches.open('v1').then(function(cache: Cache) { - cache.keys().then(function(response) { - response.forEach(function(element, index, array) { +self.caches.open('v1').then(cache => { + cache.keys().then(response => { + response.forEach((element, index, array) => { cache.delete(element); }); }); }); -self.caches.has('v1').then(function() { - self.caches.delete('v1').then(function() { +self.caches.has('v1').then(() => { + self.caches.delete('v1').then(() => { console.log('done'); }); }); -self.addEventListener('activate', function(event: ExtendableEvent) { +self.addEventListener('activate', (event: ExtendableEvent) => { var cacheWhitelist = ['v2']; event.waitUntil( - self.caches.keys().then(function(keyList) { + self.caches.keys().then(keyList => { for (var item of keyList) { if (cacheWhitelist.indexOf(item) === -1) { return self.caches.delete(item); @@ -105,9 +105,9 @@ self.addEventListener('activate', function(event: ExtendableEvent) { }); function sendMessage(message: any) { - return new Promise(function(resolve, reject) { + return new Promise((resolve, reject) => { var messageChannel = new MessageChannel(); - messageChannel.port1.onmessage = function(event) { + messageChannel.port1.onmessage = event => { if (event.data.error) { reject(event.data.error); } else { @@ -118,28 +118,28 @@ function sendMessage(message: any) { }); } -self.addEventListener('message', function(evt: ExtendableMessageEvent) { +self.addEventListener('message', (evt: ExtendableMessageEvent) => { evt.ports[0].postMessage(evt.source.id); }); -sendMessage('test').then(function(clientId: string) { +sendMessage('test').then((clientId: string) => { console.log(clientId); }); -self.clients.matchAll({type: "test"}).then(function(clients) { +self.clients.matchAll({type: "test"}).then(clients => { for (var cli of clients) { - if(cli.url === 'index.html') { + if (cli.url === 'index.html') { self.clients.openWindow(cli.url); // or do something else involving the matching client } } }); -self.addEventListener('activate', function(e: ExtendableEvent) { +self.addEventListener('activate', (e: ExtendableEvent) => { e.waitUntil(self.clients.claim()); }); -navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(function(registration) { +navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(registration => { // At this point, registration has taken place. // The service worker will not handle requests until this page and any // other instances of this page (in other tabs, etc.) have been @@ -154,31 +154,31 @@ navigator.serviceWorker.register('service-worker.js', {scope: './'}).then(functi } if (serviceWorker) { console.log(serviceWorker.state); - serviceWorker.addEventListener('statechange', function(e: any) { + serviceWorker.addEventListener('statechange', (e: any) => { console.log(e.target.state); }); } -}).catch(function(error) { +}).catch(error => { // Something went wrong during registration. The service-worker.js file // might be unavailable or contain a syntax error. }); -navigator.serviceWorker.getRegistration('/app').then(function(registration: ServiceWorkerRegistration) { +navigator.serviceWorker.getRegistration('/app').then((registration: ServiceWorkerRegistration) => { console.log(registration); }); -navigator.serviceWorker.getRegistrations().then(function(registrations: ServiceWorkerRegistration[]) { +navigator.serviceWorker.getRegistrations().then((registrations: ServiceWorkerRegistration[]) => { console.log(registrations); }); self.registration.unregister(); -self.addEventListener('install', function(event: ExtendableEvent) { +self.addEventListener('install', (event: ExtendableEvent) => { event.waitUntil(self.skipWaiting()); }); -self.addEventListener('notificationclick', function(event: NotificationEvent) { +self.addEventListener('notificationclick', (event: NotificationEvent) => { console.log('On notification click: ', event.notification.tag); event.notification.close(); @@ -186,7 +186,7 @@ self.addEventListener('notificationclick', function(event: NotificationEvent) { // focuses if it is event.waitUntil(self.clients.matchAll({ type: "window" - }).then(function(clientList) { + }).then(clientList => { if (self.clients.openWindow) return self.clients.openWindow('/'); })); diff --git a/service_worker_api/tslint.json b/service_worker_api/tslint.json index f9e30021f4..377cc837d4 100644 --- a/service_worker_api/tslint.json +++ b/service_worker_api/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/sha1/sha1-tests.ts b/sha1/sha1-tests.ts index f2c6547f2b..22467632c8 100644 --- a/sha1/sha1-tests.ts +++ b/sha1/sha1-tests.ts @@ -1,5 +1,3 @@ -/// - import fs = require("fs"); import sha1 = require("sha1"); /** @@ -31,6 +29,6 @@ console.log(sha1('message')); // should print 6f9b9af3cd6e8b8a73c2cdced37fe9f592 const testTwo = sha1('message', {asString: true}); const testThree = sha1('message', {asBytes: true}); -fs.readFile('sha1.d.ts', function(err: Error, buf: Buffer) { +fs.readFile('sha1.d.ts', (err: Error, buf: Buffer) => { console.log(sha1(buf)); }); diff --git a/sharepoint/index.d.ts b/sharepoint/index.d.ts index 22bed0c0aa..1908d46b0c 100644 --- a/sharepoint/index.d.ts +++ b/sharepoint/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for SharePoint: 2010.1 / 2013.1 -// Project: https://github.com/gandjustas/sptypescript -// Definitions by: Stanislav Vyshchepan , Andrey Markeev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Project: https:// github.com/gandjustas/sptypescript +// Definitions by: Stanislav Vyshchepan , Andrey Markeev +// Definitions: https:// github.com/DefinitelyTyped/DefinitelyTyped /// @@ -34,17 +34,17 @@ declare namespace SP { } export enum ListLevelPermissionMask { - viewListItems, //: 1, - insertListItems, //: 2, - editListItems, //: 4, - deleteListItems, //: 8, - approveItems, //: 16, - openItems, //: 32, - viewVersions, //: 64, - deleteVersions, //: 128, - breakCheckout, //: 256, - managePersonalViews, //: 512, - manageLists //: 2048 + viewListItems, // : 1, + insertListItems, // : 2, + editListItems, // : 4, + deleteListItems, // : 8, + approveItems, // : 16, + openItems, // : 32, + viewVersions, // : 64, + deleteVersions, // : 128, + breakCheckout, // : 256, + managePersonalViews, // : 512, + manageLists // : 2048 } export class HtmlBuilder { @@ -154,32 +154,32 @@ declare class JSRequest { } declare class _spPageContextInfo { - static alertsEnabled: boolean; //true - static allowSilverlightPrompt: string; //"True" - static clientServerTimeDelta: number; //-182 - static crossDomainPhotosEnabled: boolean; //true - static currentCultureName: string; //"ru-RU" - static currentLanguage: number; //1049 - static currentUICultureName: string; //"ru-RU" - static layoutsUrl: string; //"_layouts/15" - static pageListId: string; //"{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" + static alertsEnabled: boolean; // true + static allowSilverlightPrompt: string; // "True" + static clientServerTimeDelta: number; // -182 + static crossDomainPhotosEnabled: boolean; // true + static currentCultureName: string; // "ru-RU" + static currentLanguage: number; // 1049 + static currentUICultureName: string; // "ru-RU" + static layoutsUrl: string; // "_layouts/15" + static pageListId: string; // "{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" static pageItemId: number; - static pagePersonalizationScope: string; //1 - static serverRequestPath: string; //"/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" - static siteAbsoluteUrl: string; // "https://gandjustas-7b20d3715e8ed4.sharepoint.com" - static siteClientTag: string; //"0$$15.0.4454.1021" + static pagePersonalizationScope: string; // 1 + static serverRequestPath: string; // "/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" + static siteAbsoluteUrl: string; // "https:// gandjustas-7b20d3715e8ed4.sharepoint.com" + static siteClientTag: string; // "0$$15.0.4454.1021" static siteServerRelativeUrl: string; // "/" - static systemUserKey: string; //"i:0h.f|membership|10033fff84e7cb2b@live.com" - static tenantAppVersion: string; //"0" - static userId: number; //12 - static webAbsoluteUrl: string; //"https://gandjustas-7b20d3715e8ed4.sharepoint.com/SPTypeScript" - static webLanguage: number; //1049 - static webLogoUrl: string; //"/_layouts/15/images/siteIcon.png?rev=23" + static systemUserKey: string; // "i:0h.f|membership|10033fff84e7cb2b@live.com" + static tenantAppVersion: string; // "0" + static userId: number; // 12 + static webAbsoluteUrl: string; // "https:// gandjustas-7b20d3715e8ed4.sharepoint.com/SPTypeScript" + static webLanguage: number; // 1049 + static webLogoUrl: string; // "/_layouts/15/images/siteIcon.png?rev=23" static webPermMasks: { High: number; Low: number; }; - static webServerRelativeUrl: string; //"/SPTypeScript" - static webTemplate: string; //"17" - static webTitle: string; //"SPTypeScript" - static webUIVersion: number; //15 + static webServerRelativeUrl: string; // "/SPTypeScript" + static webTemplate: string; // "17" + static webTitle: string; // "SPTypeScript" + static webUIVersion: number; // 15 } declare function STSHtmlEncode(value: string): string; @@ -268,7 +268,7 @@ interface ContextInfo extends SPClientTemplates.RenderContext { LastSelectedItemIID: number; LastRowIndexSelected: number; RowFocusTimerID: number; - ListData: any; //SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm + ListData: any; // SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm ListSchema: SPClientTemplates.ListSchema; ModerationStatus: number; PortalUrl: string; @@ -356,7 +356,7 @@ declare namespace SP { body?: string | Uint8Array; binaryStringRequestBody?: boolean; - /** Currently need fix to get ginary response. Details: http://techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ + /** Currently need fix to get ginary response. Details: http:// techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ binaryStringResponseBody?: boolean; timeout?: number; success?: (response: ResponseInfo) => void; @@ -810,7 +810,7 @@ declare namespace SPClientTemplates { export interface FieldSchema_InForm_Lookup extends FieldSchema_InForm { /** Specifies if the field allows multiple values */ AllowMultipleValues: boolean; - /** Returns base url for a list display form, e.g. "http://portal/web/_layouts/15/listform.aspx?PageType=4" + /** Returns base url for a list display form, e.g. "http:// portal/web/_layouts/15/listform.aspx?PageType=4" You must add "ListId" (Guid of the list) and "ID" (integer Id of the item) parameters in order to use this Url */ BaseDisplayFormUrl: string; /** Indicates if the field is a dependent lookup */ @@ -1464,13 +1464,13 @@ declare namespace SPClientForms { } export enum FormManagerEvents { - Event_OnControlValueChanged, //: 1, - Event_OnControlInitializedCallback, //: 2, - Event_OnControlFocusSetCallback, //: 3, - Event_GetControlValueCallback, //: 4, - Event_OnControlValidationError, //: 5, - Event_RegisterControlValidator, //: 6, - Event_GetHasValueChangedCallback //: 7 + Event_OnControlValueChanged, // : 1, + Event_OnControlInitializedCallback, // : 2, + Event_OnControlFocusSetCallback, // : 3, + Event_GetControlValueCallback, // : 4, + Event_OnControlValidationError, // : 5, + Event_RegisterControlValidator, // : 6, + Event_GetHasValueChangedCallback // : 7 } export class ClientForm { @@ -1624,7 +1624,7 @@ declare namespace SP { static isValid(uuid: string): boolean; toString(format?: string): string; equals(uuid: SP.Guid): boolean; - toSerialized(): string; + ToSerialized(): string; } /** Specifies permissions that are used to define user roles. Represents SPBasePermissions class. */ export enum PermissionKind { @@ -1734,11 +1734,11 @@ declare namespace SP { export class ClientObjectPropertyConditionalScope extends SP.ConditionalScopeBase { constructor(clientObject: SP.ClientObject, propertyName: string, comparisonOperator: string, valueToCompare: any, allowAllActions?: boolean); } - //export class ClientResult { + // export class ClientResult { // get_value(): any; // setValue(value: any): void; // constructor(); - //} + // } export class ClientResult { get_value(): T; setValue(value: T): void; @@ -5235,7 +5235,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } export class QueryPersonalizationData extends SP.ClientObject { - //It's really empty; + // It's really empty; } export class QuerySuggestionResults extends SP.ClientValueObject { @@ -5561,7 +5561,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } export class SearchConfigurationPortabilityPropertyNames { - static importWarnings: string; //= 'ImportWarnings' + static importWarnings: string; // = 'ImportWarnings' } } @@ -5890,12 +5890,12 @@ declare namespace SP { } // For some reasons this enum doesn't exist - //export enum SocialFollowResult { + // export enum SocialFollowResult { // ok = 0, // alreadyFollowing = 1, // limitReached = 2, // internalError = 3 - //} + // } /** Provides information about the feed. This type provides information about whether the feed on the server contains additional threads that were not returned. */ @@ -6619,7 +6619,7 @@ declare namespace SP { set_owner(value: string): void; get_terms(): TermCollection; createTerm(name: string, lcid: number, newTermId: SP.Guid): Term; - /*getTerms(pagingLimit: number): TermCollection;*/ //Moved to descendants to void TypeScript errors + /*getTerms(pagingLimit: number): TermCollection;*/ // Moved to descendants to void TypeScript errors reuseTerm(sourceTerm: Term, reuseBranch: boolean): Term; reuseTermWithPinning(sourceTerm: Term): Term; deleteCustomProperty(name: string): void; @@ -7683,7 +7683,7 @@ declare namespace SP { /** The Follow method adds the specified document or site to the list of followed content. @param url URL that identifies the item to follow. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= @param data Optional parameter that holds application-defined data for the item. */ follow(url: string, data?: FollowedItemData): FollowResult; @@ -7694,23 +7694,23 @@ declare namespace SP { /** Removes the specified document or site from list of followed content. @param url URL that identifies the item to stop following. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ stopFollowing(url: string): void; /** Determines if the specified document or site is being followed. @param url URL that identifies the item that is supposed to be followed. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ isFollowed(url: string): SP.BooleanResult; /** Retrieves the followed status of the specified document or site. Returns a value of type FollowedStatus, wrapped into a SP.IntResult object. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ getFollowedStatus(url: string): SP.IntResult; /** Returns the followed item identified by a given URL or returns null if the item does not exist. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ getItem(url: string): FollowedItem; /** Returns an array of zero or more followed items described by the type and subtype parameters. @param options Describes the type of item to return. @@ -7719,7 +7719,7 @@ declare namespace SP { /** Updates the properties for followed item with specified URL. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= @param data Application-defined data stored with the followed item. */ updateData(url: string, data: FollowedItemData): void; /** Returns the refreshed item that is being pointed to in the Social list. @@ -8936,9 +8936,9 @@ declare namespace SP { declare namespace SP { export namespace CompliancePolicy { export enum SPContainerType { - site, //: 0, - web, //: 1, - list //: 2 + site, // : 0, + web, // : 1, + list // : 2 } export class SPContainerId extends ClientObject { @@ -9203,10 +9203,10 @@ declare namespace SP { export namespace Discovery { export enum ExportStatus { - notStarted, //: 0, - started, //: 1, - complete, //: 2, - failed //: 3 + notStarted, // : 0, + started, // : 1, + complete, // : 2, + failed // : 3 } export class Case extends ClientObject { @@ -9261,11 +9261,11 @@ declare class SPClientAutoFill { Loading: number; }; - static KeyProperty: string; //= 'AutoFillKey'; - static DisplayTextProperty: string; //= 'AutoFillDisplayText'; - static SubDisplayTextProperty: string; //= 'AutoFillSubDisplayText'; - static TitleTextProperty: string; //= 'AutoFillTitleText'; - static MenuOptionTypeProperty: string; //= 'AutoFillMenuOptionType'; + static KeyProperty: string; // = 'AutoFillKey'; + static DisplayTextProperty: string; // = 'AutoFillDisplayText'; + static SubDisplayTextProperty: string; // = 'AutoFillSubDisplayText'; + static TitleTextProperty: string; // = 'AutoFillTitleText'; + static MenuOptionTypeProperty: string; // = 'AutoFillMenuOptionType'; static GetAutoFillObjFromInput(elmText: HTMLInputElement): SPClientAutoFill; static GetAutoFillObjFromContainer(elmChild: HTMLElement): SPClientAutoFill; @@ -9338,50 +9338,50 @@ declare class SPClientPeoplePicker { TopLevelElementId: string; // '', - EditorElementId: string; //'', - AutoFillElementId: string; //'', - ResolvedListElementId: string; //'', - InitialHelpTextElementId: string; //'', - WaitImageId: string; //'', - HiddenInputId: string; //'', - AllowEmpty: boolean; //true, - ForceClaims: boolean; //false, - AutoFillEnabled: boolean; //true, - AllowMultipleUsers: boolean; //false, + EditorElementId: string; // '', + AutoFillElementId: string; // '', + ResolvedListElementId: string; // '', + InitialHelpTextElementId: string; // '', + WaitImageId: string; // '', + HiddenInputId: string; // '', + AllowEmpty: boolean; // true, + ForceClaims: boolean; // false, + AutoFillEnabled: boolean; // true, + AllowMultipleUsers: boolean; // false, OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - UrlZone: SP.UrlZone; //null, - AllUrlZones: boolean; //false, - SharePointGroupID: number; //0, - AllowEmailAddresses: boolean; //false, + UrlZone: SP.UrlZone; // null, + AllUrlZones: boolean; // false, + SharePointGroupID: number; // 0, + AllowEmailAddresses: boolean; // false, PPMRU: SPClientPeoplePickerMRU; - UseLocalSuggestionCache: boolean; //true, - CurrentQueryStr: string; //'', + UseLocalSuggestionCache: boolean; // true, + CurrentQueryStr: string; // '', LatestSearchQueryStr: string; // '', InitialSuggestions: ISPClientPeoplePickerEntity[]; CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; - VisibleSuggestions: number; //5, - PrincipalAccountType: string; //'', + VisibleSuggestions: number; // 5, + PrincipalAccountType: string; // '', PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; - EnabledClaimProviders: string; //'', - SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, - ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, - MaximumEntitySuggestions: number; //30, - EditorWidthSet: boolean; //false, - QueryScriptInit: boolean; //false, - AutoFillControl: SPClientAutoFill; //null, - TotalUserCount: number; //0, - UnresolvedUserCount: number; //0, + EnabledClaimProviders: string; // '', + SearchPrincipalSource: SP.Utilities.PrincipalSource; // null, + ResolvePrincipalSource: SP.Utilities.PrincipalSource; // null, + MaximumEntitySuggestions: number; // 30, + EditorWidthSet: boolean; // false, + QueryScriptInit: boolean; // false, + AutoFillControl: SPClientAutoFill; // null, + TotalUserCount: number; // 0, + UnresolvedUserCount: number; // 0, UserQueryDict: { [index: string]: SP.StringResult }; ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; - HasInputError: boolean; //false, - HasServerError: boolean; //false, - ShowUserPresence: boolean; //true, - TerminatingCharacter: string; //';', - UnresolvedUserElmIdToReplace: string; //'', - WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', + HasInputError: boolean; // false, + HasServerError: boolean; // false, + ShowUserPresence: boolean; // true, + TerminatingCharacter: string; // ';', + UnresolvedUserElmIdToReplace: string; // '', + WebApplicationID: SP.Guid; // '{00000000-0000-0000-0000-000000000000}', GetAllUserInfo(): ISPClientPeoplePickerEntity[]; SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void @@ -9482,9 +9482,9 @@ interface ISPClientPeoplePickerSchema { } declare class SPClientPeoplePickerMRU { - static PPMRUVersion: number; //= 1; - static MaxPPMRUItems: number; //= 200; - static PPMRUDomLocalStoreKey: string; //= "ClientPeoplePickerMRU"; + static PPMRUVersion: number; // = 1; + static MaxPPMRUItems: number; // = 200; + static PPMRUDomLocalStoreKey: string; // = "ClientPeoplePickerMRU"; static GetSPClientPeoplePickerMRU(): SPClientPeoplePickerMRU; GetItems(strKey: string): { Key: string, [name: string]: any }; @@ -9513,18 +9513,18 @@ interface ISPClientPeoplePickerEntity { } declare class SPClientPeoplePickerProcessedUser { - UserContainerElementId: string; //'', - DisplayElementId: string; //'', - PresenceElementId: string; //'', - DeleteUserElementId: string; //'', - SID: string; //'', - DisplayName: string; //'', - SIPAddress: string; //'', - UserInfo: ISPClientPeoplePickerEntity; //null, - ResolvedUser: boolean; //true, - Suggestions: ISPClientAutoFillData[]; //null, - ErrorDescription: string; //'', - ResolveText: string; //'', + UserContainerElementId: string; // '', + DisplayElementId: string; // '', + PresenceElementId: string; // '', + DeleteUserElementId: string; // '', + SID: string; // '', + DisplayName: string; // '', + SIPAddress: string; // '', + UserInfo: ISPClientPeoplePickerEntity; // null, + ResolvedUser: boolean; // true, + Suggestions: ISPClientAutoFillData[]; // null, + ErrorDescription: string; // '', + ResolveText: string; // '', UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; UpdateSuggestions(entity: ISPClientPeoplePickerEntity): void; BuildUserHTML(): string; @@ -9713,126 +9713,126 @@ declare namespace SP { export namespace JsGrid { export enum TextDirection { - Default, //0, - RightToLeft, //1, - LeftToRight //2 + Default, // 0, + RightToLeft, // 1, + LeftToRight // 2 } export enum PaneId { - MainGrid, //0, - PivotedGrid, //1, - Gantt //2 + MainGrid, // 0, + PivotedGrid, // 1, + Gantt // 2 } export enum PaneLayout { - GridOnly, //0, - GridAndGantt, //1, - GridAndPivotedGrid //2 + GridOnly, // 0, + GridAndGantt, // 1, + GridAndPivotedGrid // 2 } export enum EditMode { - ReadOnly, //0, - ReadWrite, //1, - ReadOnlyDefer, //2, - ReadWriteDefer, //3, - Defer //4 + ReadOnly, // 0, + ReadWrite, // 1, + ReadOnlyDefer, // 2, + ReadWriteDefer, // 3, + Defer // 4 } export enum GanttDrawBarFlags { - LeftLink, //0x01, - RightLink //0x02 + LeftLink, // 0x01, + RightLink // 0x02 } export enum GanttBarDateType { - Start, //0, - End //1 + Start, // 0, + End // 1 } export enum ValidationState { - Valid, //0, - Pending, //1, - Invalid //2 + Valid, // 0, + Pending, // 1, + Invalid // 2 } export enum HierarchyMode { - None, //0, - Standard, //1, - Grouping //2 + None, // 0, + Standard, // 1, + Grouping // 2 } export enum EditActorWriteType { - Both, //1, - LocalizedOnly, //2, - DataOnly, //3, - Either //4 + Both, // 1, + LocalizedOnly, // 2, + DataOnly, // 3, + Either // 4 } export enum EditActorReadType { - Both, //1, - LocalizedOnly, //2, - DataOnly //3 + Both, // 1, + LocalizedOnly, // 2, + DataOnly // 3 } export enum EditActorUpdateType { - Committed, //0, - Uncommitted, //1 + Committed, // 0, + Uncommitted, // 1 } export enum SortMode { - Ascending, //1, - Descending, //-1, - None //0 + Ascending, // 1, + Descending, // -1, + None // 0 } export namespace RowHeaderStyleId { - export var Transfer: string; //'Transfer', - export var Conflict: string; //'Conflict' + export var Transfer: string; // 'Transfer', + export var Conflict: string; // 'Conflict' } export namespace RowHeaderAutoStyleId { - export var Dirty: string; //'Dirty', - export var Error: string; //'Error', - export var NewRow: string; //'NewRow' + export var Dirty: string; // 'Dirty', + export var Error: string; // 'Error', + export var NewRow: string; // 'NewRow' } export enum RowHeaderStatePriorities { - Dirty, //10, - Transfer, //30, - CellError, //40, - Conflict, //50, - RowError, //60, - NewRow //90 + Dirty, // 10, + Transfer, // 30, + CellError, // 40, + Conflict, // 50, + RowError, // 60, + NewRow // 90 } export enum UpdateSerializeMode { - Cancel, //0, - Default, //1, - PropDataOnly, //2, - PropLocalizedOnly, //3, - PropBoth //4 + Cancel, // 0, + Default, // 1, + PropDataOnly, // 2, + PropLocalizedOnly, // 3, + PropBoth // 4 } export enum UpdateTrackingMode { - PropData, //2, - PropLocalized, //3, - PropBoth //4 + PropData, // 2, + PropLocalized, // 3, + PropBoth // 4 } export namespace UserAction { - export var UserEdit: string; //'User Edit':string; - export var DeleteRecord: string; //'Delete Record':string; - export var InsertRecord: string; //'Insert Record':string; - export var Indent: string; //'Indent':string; - export var Outdent: string; //'Outdent':string; - export var Fill: string; //'Fill':string; - export var Paste: string; //'Paste':string; - export var CutPaste: string; //'Cut/Paste' + export var UserEdit: string; // 'User Edit':string; + export var DeleteRecord: string; // 'Delete Record':string; + export var InsertRecord: string; // 'Insert Record':string; + export var Indent: string; // 'Indent':string; + export var Outdent: string; // 'Outdent':string; + export var Fill: string; // 'Fill':string; + export var Paste: string; // 'Paste':string; + export var CutPaste: string; // 'Cut/Paste' } export enum ReadOnlyActiveState { - ReadOnlyActive, //0, - ReadOnlyDisabled, //1 + ReadOnlyActive, // 0, + ReadOnlyDisabled, // 1 } // tslint:disable-next-line: interface-name @@ -10403,15 +10403,15 @@ declare namespace SP { gridFieldMap: { [name: string]: GridField }; columns: ColumnInfoCollection; - messageOverrides: any; //TODO - operationalConstantsFieldKeyMap: any; //TODO + messageOverrides: any; // TODO + operationalConstantsFieldKeyMap: any; // TODO ganttParams: GanttParameters; pivotedGridParams: PivotedGridParameters; rowViewParams: RowViewParameters; } export class PivotedGridParameters { - //this.dateRange = null; + // this.dateRange = null; // this.ganttBarStyles = null; // this.ganttZoomLevel = 3; // this.fnRenderGanttRow = null; @@ -10883,7 +10883,7 @@ declare namespace SP { bHyperlink: boolean; DataToLocalized(dataValue: any): string; GetAddress(dataValue: any): string; - /** Returns string like this: '"http://site.com, Site title"' */ + /** Returns string like this: '"http:// site.com, Site title"' */ GetCopyValue(record: IRecord, dataValue: any, locValue: string): string; toString(): string; } @@ -10950,7 +10950,7 @@ declare namespace SP { export interface IEditControlCellContext extends IEditActorCellContext { cellWidth: number; cellHeight: number; - cellStyle: any; //TODO: Determine correct type + cellStyle: any; // TODO: Determine correct type cellRect: any; NotifyExpandControl(): void; NotifyEditComplete(): void; diff --git a/sharepoint/sharepoint-tests.ts b/sharepoint/sharepoint-tests.ts index 9d75197d89..4c028d977c 100644 --- a/sharepoint/sharepoint-tests.ts +++ b/sharepoint/sharepoint-tests.ts @@ -3,8 +3,8 @@ import * as angular from 'angular'; import * as ng from 'angular'; -//code from http://sptypescript.codeplex.com/ -//BasicTasksJSOM.ts +// code from http://sptypescript.codeplex.com/ +// BasicTasksJSOM.ts // Website tasks function retrieveWebsite(resultpanel: HTMLElement) { var clientContext = SP.ClientContext.get_current(); @@ -613,7 +613,7 @@ namespace CSR { } - //typescripttempltes.ts + // typescripttempltes.ts declare var Strings: any; export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm @@ -674,7 +674,7 @@ namespace CSR { export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; - //TODO: Handle different input types + // TODO: Handle different input types return $get(id) as HTMLInputElement; } @@ -782,7 +782,7 @@ namespace CSR { return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; - //ListSchema schma exists in Form and in View render context + // ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { for (var innerField of fields) { @@ -798,7 +798,7 @@ namespace CSR { return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; - //ListSchema schma exists in Form and in View render context + // ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { for (var innerField of fields) { @@ -821,7 +821,7 @@ namespace CSR { if (ctx.ControlMode === SPClientTemplates.ClientControlMode.View) { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { - //TODO: Disable editing in grid mode + // TODO: Disable editing in grid mode } @@ -869,7 +869,7 @@ namespace CSR { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { - //TODO: Hide item in grid mode + // TODO: Hide item in grid mode } else { ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); } @@ -1014,7 +1014,7 @@ namespace CSR { } else { var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); - //TODO: Handle lookup to another web + // TODO: Handle lookup to another web var list = web.get_lists().getById(listId); var item = list.getItemById(parseInt(value, 10)); var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); @@ -1059,7 +1059,7 @@ namespace CSR { pendingLoads++; var ctx = SP.ClientContext.get_current(); - //TODO: Handle lookup to another web + // TODO: Handle lookup to another web var web = ctx.get_web(); var listId = _schema.LookupListId; var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); @@ -1070,7 +1070,7 @@ namespace CSR { return dependencyValues[expr] ? dependencyValues[expr] : ''; }); - //TODO: Handle ShowField attribure + // TODO: Handle ShowField attribure if (predicate.substr(0, 5) === ''); @@ -1336,14 +1336,14 @@ namespace CSR { query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); var selectProps = query.get_selectProperties(); selectProps.clear(); - //TODO: Handle ShowField attribute + // TODO: Handle ShowField attribute selectProps.add('Title'); selectProps.add('ListItemId'); var executor = new Search.SearchExecutor(ctx); var result = executor.executeQuery(query); ctx.executeQueryAsync( () => { - //TODO: Discover proper way to load collection + // TODO: Discover proper way to load collection var tableCollection = new Search.ResultTableCollection(); tableCollection.initPropertiesFromJson(result.get_value()); @@ -1711,7 +1711,7 @@ if (typeof SP === 'object' && SP && typeof SP.SOD === 'object' && SP.SOD) { } -//mquery.ts +// mquery.ts @@ -1822,7 +1822,7 @@ m$.ready(() => { }); -//whoisapppart.ts +// whoisapppart.ts namespace _ { @@ -1842,7 +1842,7 @@ namespace _ { } }); - //Load the people picker + // Load the people picker function loadPeoplePicker(peoplePickerElementId: string) { var schema: ISPClientPeoplePickerSchema = { PrincipalAccountType: "User", @@ -1881,7 +1881,7 @@ namespace _ { var properties = personProperties.get_userProfileProperties(); var messageText = ""; for (var key in properties) { - if(properties.hasOwnProperty(key)) + if (properties.hasOwnProperty(key)) continue; messageText += "
[" + key + "]: \"" + properties[key] + "\""; } @@ -1916,12 +1916,12 @@ namespace _ { function prepareVisual() { if (isIframe) { - //Create a Link element for the defaultcss.ashx resource + // Create a Link element for the defaultcss.ashx resource var linkElement = document.createElement('link'); linkElement.setAttribute('rel', 'stylesheet'); linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); - //Add the linkElement as a child to the head section of the html + // Add the linkElement as a child to the head section of the html document.head.appendChild(linkElement); } else { @@ -1953,7 +1953,7 @@ namespace _ { } } -//taxonomy +// taxonomy namespace MySP { // Class @@ -2261,7 +2261,7 @@ namespace _ { }; -//publishing.ts +// publishing.ts // Variables used in various callbacks JSRequest.EnsureSetup(); @@ -2332,7 +2332,7 @@ function createPage(evt) { }); } -//likes +// likes namespace SampleReputation { interface MyList extends SPClientTemplates.RenderContext_InView { @@ -2428,7 +2428,7 @@ namespace SampleReputation { -//code from https://github.com/gandjustas/SharePointAngularTS +// code from https://github.com/gandjustas/SharePointAngularTS namespace App { "use strict"; var app = angular.module("app", []); diff --git a/sharepoint/tslint.json b/sharepoint/tslint.json index 192203ab54..e4f5db4fa0 100644 --- a/sharepoint/tslint.json +++ b/sharepoint/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" -} \ No newline at end of file + "extends": "../tslint.json", + "rules": { + "max-line-length": false + } +} diff --git a/sharp/index.d.ts b/sharp/index.d.ts new file mode 100644 index 0000000000..0776b80b81 --- /dev/null +++ b/sharp/index.d.ts @@ -0,0 +1,653 @@ +// Type definitions for sharp 0.17 +// Project: https://github.com/lovell/sharp +// Definitions by: François Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Duplex } from "stream"; + +/** + * Creates a sharp instance from an image + * @param {string} input Buffer containing JPEG, PNG, WebP, GIF, SVG, TIFF or raw pixel image data, or String containing the path to an JPEG, PNG, WebP, GIF, SVG or TIFF image file. + * @param {sharp.SharpOptions} options Object with optional attributes. + * @throws {Error} Invalid parameters + * @returns {sharp.SharpInstance} A sharp instance that can be used to chain operations + */ +declare function sharp(input?: string | Buffer, options?: sharp.SharpOptions): sharp.SharpInstance; +declare namespace sharp { + const gravity: sharp.GravityEnum; + const strategy: sharp.StrategyEnum; + /** + * Gets, or when options are provided sets, the limits of libvips' operation cache. + * Existing entries in the cache will be trimmed after any change in limits. + * This method always returns cache statistics, useful for determining how much working memory is required for a particular task. + * @param {boolean|sharp.CacheOptions} options Object with the cache options, or Boolean where true uses default cache settings and false removes all caching. + * @returns {Object} + */ + function cache(options?: boolean | sharp.CacheOptions): CacheResult; + /** + * Gets, or when a concurrency is provided sets, the number of threads libvips' should create to process each image. + * @param {number} concurrency concurrency value + */ + function concurrency(threads?: number): number; + /** + * Provides access to internal task counters. + * @returns {sharp.SharpCounters} Object containing task counters + */ + function counters(): sharp.SharpCounters; + /** + * Get and set use of SIMD vector unit instructions. + * @param {boolean} enable enable or disable use of SIMD vector unit instructions + * @returns {boolean} true if usage of SIMD vector unit instructions is enabled + */ + function simd(enable?: boolean): boolean; + const kernel: sharp.KernelEnum; + const interpolator: sharp.InterpolatorEnum; + /** + * Object containing nested boolean values representing the available input and output formats/methods. + */ + const format: FormatEnum; + /** An EventEmitter that emits a change event when a task is either queued, waiting for libuv to provide a worker thread, complete */ + const queue: NodeJS.EventEmitter; + /** An Object containing the version numbers of libvips and its dependencies. */ + const versions: string[]; + const bool: BoolEnum; + + interface SharpInstance extends Duplex { + /** + * Fast access to image metadata without decoding any compressed image data. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + metadata(callback: (err: Error, metadata: Metadata) => void): SharpInstance; + /** + * Fast access to image metadata without decoding any compressed image data. + * @returns {Promise} A promise that fulfills with a metadata object. + */ + metadata(): Promise; + /** + * Take a "snapshot" of the Sharp instance, returning a new instance. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + clone(): SharpInstance; + /** + * An advanced setting that switches the libvips access method to VIPS_ACCESS_SEQUENTIAL. + * @param {boolean} sequentialRead true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + sequentialRead(sequentialRead?: boolean): SharpInstance; + /** + * Do not process input images where the number of pixels (width _ height) exceeds this limit. + * @param {number|boolean} pixels An integral Number of pixels, zero or false to remove limit, true to use default limit. + * @throws {Error} Invalid limit + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + limitInputPixels(pixels: number | boolean): SharpInstance; + /** + * Resize image to width x height. By default, the resized image is centre cropped to the exact size specified. + * @param {number} width pixels wide the resultant image should be, between 1 and 16383 (0x3FFF). Use null or undefined to auto-scale the width to match the height. + * @param {number} height pixels high the resultant image should be, between 1 and 16383. Use null or undefined to auto-scale the height to match the width. + * @param {ResizeOptions} options resize options + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + resize(width?: number, height?: number, options?: ResizeOptions): SharpInstance; + /** + * Crop the resized image to the exact size specified, the default behaviour. + * @param {number|string} crop A member of sharp.gravity to crop to an edge/corner or sharp.strategy to crop dynamically. (optional, default 'centre') + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + crop(crop?: number | string): SharpInstance; + /** + * Preserving aspect ratio, resize the image to the maximum width or height specified then embed on a background of the exact width and height specified. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + embed(): SharpInstance; + /** + * Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to the width and height specified. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + max(): SharpInstance; + /** + * Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to the width and height specified. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + min(): SharpInstance; + /** + * Do not enlarge the output image if the input image width or height are already less than the required dimensions. + * @param {boolean} withoutEnlargement true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + withoutEnlargement(withoutEnlargement?: boolean): SharpInstance; + /** + * Ignoring the aspect ratio of the input, stretch the image to the exact width and/or height provided via resize. + */ + ignoreAspectRatio(): SharpInstance; + /** + * Extract a region of the image. + * @param {Region} region Region to extract + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + extract(region: Region): SharpInstance; + /** + * Trim "boring" pixels from all edges that contain values within a percentage similarity of the top-left pixel. + * @param {number} tolerance value between 1 and 99 representing the percentage similarity. (optional, default 10) + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + trim(tolerance?: number): SharpInstance; + /** + * Set the background for the embed, flatten and extend operations. The default background is {r: 0, g: 0, b: 0, alpha: 1}, black without transparency. + * @param {RGBA|string} rgba String or Object parsed by the color module to extract values for red, green, blue and alpha. + * @throws {Error} Invalid parameter + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + background(rgba?: RGBA | string): SharpInstance; // Wait for typings to fetch latest color typings from DT + /** + * Merge alpha transparency channel, if any, with background. + * @param {boolean} flatten true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + flatten(flatten?: boolean): SharpInstance; + /** + * Extends/pads the edges of the image with the colour provided to the background method. + * @param {number|ExtendOptions} extend single pixel count to add to all edges or an Object with per-edge counts + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + extend(extend: number | ExtendOptions): SharpInstance; + /** + * Produce the "negative" of the image. + * @param {boolean} negate true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + negate(negate?: boolean): SharpInstance; + /** + * Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag. + * @param {number} angle 0, 90, 180 or 270. (optional, default auto) + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + rotate(angle?: number): SharpInstance; + /** + * Flip the image about the vertical Y axis. + * @param {boolean} flip true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + flip(flip?: boolean): SharpInstance; + /** + * Flop the image about the horizontal X axis. + * @param {boolean} flop true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + flop(flop?: boolean): SharpInstance; + /** + * Blur the image. + * @param {number} sigma a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where sigma = 1 + radius / 2. + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + blur(sigma?: number): SharpInstance; + /** + * Convolve the image with the specified kernel. + * @param {Kernel} kernel the specified kernel + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + convolve(kernel: Kernel): SharpInstance; + /** + * Sharpen the image. + * @param {number} sigma the sigma of the Gaussian mask, where sigma = 1 + radius / 2. + * @param {number} flat the level of sharpening to apply to "flat" areas. (optional, default 1.0) + * @param {number} jagged the level of sharpening to apply to "jagged" areas. (optional, default 2.0) + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + sharpen(sigma?: number, flat?: number, jagged?: number): SharpInstance; + /** + * Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0. + * @param {number} threshold a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default 128) + * @param {ThresholdOptions} options threshold options + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + threshold(threshold?: number, options?: ThresholdOptions): SharpInstance; + /** + * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma. + * @param {number} gamma value between 1.0 and 3.0. (optional, default 2.2) + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + gamma(gamma?: number): SharpInstance; + /** + * Alternative spelling of greyscale. + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. + * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) color channels. + * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. + * An alpha channel may be present, and will be unchanged by the operation. + * @param {boolean} grayscale true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + grayscale(grayscale?: boolean): SharpInstance; + /** + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. + * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) color channels. + * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. + * An alpha channel may be present, and will be unchanged by the operation. + * @param {boolean} greyscale true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + greyscale(greyscale?: boolean): SharpInstance; + /** + * Enhance output image contrast by stretching its luminance to cover the full dynamic range. + * @param {boolean} normalize true to enable and false to disable (defaults to true) + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + normalize(normalize?: boolean): SharpInstance; + /** + * Alternative spelling of normalise. + * Enhance output image contrast by stretching its luminance to cover the full dynamic range. + * @param {boolean} normalise true to enable and false to disable (defaults to true) + */ + normalise(normalise?: boolean): SharpInstance; + /** + * Overlay (composite) an image over the processed (resized, extracted etc.) image. + * @param {string|Buffer} image Buffer containing image data or String containing the path to an image file. + * @param {OverlayOptions} options overlay options + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + overlayWith(image: string | Buffer, options?: OverlayOptions): SharpInstance; + /** + * Set the output colourspace. + * @param {string} colourspace output colourspace e.g. srgb, rgb, cmyk, lab, b-w ... + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + toColourspace(colourspace?: string): SharpInstance; + /** + * Alternative spelling of toColourspace. + * Set the output colorspace. + * @param {string} colorspace output colourspace e.g. srgb, rgb, cmyk, lab, b-w ... + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + toColorspace(colorspace: string): SharpInstance; + /** + * Extract a single channel from a multi-channel image. + * @param {number|string} channel zero-indexed band number to extract, or red, green or blue as alternative to 0, 1 or 2 respectively. + * @throws {Error} Invalid channel + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + extractChannel(channel: number | string): SharpInstance; + /** + * Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace(). + * @param {string|string[]|Buffer|Buffer[]} channels one or more images (file paths, Buffers). + * @param {{raw:Raw}} options image options + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + joinChannel(channels: string | string[] | Buffer | Buffer[], options?: { raw: Raw }): SharpInstance; + /** + * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. + * @param {string} boolOp one of and, or or eor to perform that bitwise operation, like the C logic operators &, | and ^ respectively. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + bandbool(boolOp: string): SharpInstance; + /** + * Perform a bitwise boolean operation with operand image. + * @param {string|Buffer} image Buffer containing image data or String containing the path to an image file. + * @param {strip} operator one of and, or or eor to perform that bitwise operation, like the C logic operators &, | and ^ respectively. + * @param {{raw:Raw}} options describes operand when using raw pixel data. + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + boolean(operand: string | Buffer, operator: string, options?: { raw: Raw }): SharpInstance; + /** + * Write output image data to a file. + * @param {string} fileOut The path to write the image data to. + * @param {Function} callback Callback function called on completion with two arguments (err, info). info contains the output image format, size (bytes), width, height and channels. + * @throws {Error} Invalid parameters + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + toFile(fileOut: string, callback: (err: Error, info: OutputInfo) => void): SharpInstance; + /** + * Write output image data to a file. + * @param {string} fileOut The path to write the image data to. + * @throws {Error} Invalid parameters + * @returns {Promise} A promise that fulfills with an object containing informations on the resulting file + */ + toFile(fileOut: string): Promise; + /** + * Write output to a Buffer. JPEG, PNG, WebP, and RAW output are supported. By default, the format will match the input image, except GIF and SVG input which become PNG output. + * @param {Function} callback Callback function called on completion with three arguments (err, buffer, info). + * err is an error message, if any. + * buffer is the output image data. + * info contains the output image format, size (bytes), width, height and channels. + * A Promises/A+ promise is returned when callback is not provided. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): SharpInstance; + /** + * Write output to a Buffer. JPEG, PNG, WebP, and RAW output are supported. By default, the format will match the input image, except GIF and SVG input which become PNG output. + * @returns {Promise} A promise that fulfills with the resulting Buffer + */ + toBuffer(): Promise; + /** + * Use these JPEG options for output image. + * @param {JpegOptions} options Output options. + * @throws {Error} Invalid options + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + jpeg(options?: JpegOptions): SharpInstance; + /** + * Use these PNG options for output image. + * @param {PngOptions} options Output options. + * @throws {Error} Invalid options + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + png(options?: PngOptions): SharpInstance; + /** + * Use these WebP options for output image. + * @param {OutputOptions} options Output options. + * @throws {Error} Invalid options + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + webp(options?: OutputOptions): SharpInstance; + /** + * Use these TIFF options for output image. + * @param {OutputOptions} options Output options. + * @throws {Error} Invalid options + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + tiff(options?: OutputOptions): SharpInstance; + /** + * Force output to be raw, uncompressed uint8 pixel data. + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + raw(): SharpInstance; + /** + * Force output to a given format. + * @param {string|AvailableFormatInfo} format a String or an Object with an 'id' attribute + * @param {OutputOptions|JpegOptions|PngOptions} options output options + * @throws {Error} Unsupported format or options + * @returns {SharpInstance} A sharp instance that can be used to chain operations + */ + toFormat(format: string | AvailableFormatInfo, options?: OutputOptions | JpegOptions | PngOptions): SharpInstance; + /** + * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. + * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space. + * This will also convert to and add a web-friendly sRGB ICC profile. + * @param {Metadata} + * @throws {Error} Invalid parameters. + */ + withMetadata(metadata?: Metadata): SharpInstance; + /** + * Use tile-based deep zoom (image pyramid) output. Set the format and options for tile images via the toFormat, jpeg, png or webp functions. + * Use a .zip or .szi file extension with toFile to write to a compressed archive file format. + * @param {TileOptions} options options + */ + tile(options: TileOptions): SharpInstance; + } + + interface SharpOptions { + /** integral number representing the DPI for vector images. */ + density?: number; + /** describes raw pixel image data. */ + raw?: Raw; + } + + interface CacheOptions { + /** is the maximum memory in MB to use for this cache */ + memory?: number; + /** is the maximum number of files to hold open */ + files?: number; + /** is the maximum number of operations to cache */ + items?: number; + } + + interface SharpCounters { + queue: number; + process: number; + } + + interface Raw { + width: number; + height: number; + channels: number; + } + + interface Metadata { + /** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */ + format?: string; + /** Number of pixels wide */ + width?: number; + /** Number of pixels high */ + height?: number; + /** Name of colour space interpretation e.g. srgb, rgb, cmyk, lab, b-w ... */ + space?: string; + /** Number of bands e.g. 3 for sRGB, 4 for CMYK */ + channels?: number; + /** Number of pixels per inch (DPI), if present */ + density?: number; + /** Boolean indicating the presence of an embedded ICC profile */ + hasProfile?: boolean; + /** Boolean indicating the presence of an alpha transparency channel */ + hasAlpha?: boolean; + /** Number value of the EXIF Orientation header, if present */ + orientation?: number; + /** Buffer containing raw EXIF data, if present */ + exif?: Buffer; + /** Buffer containing raw ICC profile data, if present */ + icc?: Buffer; + } + + interface JpegOptions extends OutputOptions { + /** Use progressive (interlace) scan (optional, default false) */ + progressive?: boolean; + /** Set to '4:4:4' to prevent chroma subsampling when quality <= 90 (optional, default '4:2:0') */ + chromaSubsampling?: string; + /** Apply trellis quantisation, requires mozjpeg (optional, default false) */ + trellisQuantisation?: boolean; + /** Apply overshoot deringing, requires mozjpeg (optional, default false) */ + overshootDeringing?: boolean; + /** Optimise progressive scans, forces progressive, requires mozjpeg (optional, default false) */ + optimiseScans?: boolean; + /** Alternative spelling of optimiseScans (optional, default false) */ + optimizeScans?: boolean; + } + + interface PngOptions { + /** Use progressive (interlace) scan (optional, default false) */ + progressive?: boolean; + /** zlib compression level (optional, default 6) */ + compressionLevel?: number; + /** Use adaptive row filtering (optional, default true) */ + adaptiveFiltering?: boolean; + /** Force PNG output, otherwise attempt to use input format (optional, default true) */ + force?: boolean; + } + + interface OutputOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number; + /** Force format output, otherwise attempt to use input format (optional, default true) */ + force?: boolean; + } + + interface ResizeOptions { + /** the kernel to use for image reduction. (optional, default 'lanczos3') */ + kernel?: string; + /** the interpolator to use for image enlargement. (optional, default 'bicubic') */ + interpolator?: string; + /** use magick centre sampling convention instead of corner sampling. (optional, default false) */ + centreSampling?: boolean; + /** alternative spelling of centreSampling. (optional, default false) */ + centerSampling?: boolean; + } + + interface Region { + /** zero-indexed offset from left edge */ + left?: number; + /** zero-indexed offset from top edge */ + top?: number; + /** dimension of extracted image */ + width?: number; + /** dimension of extracted image */ + height?: number; + } + + interface ExtendOptions { + top?: number; + left?: number; + bottom?: number; + right?: number; + } + + interface RGBA { + r?: number; + g?: number; + b?: number; + alpha?: number; + } + + interface Kernel { + /** width of the kernel in pixels. */ + width: number; + /** height of the kernel in pixels. */ + height: number; + /** Array of length width*height containing the kernel values. */ + kernel: number[]; + /** the scale of the kernel in pixels. (optional, default sum) */ + scale?: number; + /** the offset of the kernel in pixels. (optional, default 0) */ + offset?: number; + } + + interface ThresholdOptions { + /** convert to single channel greyscale. (optional, default true) */ + greyscale?: boolean; + /** alternative spelling for greyscale. (optional, default true) */ + grayscale?: boolean; + } + + interface OverlayOptions { + /** gravity at which to place the overlay. (optional, default 'centre') */ + gravity?: number; + /** the pixel offset from the top edge. */ + top?: number; + /** the pixel offset from the left edge. */ + left?: number; + /** set to true to repeat the overlay image across the entire image with the given gravity. (optional, default false) */ + tile?: boolean; + /** set to true to apply only the alpha channel of the overlay image to the input image, giving the appearance of one image being cut out of another. (optional, default false) */ + cutout?: boolean; + /** describes overlay when using raw pixel data. */ + raw?: Raw; + } + + interface TileOptions { + /** Tile size in pixels, a value between 1 and 8192. (optional, default 256) */ + size?: number; + /** Tile overlap in pixels, a value between 0 and 8192. (optional, default 0) */ + overlap?: number; + /** Tile container, with value fs (filesystem) or zip (compressed file). (optional, default 'fs') */ + container?: string; + /** Filesystem layout, possible values are dz, zoomify or google. (optional, default 'dz') */ + layout?: string; + } + + interface OutputInfo { + format: string; + size: number; + width: number; + height: number; + channels: number; + } + + interface AvailableFormatInfo { + id: string; + input: { file: boolean; buffer: boolean; stream: boolean; }; + output: { file: boolean; buffer: boolean; stream: boolean; }; + } + + interface KernelEnum { + cubic: string; + lanczos2: string; + lanczos3: string; + } + + interface InterpolatorEnum { + nearest: string; + bilinear: string; + bicubic: string; + nohalo: string; + lbb: string; + locallyBoundedBicubic: string; + vsqbs: string; + vertexSplitQuadraticBasisSpline: string; + } + + interface BoolEnum { + and: string; + or: string; + eor: string; + } + + interface ColourspaceEnum { + multiband: string; + "b-w": string; + bw: string; + cmyk: string; + srgb: string; + } + + interface GravityEnum { + north: number; + northeast: number; + southeast: number; + south: number; + southwest: number; + west: number; + northwest: number; + east: number; + center: number; + centre: number; + } + + interface StrategyEnum { + entropy: number; + attention: number; + } + + interface FormatEnum { + jpeg: AvailableFormatInfo; + png: AvailableFormatInfo; + webp: AvailableFormatInfo; + raw: AvailableFormatInfo; + tiff: AvailableFormatInfo; + dz: AvailableFormatInfo; + input: AvailableFormatInfo; + magick: AvailableFormatInfo; + openslide: AvailableFormatInfo; + ppm: AvailableFormatInfo; + fits: AvailableFormatInfo; + gif: AvailableFormatInfo; + svg: AvailableFormatInfo; + pdf: AvailableFormatInfo; + v: AvailableFormatInfo; + } + + interface CacheResult { + memory: { current: number; high: number; max: number; }; + files: { current: number; max: number; }; + items: { current: number; max: number; }; + } +} + +export = sharp; diff --git a/sharp/sharp-tests.ts b/sharp/sharp-tests.ts new file mode 100644 index 0000000000..2ca348620a --- /dev/null +++ b/sharp/sharp-tests.ts @@ -0,0 +1,202 @@ +import * as sharp from "sharp"; +import { createReadStream, createWriteStream } from "fs"; + +// Test samples taken from the official documentation + +const input: Buffer = new Buffer(0); +const readableStream: NodeJS.ReadableStream = createReadStream(input); +const writableStream: NodeJS.WritableStream = createWriteStream(input); + +sharp(input) + .extractChannel('green') + .toFile('input_green.jpg', (err, info) => { + // info.channels === 1 + // input_green.jpg contains the green channel of the input image + }); + +sharp('3-channel-rgb-input.png') + .bandbool(sharp.bool.and) + .toFile('1-channel-output.png', (err, info) => { + // The output will be a single channel image where each pixel `P = R & G & B`. + // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]` + // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`. + }); + +sharp('input.png') + .rotate(180) + .resize(300) + .flatten() + .background('#ff6600') + .overlayWith('overlay.png', { gravity: sharp.gravity.southeast }) + .sharpen() + .withMetadata() + .webp({ + quality: 90 + }) + .toBuffer() + .then((outputBuffer: Buffer) => { + // outputBuffer contains upside down, 300px wide, alpha channel flattened + // onto orange background, composited with overlay.png with SE gravity, + // sharpened, with metadata, 90% quality WebP image data. Phew! + }); + +sharp('input.jpg') + .resize(300, 200) + .toFile('output.jpg', (err: Error) => { + // output.jpg is a 300 pixels wide and 200 pixels high image + // containing a scaled and cropped version of input.jpg + }); + +var transformer = sharp() + .resize(300) + .on('info', (info: sharp.OutputInfo) => { + console.log('Image height is ' + info.height); + }); +readableStream.pipe(transformer).pipe(writableStream); + +console.log(sharp.format); +console.log(sharp.versions); + +sharp.queue.on('change', (queueLength: number) => { + console.log('Queue contains ' + queueLength + ' task(s)'); +}); + +let pipeline: sharp.SharpInstance = sharp().rotate(); +pipeline.clone().resize(800, 600).pipe(writableStream); +pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(writableStream); +readableStream.pipe(pipeline); +// firstWritableStream receives auto-rotated, resized readableStream +// secondWritableStream receives auto-rotated, extracted region of readableStream + +const image: sharp.SharpInstance = sharp(input); +image + .metadata() + .then((metadata: sharp.Metadata) => { + if (metadata.width) { + return image + .resize(Math.round(metadata.width / 2)) + .webp() + .toBuffer(); + } + }) + .then((data: Buffer) => { + // data contains a WebP image half the width and height of the original JPEG + }); + +pipeline = sharp() + .rotate() + .resize(undefined, 200) + .toBuffer((err: Error, outputBuffer: Buffer, info: sharp.OutputInfo) => { + // outputBuffer contains 200px high JPEG image data, + // auto-rotated using EXIF Orientation tag + // info.width and info.height contain the dimensions of the resized image + }); +readableStream.pipe(pipeline); + +sharp(input) + .extract({ left: 0, top: 0, width: 100, height: 100 }) + .toFile("output", (err: Error) => { + // Extract a region of the input image, saving in the same format. + }); + +sharp(input) + .extract({ left: 0, top: 0, width: 100, height: 100 }) + .resize(200, 200) + .extract({ left: 0, top: 0, width: 100, height: 100 }) + .toFile("output", (err: Error) => { + // Extract a region, resize, then extract from the resized image + }); + +// Resize to 140 pixels wide, then add 10 transparent pixels +// to the top, left and right edges and 20 to the bottom edge +sharp(input) + .resize(140) + .background({ r: 0, g: 0, b: 0, alpha: 0 }) + .extend({ top: 10, bottom: 20, left: 10, right: 10 }); + +sharp(input) + .convolve({ + width: 3, + height: 3, + kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] + }) + .raw() + .toBuffer((err: Error, data: Buffer, info: sharp.OutputInfo) => { + // data contains the raw pixel data representing the convolution + // of the input image with the horizontal Sobel operator + }); + +sharp('input.tiff') + .png() + .tile({ + size: 512 + }) + .toFile('output.dz', (err: Error, info: sharp.OutputInfo) => { + // output.dzi is the Deep Zoom XML definition + // output_files contains 512x512 tiles grouped by zoom level + }); + +sharp(input) + .resize(200, 300, { + kernel: sharp.kernel.lanczos2, + interpolator: sharp.interpolator.nohalo + }) + .background('white') + .embed() + .toFile('output.tiff') + .then(() => { + // output.tiff is a 200 pixels wide and 300 pixels high image + // containing a lanczos2/nohalo scaled version, embedded on a white canvas, + // of the image data in inputBuffer + }); + +transformer = sharp() + .resize(200, 200) + .crop(sharp.strategy.entropy) + .on('error', (err: Error) => { + console.log(err); + }); +// Read image data from readableStream +// Write 200px square auto-cropped image data to writableStream +readableStream.pipe(transformer).pipe(writableStream); + +sharp('input.gif') + .resize(200, 300) + .background({ r: 0, g: 0, b: 0, alpha: 0 }) + .embed() + .toFormat(sharp.format.webp) + .toBuffer((err: Error, outputBuffer: Buffer) => { + if (err) { + throw err; + } + // outputBuffer contains WebP image data of a 200 pixels wide and 300 pixels high + // containing a scaled version, embedded on a transparent canvas, of input.gif + }); + +sharp(input) + .resize(200, 200) + .max() + .toFormat('jpeg') + .toBuffer() + .then((outputBuffer: Buffer) => { + // outputBuffer contains JPEG image data no wider than 200 pixels and no higher + // than 200 pixels regardless of the inputBuffer image dimensions + }); + +const stats = sharp.cache(); + +sharp.cache({ items: 200 }); +sharp.cache({ files: 0 }); +sharp.cache(false); + +const threads = sharp.concurrency(); // 4 +sharp.concurrency(2); // 2 +sharp.concurrency(0); // 4 + +const counters = sharp.counters(); // { queue: 2, process: 4 } + +let simd: boolean = sharp.simd(); +// simd is `true` if SIMD is currently enabled + +simd = sharp.simd(true); +// attempts to enable the use of SIMD, returning true if available diff --git a/sharp/tsconfig.json b/sharp/tsconfig.json new file mode 100644 index 0000000000..eafee068c7 --- /dev/null +++ b/sharp/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", + "sharp-tests.ts" + ] +} \ No newline at end of file diff --git a/sharp/tslint.json b/sharp/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/sharp/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/sheetify/sheetify-tests.ts b/sheetify/sheetify-tests.ts index 7287ba1499..931e05b579 100644 --- a/sheetify/sheetify-tests.ts +++ b/sheetify/sheetify-tests.ts @@ -1,8 +1,8 @@ import * as sheetify from 'sheetify'; -function done1 (err: Error, css: string, prefix: string) {}; -function done2 (err: Error, css: string) {}; -function done3 (err: Error) {}; +function done1(err: Error, css: string, prefix: string) {}; +function done2(err: Error, css: string) {}; +function done3(err: Error) {}; const test1 = sheetify('foobar'); const test2 = sheetify('foobar', {global: true}); @@ -15,6 +15,6 @@ const test8 = sheetify` .test { border: 1px soild black; } -` +`; const prefix = sheetify.getPrefix('boop'); \ No newline at end of file diff --git a/shelljs/index.d.ts b/shelljs/index.d.ts index 26f92c379f..a8f2196dab 100644 --- a/shelljs/index.d.ts +++ b/shelljs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ShellJS v0.3.0 +// Type definitions for ShellJS v0.7.6 // Project: http://shelljs.org // Definitions by: Niklas Mollenhauer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -463,17 +463,18 @@ export declare function exec(command: string, options: ExecOptions, callback: Ex export declare function exec(command: string, callback: ExecCallback): child.ChildProcess; export interface ExecCallback { - (code: number, output: string, error?: string): any; + (code: number, stdout: string, stderr: string): any; } -export interface ExecOptions { +export interface ExecOptions extends child.ExecOptions { silent?: boolean; async?: boolean; } export interface ExecOutputReturnValue { code: number; - output: string; + stdout: string; + stderr: string; } /** diff --git a/shelljs/shelljs-tests.ts b/shelljs/shelljs-tests.ts index 7934046d0a..6c155e5aee 100644 --- a/shelljs/shelljs-tests.ts +++ b/shelljs/shelljs-tests.ts @@ -86,22 +86,22 @@ var testPath = shell.env["path"]; import child = require("child_process"); -var version = shell.exec("node --version").output; +var version = shell.exec("node --version").stdout; var version2 = shell.exec("node --version", { async: false }); -var output = version2.output; +var output = version2.stdout; var asyncVersion3 = shell.exec("node --version", { async: true }); var pid = asyncVersion3.pid; -shell.exec("node --version", { silent: true }, function (code, output) { - var version = output; +shell.exec("node --version", { silent: true }, function (code, stdout, stderr) { + var version = stdout; }); -shell.exec("node --version", { silent: true, async: true }, function (code, output) { - var version = output; +shell.exec("node --version", { silent: true, async: true, cwd: '/usr/local/bin' }, function (code, stdout, stderr) { + var version = stdout; }); -shell.exec("node --version", function (code, output) { - var version = output; +shell.exec("node --version", function (code, stdout, stderr) { + var version = stdout; }); shell.exec("node --version", function (code: number) { var num: number = code; diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts new file mode 100644 index 0000000000..aec379f5f2 --- /dev/null +++ b/shipit-utils/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for shipit-utils 1.4 +// Project: https://github.com/shipitjs/shipit-utils +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import shipit = require("shipit"); + +type GruntOrShipit = typeof shipit | {}; +type EmptyCallback = () => void; + +export function equalValues(value: any[]): void; +export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; +export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; +export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependenciesOrTask: string[] | EmptyCallback): typeof shipit; +export function runTask(gruntOrShipit: {}): void; diff --git a/shipit-utils/shipit-utils-tests.ts b/shipit-utils/shipit-utils-tests.ts new file mode 100644 index 0000000000..81cb741054 --- /dev/null +++ b/shipit-utils/shipit-utils-tests.ts @@ -0,0 +1,11 @@ +import shipit = require("shipit"); +import utils = require("shipit-utils"); + +var originalShipit = utils.getShipit(shipit); + +var task = () => { + return shipit.local("sleep 10s"); +}; + +utils.registerTask(originalShipit, "myTask", task); +utils.registerTask(originalShipit, "myTask", ["some", "other", "tasks"]); diff --git a/shipit-utils/tsconfig.json b/shipit-utils/tsconfig.json new file mode 100644 index 0000000000..d2fdb45d17 --- /dev/null +++ b/shipit-utils/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", + "shipit-utils-tests.ts" + ] +} diff --git a/shipit-utils/tslint.json b/shipit-utils/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit-utils/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/shipit/index.d.ts b/shipit/index.d.ts new file mode 100644 index 0000000000..187b8c1f7d --- /dev/null +++ b/shipit/index.d.ts @@ -0,0 +1,60 @@ +// Type definitions for shipit-cli 1.5 +// Project: https://github.com/shipitjs/shipit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as fs from "fs"; +import * as child_process from "child_process"; +import * as shipit from "./index"; // Used for `typeof shipit` + +type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; +type EmptyCallback = () => void; +type TaskExecution = (name: string, depsOrFn: string[] | EmptyCallback, fn: () => void) => any; + +interface Options { + environment: string; + stderr: fs.WriteStream; + stdout: fs.WriteStream; +} + +interface ShipitLocal { + child: child_process.ChildProcess; + stderr: fs.WriteStream; + stdout: fs.WriteStream; +} + +interface Tasks { + [name: string]: Task; +} + +interface Task { + blocking: boolean; + dep: string[]; + fn: () => void; + name: string; +} + +export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; +export function emit(name: string): any; +export function initConfig(config: {}): typeof shipit; +export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function log(log: any): void; +export function log(...log: any[]): void; +export function on(name: string, callback: (e: any) => void): any; +export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function start(tasks: string | string[]): typeof shipit; +export function start(...tasks: string[]): typeof shipit; +export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; + +export var config: {}; +export var domain: any; +export var doneCallback: any; +export var environment: string; +export var seq: any[]; +export var tasks: Tasks; +export var isRunning: boolean; + +export as namespace shipit; diff --git a/shipit/shipit-tests.ts b/shipit/shipit-tests.ts new file mode 100644 index 0000000000..a256f87e07 --- /dev/null +++ b/shipit/shipit-tests.ts @@ -0,0 +1,50 @@ +import shipit = require("shipit"); + +shipit.initConfig({ + default: { + workspace: "/tmp/github-monitor", + deployTo: "/tmp/deploy_to", + repositoryUrl: "https://github.com/user/repo.git", + ignores: [".git", "node_modules"], + rsync: ["--del"], + keepReleases: 2, + key: "/path/to/key", + shallowClone: true + }, + staging: { + servers: "user@myserver.com" + } +}); + +shipit.task("build", () => { + shipit.emit("built"); +}); + +shipit.on("built", () => { + shipit.start("start-server"); +}); + +shipit.task("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.blTask("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.start("task"); +shipit.start("task1", "task2"); +shipit.start(["task1", "task2"]); + +shipit.local("ls -lah", {cwd: "/tmp/deploy/workspace"}).then((res: any) => { + console.log(res.stdout); + console.log(res.stderr); +}); + +shipit.remote("ls -lah").then((res: any) => { + console.log(res[0].stdout); + console.log(res[0].stderr); +}); + +shipit.remoteCopy("/tmp/workspace", "/opt/web/myapp").then(() => {}); +shipit.log("hello %s", "world"); diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json new file mode 100644 index 0000000000..17049e7271 --- /dev/null +++ b/shipit/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", + "shipit-tests.ts" + ] +} diff --git a/shipit/tslint.json b/shipit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/siema/tslint.json b/siema/tslint.json index f9e30021f4..377cc837d4 100644 --- a/siema/tslint.json +++ b/siema/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/simple-oauth2/simple-oauth2-tests.ts b/simple-oauth2/simple-oauth2-tests.ts index 290ac6fc31..7a47078a71 100644 --- a/simple-oauth2/simple-oauth2-tests.ts +++ b/simple-oauth2/simple-oauth2-tests.ts @@ -13,13 +13,13 @@ const credentials = { }; // Initialize the OAuth2 Library -//const oauth2 = require('simple-oauth2').create(credentials); +// const oauth2 = require('simple-oauth2').create(credentials); import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); // #Authorization Code flow -(function () { +(() => { // Authorization oauth2 URI const authorizationUri = oauth2.authorizationCode.authorizeURL({ @@ -29,7 +29,7 @@ const oauth2 = oauth2lib.create(credentials); }); // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) - //res.redirect(authorizationUri); + // res.redirect(authorizationUri); // Get the access token object (the authorization code is given from the previous step). const tokenConfig = { @@ -60,7 +60,7 @@ const oauth2 = oauth2lib.create(credentials); // #Client Credentials Flow -(function () { +(() => { const tokenConfig = {}; // Callbacks @@ -88,12 +88,12 @@ const oauth2 = oauth2lib.create(credentials); // #Access Token object -(function () { +(() => { // Sample of a JSON access token (you got it through previous steps) const tokenObject = { - 'access_token': '', - 'refresh_token': '', - 'expires_in': '7200' + access_token: '', + refresh_token: '', + expires_in: '7200' }; // Create the access token wrapper @@ -104,7 +104,7 @@ const oauth2 = oauth2lib.create(credentials); // Callbacks token.refresh((error, result) => { token = result; - }) + }); // Promises token.refresh() diff --git a/simple-peer/tslint.json b/simple-peer/tslint.json index ec365f164b..377cc837d4 100644 --- a/simple-peer/tslint.json +++ b/simple-peer/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/simplemde/index.d.ts b/simplemde/index.d.ts index 6c199f48a7..c78d4fb408 100644 --- a/simplemde/index.d.ts +++ b/simplemde/index.d.ts @@ -127,4 +127,7 @@ declare class SimpleMDE { static toggleFullScreen: (editor: SimpleMDE) => void; static undo: (editor: SimpleMDE) => void; static redo: (editor: SimpleMDE) => void; -} \ No newline at end of file +} + +export = SimpleMDE; +export as namespace SimpleMDE; diff --git a/sinon/index.d.ts b/sinon/index.d.ts index 966c7229d0..7c44ab9d7a 100644 --- a/sinon/index.d.ts +++ b/sinon/index.d.ts @@ -109,6 +109,7 @@ declare namespace Sinon { callsArgOnAsync(index: number, context: any): SinonStub; callsArgWithAsync(index: number, ...args: any[]): SinonStub; callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; + callsFake(func: (...args: any[]) => void): SinonStub; onCall(n: number): SinonStub; onFirstCall(): SinonStub; onSecondCall(): SinonStub; diff --git a/sip.js/index.d.ts b/sip.js/index.d.ts new file mode 100644 index 0000000000..d4e6bcebf1 --- /dev/null +++ b/sip.js/index.d.ts @@ -0,0 +1,335 @@ +// Type definitions for sip.js 0.7 +// Project: http://sipjs.com +// Definitions by: Kir Dergachev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare interface SIP { + UA: { + new (configuration?: sipjs.ConfigurationParameters): sipjs.UA; + }; + URI: { + new (scheme?: string, user?: string, host?: string, port?: number, parameters?: string[], headers?: string[]): sipjs.URI; + parse(uri: string): sipjs.URI; + }; + NameAddrHeader: { + new (uri: string | sipjs.URI, displayName: string, parameters: Array<{ key: string, value: string }>): sipjs.NameAddrHeader; + parse(name_addr_header: string): sipjs.NameAddrHeader; + }; +} + +declare namespace sipjs { + + interface URI { + scheme?: string; + user?: string; + host?: string; + port?: number; + + setParam(key: string, value?: string): void; + getParam(key: string): string; + hasParam(key: string): string; + deleteParam(key: string): string; + clearParams(): void; + setHeader(name: string, value: string): void; + getHeader(name: string): string[]; + hasHeader(name: string): boolean; + deleteHeader(name: string): string[]; + clearHeaders(): void; + clone(): URI; + toString(): string; + } + + namespace UA.EventArgs { + interface ConnectedArgs { attempts: number; } + interface UnregisteredArgs { response: string; cause: string; } + interface RegistrationFailedArgs extends UnregisteredArgs { } + } + + interface UA { + start(): void; + stop(): void; + register(options?: ExtraHeadersOptions): UA; + unregister(options?: UnregisterOptions): void; + isRegistered(): boolean; + isConnected(): boolean; + message(target: string | URI, body: string, options?: MessageOptions): Message; + subscribe(target: string | URI, event: string, options?: SubscribeOptions): Subscription; + invite(target: string | URI, element?: InviteOptions | HTMLAudioElement | HTMLVideoElement): Session; + request(method: string, target: string | URI, options?: RequestOptions): ClientContext; + + on(name: 'connected', callback: (args: UA.EventArgs.ConnectedArgs) => void): void; + on(name: 'disconnected' | 'registered' | string, callback: () => void): void; + on(name: 'unregistered', callback: (args: UA.EventArgs.UnregisteredArgs) => void): void; + on(name: 'registrationFailed', callback: (args: UA.EventArgs.RegistrationFailedArgs) => void): void; + on(name: 'invite', callback: (session: Session) => void): void; + on(name: 'message', callback: (message: Message) => void): void; + } + + namespace UA.C { + class supported { + REQUIRED: string; + SUPPORTED: string; + UNSUPPORTED: string; + } + + class causes { + INVALID_TARGET: string; + CONNECTION_ERROR: string; + REQUEST_TIMEOUT: string; + SIP_FAILURE_CODE: string; + } + } + + interface Session { + startTime?: Date; + endTime?: Date; + ua?: UA; + method?: string; + mediaHandler?: WebRTC.MediaHandler; + request?: IncomingRequest | OutgoingRequest; + localIdentity?: NameAddrHeader; + remoteIdentity?: NameAddrHeader; + data: ClientContext | ServerContext; + + dtmf(tone: string | number, options?: Session.DtmfOptions): Session; + terminate(options?: Session.CommonOptions): Session; + bye(options?: Session.CommonOptions): Session; + getLocalStreams(): any[]; + getRemoteStreams(): any[]; + refer(target: string | Session, options?: ExtraHeadersOptions): Session; + mute(options?: ExtraHeadersOptions): void; + unmute(options?: ExtraHeadersOptions): void; + cancel(options?: Session.CommonOptions): void; + progress(options?: Session.ProgressOptions): void; + accept(options?: Session.AcceptOptions): void; + reject(options?: Session.CommonOptions): void; + reply(options?: Session.CommonOptions): void; + followRefer(callback: () => void): void; + + on(name: 'progress', callback: (response: IncomingResponse) => void): void; + on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; + on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; + on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; + on(name: 'cancel' | string, callback: () => void): void; + on(name: 'replaced', callback: (newSession: Session) => void): void; + on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; + on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; + on(name: 'refer' | 'bye', callback: (request: IncomingRequest) => void): void; + } + + namespace Session { + interface DtmfOptions extends ExtraHeadersOptions { + duration?: number; + interToneGap?: number; + } + + interface CommonOptions extends ExtraHeadersOptions { + status_code?: number; + reason_phrase?: string; + body?: string; + } + + interface ProgressOptions extends ExtraHeadersOptions { + rel100?: boolean; + media?: MediaConstraints; + } + + interface AcceptOptions { + RTCConstraints?: any; + media?: MediaOptions; + } + + interface DTMF extends Object {} + + interface Muted { + audio?: boolean; + video?: boolean; + } + } + + interface RenderHint { + remote?: Element; + local?: Element; + } + + interface MediaConstraints { + audio: boolean; + video: boolean; + } + + interface TurnServer { + urls?: string | string[]; + username?: string; + password?: string; + } + + namespace WebRTC { + + interface Options { + stunServers?: string | string[]; + turnServers?: TurnServer | TurnServer[]; + RTCConstraints?: any; + } + + type MediaHandlerFactory = (session: Session, options: Options) => MediaHandler; + + class MediaHandler { + getLocalStreams(): any[]; + getRemoteStreams(): any[]; + render(renderHint: RenderHint): void; + + on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; + on(name: 'addStream' | 'userMedia', callback: (stream: any) => void): void; + on(name: 'userMediaFailed', callback: (error: string) => void): void; + on(name: 'iceCandidate', callback: (candidate: any) => void): void; + on( + name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | + 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, + callback: () => void): void; + on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; + } + } + + /* Parameters */ + interface ConfigurationParameters { + uri?: string; + wsServers?: string | string[] | Array<{ ws_uri: string; weigth: number }>; + allowLegacyNotifications?: boolean; + authenticationFactory?: WebRTC.MediaHandlerFactory; + authorizationUser?: string; + autostart?: boolean; + connectionRecoveryMaxInterval?: number; + connectionRecoveryMinInterval?: number; + displayName?: string; + hackCleanJitsiSdpImageattr?: boolean; + hackStripTcp?: boolean; + hackIpInContact?: boolean; + hackViaTcp?: boolean; + hackWssInTransport?: boolean; + iceCheckingTimeout?: number; + instanceId?: string; + log?: { + builtinEnabled?: boolean; + level?: number | string; + connector?: (level: string, category: string, label: string, content: string) => void; + }; + mediaHandlerFactory?: WebRTC.MediaHandlerFactory; + noAnswerTimeout?: number; + password?: string; + register?: boolean; + registerExpires?: number; + registrarServer?: string; + rel100?: string; + replaces?: string; + stunServers?: string | string[]; + traceSip?: boolean; + turnServers?: TurnServer | TurnServer[]; + usePreloadedRoute?: boolean; + userAgentString?: string; + wsServerMaxReconnection?: number; + wsServerReconnectionTimeout?: number; + } + + /* Options */ + interface ExtraHeadersOptions { + extraHeaders?: string[]; + } + + interface UnregisterOptions extends ExtraHeadersOptions { + all?: boolean; + } + + interface MessageOptions extends ExtraHeadersOptions { + contentType?: string; + } + + interface SubscribeOptions extends ExtraHeadersOptions { + expires?: number; + } + + interface MediaOptions { + constraints?: MediaConstraints; + stream?: any; + render?: RenderHint; + } + + interface InviteOptions extends ExtraHeadersOptions { + media?: MediaOptions; + anonymous?: boolean; + rel100?: string; + inviteWithoutSdp?: boolean; + RTCConstraints?: any; + } + + interface RequestOptions extends ExtraHeadersOptions { + body?: string; + } + + /* Contexts */ + interface Message extends ClientContext { + body: string; + } + + interface Subscription extends ClientContext { + id: string; + state: string; + event: string; + dialog: string; + timers: {}; + errorCodes: number[]; + subscribe(): Subscription; + unsubscribe(): void; + close(): void; + } + + /* Context */ + interface Context { + ua: UA; + method: string; + request: OutgoingRequest; + localIdentity: NameAddrHeader; + remoteIdentity: NameAddrHeader; + data: {}; + on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'notify', callback: (request: IncomingRequest) => void): void; + on(name: string, callback: () => void): void; + } + + interface ClientContext extends Context { + cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; + } + + interface ServerContext extends Context { + progress(options?: Session.ProgressOptions): void; + accept(options?: Session.AcceptOptions): void; + reject(options?: Session.CommonOptions): void; + reply(options?: Session.CommonOptions): void; + } + + /* Request */ + interface Request extends Context { + } + + interface IncomingRequest extends Request { + } + + interface OutgoingRequest extends Request { + } + + interface IncomingResponse extends Request { + } + + interface IncomingMessage extends Request { + } + + /* Header */ + interface NameAddrHeader { + uri: string | URI; + displayName: string; + + setParam(key: string, value?: string): void; + getParam(key: string): string; + deleteParam(key: string): string; + clearParams(): void; + } +} diff --git a/sip.js/sip.js-tests.ts b/sip.js/sip.js-tests.ts new file mode 100644 index 0000000000..b817b8e2c8 --- /dev/null +++ b/sip.js/sip.js-tests.ts @@ -0,0 +1,99 @@ +declare var sip: SIP; + +let ua: sipjs.UA = new sip.UA(); + +const mediaHandler = (session: sipjs.Session, options: sipjs.WebRTC.Options) => new sipjs.WebRTC.MediaHandler(); +const logConnector = (level: string, category: string, label: string, content: string) => null; + +const uaWithConfig: sipjs.UA = new sip.UA({ + uri: "wss://uri", + wsServers: ["s1", "s2"], + allowLegacyNotifications: true, + authenticationFactory: mediaHandler, + authorizationUser: "user", + autostart: true, + connectionRecoveryMaxInterval: 1, + connectionRecoveryMinInterval: 1, + displayName: "name", + hackCleanJitsiSdpImageattr: true, + hackStripTcp: true, + hackIpInContact: true, + hackViaTcp: true, + hackWssInTransport: true, + iceCheckingTimeout: 1, + instanceId: "id", + log: { + builtinEnabled: true, + level: 1, + connector: logConnector + }, + mediaHandlerFactory: mediaHandler, + noAnswerTimeout: 1, + password: "", + register: true, + registerExpires: 1, + registrarServer: "sip:registrar.mydomain.com", + rel100: "", + replaces: "", + stunServers: ["", ""], + turnServers: [ + { + password: "", + username: "", + urls: ["", ""] + } + ], + usePreloadedRoute: true, + userAgentString: "", + wsServerMaxReconnection: 1, + wsServerReconnectionTimeout: 1 +}); + +ua.start(); +ua.stop(); + +ua.register(); +ua = ua.register({ extraHeaders: [""] }); + +ua.unregister(); +ua.unregister({ extraHeaders: [""], all: true }); + +const isConnected: boolean = ua.isConnected(); +const isRegistered: boolean = ua.isRegistered(); + +const message: sipjs.Message = ua.message("", "", { contentType: "" }); + +ua.subscribe("", "", { expires: 1, extraHeaders: [""] }); +const subscription: sipjs.Subscription = ua.subscribe(new sip.URI(), "", { expires: 1, extraHeaders: [""] }); + +let session = ua.invite("", new HTMLVideoElement()); + +const inviteOptions: sipjs.InviteOptions = { + media: { + constraints: { audio: true, video: false }, + stream: new MediaStream(), + render: { remote: new Element(), local: new Element() }, + }, + anonymous: true, + rel100: "", + inviteWithoutSdp: true, + RTCConstraints: {} +}; + +session = ua.invite("", inviteOptions); + +ua.on('connected', (args: sipjs.UA.EventArgs.ConnectedArgs) => { }); +ua.on('disconnected', () => { }); +ua.on('registered', () => { }); +ua.on('unregistered', (args: sipjs.UA.EventArgs.UnregisteredArgs) => { }); +ua.on('registrationFailed', (args: sipjs.UA.EventArgs.RegistrationFailedArgs) => { }); +ua.on('invite', (session: sipjs.Session) => { + session.on('progress', (response) => { + }); + session.on('accepted', (response) => { + }); + session.on('rejected', (response) => { + }); + +}); +ua.on('message', (message: sipjs.Message) => { }); diff --git a/sip.js/tsconfig.json b/sip.js/tsconfig.json new file mode 100644 index 0000000000..b6532e5674 --- /dev/null +++ b/sip.js/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", + "sip.js-tests.ts" + ] +} diff --git a/sip.js/tslint.json b/sip.js/tslint.json new file mode 100644 index 0000000000..105f5736e6 --- /dev/null +++ b/sip.js/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false + } +} diff --git a/slug/slug-tests.ts b/slug/slug-tests.ts index 101155e3ce..5ba9aa7f29 100644 --- a/slug/slug-tests.ts +++ b/slug/slug-tests.ts @@ -1,28 +1,28 @@ -import slug = require('slug') -var print = console.log.bind(console, '>') +import slug = require('slug'); +var print = console.log.bind(console, '>'); -print(slug('i ♥ unicode')) +print(slug('i ♥ unicode')); // > i-love-unicode -print(slug('unicode ♥ is ☢')) // yes! +print(slug('unicode ♥ is ☢')); // yes! // > unicode-love-is-radioactive -print(slug('i ♥ unicode', '_')) // If you prefer something else then `-` as seperator +print(slug('i ♥ unicode', '_')); // If you prefer something else then `-` as seperator // > i_love_unicode -slug.charmap['♥'] = 'freaking love' // change default charmap or use option {charmap:{…}} as 2. argument -print(slug('I ♥ UNICODE')) +slug.charmap['♥'] = 'freaking love'; // change default charmap or use option {charmap:{…}} as 2. argument +print(slug('I ♥ UNICODE')); // > I-freaking-love-UNICODE -print(slug('☏-Number', {lower: true})) // If you prefer lower case +print(slug('☏-Number', {lower: true})); // If you prefer lower case // > telephone-number -print(slug('i <3 unicode')) +print(slug('i <3 unicode')); // > i-love-unicode // options is either object or replacement (sets options.replacement) slug('string', { } || 'replacement'); -slug.defaults.mode ='pretty'; +slug.defaults.mode = 'pretty'; slug.defaults.modes['rfc3986'] = { replacement: '-', // replace spaces with replacement symbols: true, // replace unicode symbols or not diff --git a/soap/index.d.ts b/soap/index.d.ts index 8cb9c43424..151e914f63 100644 --- a/soap/index.d.ts +++ b/soap/index.d.ts @@ -10,6 +10,10 @@ import * as events from 'events'; interface Security { } +export interface SoapMethod { + (args: any, callback: (err: any, result: any) => void, options?: any, extraHeaders?: any): void; +} + export class WSSecurity implements Security { constructor(username: string, password: string, options?: any); } @@ -19,12 +23,22 @@ export class ClientSSLSecurity implements Security { constructor(key: Buffer | string, cert: Buffer | string, defaults?: any); } -interface Client extends events.EventEmitter { - setSecurity(s: Security): void; - [method: string]: (args: any, fn: (err: any, result: any) => void, options?: any, extraHeaders?: any) => void; - addSoapHeader(headJSON: any): void; - setEndpoint(endpoint: string): void; +export interface Client extends events.EventEmitter { + addBodyAttribute(bodyAttribute: any, name?: string, namespace?: string, xmlns?: string): void; + addHttpHeader(name: string, value: any): void; + addSoapHeader(soapHeader: any, name?: string, namespace?: string, xmlns?: string): number; + changeSoapHeader(index: number, soapHeader: any, name?: string, namespace?: string, xmlns?: string): void; + clearBodyAttributes(): void; + clearHttpHeaders(): void; + clearSoapHeaders(): void; describe(): any; + getBodyAttributes(): any[]; + getHttpHeaders(): any[]; + getSoapHeaders(): any[]; + setEndpoint(endpoint: string): void; + setSOAPAction(action: string): void; + setSecurity(s: Security): void; + [method: string]: SoapMethod | Function; } export interface Server extends events.EventEmitter { diff --git a/soap/soap-tests.ts b/soap/soap-tests.ts index 48b2e2317e..9771b26efc 100644 --- a/soap/soap-tests.ts +++ b/soap/soap-tests.ts @@ -1,4 +1,3 @@ - import * as soap from 'soap'; import * as events from 'events'; import * as fs from "fs"; @@ -14,18 +13,28 @@ soap.createClient(url, wsdlOptions, function(err: any, client: soap.Client) { client.setSecurity(new soap.ClientSSLSecurity('/path/to/key', '/path/to/cert', '/path/to/ca', defaults)); client.setSecurity(new soap.ClientSSLSecurity('/path/to/key', '/path/to/cert', defaults)); client.setSecurity(new soap.ClientSSLSecurity('/path/to/key', '/path/to/cert', '/path/to/ca')); - client.addSoapHeader({}); client.setEndpoint('http://localhost'); - client['create']({ name: 'value' }, function(err, result) { + client.describe(); + client.addBodyAttribute({}); + client.addHttpHeader('test', true); + client.addSoapHeader({}); + client.changeSoapHeader(0, {}); + client.clearBodyAttributes(); + client.clearHttpHeaders(); + client.clearSoapHeaders(); + client.getBodyAttributes(); + client.getHttpHeaders(); + client.getSoapHeaders(); + client.setSOAPAction('action'); + (client['create'] as soap.SoapMethod)({ name: 'value' }, function(err: any, result: any) { // result is an object }); - client['create']({ name: 'value' }, function(err, result) { + (client['create'] as soap.SoapMethod)({ name: 'value' }, function(err: any, result: any) { // result is an object }, {}); client.on('request', function(obj: any) { //obj is an object }); - client.describe(); }); var myService = { diff --git a/socket.io/index.d.ts b/socket.io/index.d.ts index bf46ca1160..2333dc8fe2 100644 --- a/socket.io/index.d.ts +++ b/socket.io/index.d.ts @@ -180,7 +180,7 @@ declare namespace SocketIO { /** * Closes the server connection */ - close():void; + close( fn ?: () => void ):void; /** * The event fired when we get a new connection diff --git a/socket.io/socket.io-tests.ts b/socket.io/socket.io-tests.ts index 442e677751..ea3d97e21f 100644 --- a/socket.io/socket.io-tests.ts +++ b/socket.io/socket.io-tests.ts @@ -143,3 +143,14 @@ function testUsingItJustAsACrossBrowserWebSocket() { socket.on('disconnect', function () { }); }); } + +function testClosingServerWithCallback() { + var io = socketIO.listen(80); + io.close(function() { + }); +} + +function testClosingServerWithoutCallback() { + var io = socketIO.listen(80); + io.close(); +} diff --git a/spatialite/spatialite-tests.ts b/spatialite/spatialite-tests.ts index eef51b3c18..0edf111cc1 100644 --- a/spatialite/spatialite-tests.ts +++ b/spatialite/spatialite-tests.ts @@ -44,8 +44,8 @@ function insertRows() { function readAllRows() { console.log("readAllRows lorem"); - db.all("SELECT rowid AS id, info FROM lorem", function(err, rows) { - rows.forEach(function (row) { + db.all("SELECT rowid AS id, info FROM lorem", (err, rows) => { + rows.forEach(row => { console.log(row.id + ": " + row.info); }); readSomeRows(); @@ -54,7 +54,7 @@ function readAllRows() { function readSomeRows() { console.log("readAllRows lorem"); - db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, (err, row) => { console.log(row.id + ": " + row.info); }, closeDb); } @@ -70,7 +70,7 @@ function runChainExample() { runChainExample(); -db.serialize(function() { +db.serialize(() => { db.run("CREATE TABLE lorem (info TEXT)"); var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); @@ -79,15 +79,15 @@ db.serialize(function() { } stmt.finalize(); - db.each("SELECT rowid AS id, info FROM lorem", function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem", (err, row) => { console.log(row.id + ": " + row.info); }); }); -db.serialize(function() { +db.serialize(() => { // These two queries will run sequentially. db.run("CREATE TABLE foo (num)"); - db.run("INSERT INTO foo VALUES (?)", 1, function(err) { + db.run("INSERT INTO foo VALUES (?)", 1, err => { // These queries will run in parallel and the second query will probably // fail because the table might not exist yet. db.run("CREATE TABLE bar (num)"); @@ -107,7 +107,7 @@ db.run("UPDATE tbl SET name = $name WHERE id = $id", { $name: "bar" }); db.run("UPDATE tbl SET name = $name WHERE id = $id", { $id: 2, $name: "bar" }, - function(err) { } + err => { } ); db.run("UPDATE tbl SET name = ?5 WHERE id = ?", { diff --git a/spatialite/tsconfig.json b/spatialite/tsconfig.json index 6ad0b96035..ddcef0c7ac 100644 --- a/spatialite/tsconfig.json +++ b/spatialite/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "spatialite-tests.ts" ] -} +} \ No newline at end of file diff --git a/spectacle/index.d.ts b/spectacle/index.d.ts index 55227fbb2c..41095a5839 100644 --- a/spectacle/index.d.ts +++ b/spectacle/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/FormidableLabs/victory // Definitions by: Zachary Maybury // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/sqlite3/sqlite3-tests.ts b/sqlite3/sqlite3-tests.ts index 5e13fd7840..75a8c2e72c 100644 --- a/sqlite3/sqlite3-tests.ts +++ b/sqlite3/sqlite3-tests.ts @@ -27,8 +27,8 @@ function insertRows() { function readAllRows() { console.log("readAllRows lorem"); - db.all("SELECT rowid AS id, info FROM lorem", function(err, rows) { - rows.forEach(function (row) { + db.all("SELECT rowid AS id, info FROM lorem", (err, rows) => { + rows.forEach(row => { console.log(row.id + ": " + row.info); }); readSomeRows(); @@ -37,7 +37,7 @@ function readAllRows() { function readSomeRows() { console.log("readAllRows lorem"); - db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, (err, row) => { console.log(row.id + ": " + row.info); }, closeDb); } @@ -53,7 +53,7 @@ function runChainExample() { runChainExample(); -db.serialize(function() { +db.serialize(() => { db.run("CREATE TABLE lorem (info TEXT)"); var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); @@ -62,15 +62,15 @@ db.serialize(function() { } stmt.finalize(); - db.each("SELECT rowid AS id, info FROM lorem", function(err, row) { + db.each("SELECT rowid AS id, info FROM lorem", (err, row) => { console.log(row.id + ": " + row.info); }); }); -db.serialize(function() { +db.serialize(() => { // These two queries will run sequentially. db.run("CREATE TABLE foo (num)"); - db.run("INSERT INTO foo VALUES (?)", 1, function(err) { + db.run("INSERT INTO foo VALUES (?)", 1, err => { // These queries will run in parallel and the second query will probably // fail because the table might not exist yet. db.run("CREATE TABLE bar (num)"); @@ -90,7 +90,7 @@ db.run("UPDATE tbl SET name = $name WHERE id = $id", { $name: "bar" }); db.run("UPDATE tbl SET name = $name WHERE id = $id", { $id: 2, $name: "bar" }, - function(err) { } + err => { } ); db.run("UPDATE tbl SET name = ?5 WHERE id = ?", { diff --git a/sshpk/index.d.ts b/sshpk/index.d.ts index 05d26053b6..0bc2274120 100644 --- a/sshpk/index.d.ts +++ b/sshpk/index.d.ts @@ -365,7 +365,8 @@ declare namespace SshPK { export function parseCertificate(data: string|Buffer, format: string, options?: any): Certificate; export function createSelfSignedCertificate(subjectOrSubjects: string, key: Key, options?: any): Certificate; - export function createCertificate(subjectOrSubjects: string, key: Key, issuer: string, + export function createCertificate( + subjectOrSubjects: string, key: Key, issuer: string, issuerKey: PrivateKey, options?: any): Certificate; export function identityFromDN(dn: string): Identity; diff --git a/steed/index.d.ts b/steed/index.d.ts new file mode 100644 index 0000000000..4865c8efa8 --- /dev/null +++ b/steed/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for steed 1.1 +// Project: https://github.com/mcollina/steed#readme +// Definitions by: Paul Isache +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace steed { + interface Dictionary { [key: string]: T; } + type ErrorCallback = (err?: T) => void; + + type SteedResultCallback = (err: E, result: T) => void; + type SteedResultArrayCallback = (err: E, results: T[]) => void; + type SteedResultObjectCallback = (err: E, results: Dictionary) => void; + + type SteedWorker = (task: T, callback: ErrorCallback) => void; + type SteedIterator = (item: T, callback: ErrorCallback) => void; + type SteedResultIterator = (item: T, callback: SteedResultCallback) => void; + type SteedFunction = (callback: (err?: E, result?: T) => void) => void; + + interface SteedQueue { + push(task: T | T[], callback?: SteedResultCallback): void; + unshift(task: T | T[], callback?: ErrorCallback): void; + pause(): void; + resume(): void; + idle(): boolean; + length(): number; + kill(): void; + concurrency: number; + drain: () => any; + empty: () => any; + saturated: () => any; + } + + interface Steed { + parallel(tasks: Array>, callback?: SteedResultArrayCallback): void; + parallel(tasks: Dictionary>, callback?: SteedResultObjectCallback): void; + series(tasks: Array>, callback?: SteedResultArrayCallback): void; + series(tasks: Dictionary>, callback?: SteedResultObjectCallback): void; + waterfall(tasks: Function[], callback?: SteedResultCallback): void; + each(arr: T[] | Dictionary, iterator: SteedIterator, callback?: ErrorCallback): void; + eachSeries: typeof steed.each; + map(arr: T[] | Dictionary, iterator: SteedResultIterator, callback?: SteedResultArrayCallback): void; + mapSeries: typeof steed.map; + queue(worker: SteedWorker, concurrency?: number): SteedQueue; + queue(worker: SteedResultIterator, concurrency?: number): SteedQueue; + } +} + +declare const steed: steed.Steed; + +export = steed; diff --git a/steed/steed-tests.ts b/steed/steed-tests.ts new file mode 100644 index 0000000000..dd89e4480b --- /dev/null +++ b/steed/steed-tests.ts @@ -0,0 +1,328 @@ +/// + +import steed = require('steed'); + +declare var path: { + exists: (path: string, callback?: (error: Error, exists: boolean) => any) => void; +}; + +function funcStringCbErrBoolean(v: string, cb: (error: Error, res: boolean) => void) { } +function callback() { } + +steed.parallel([ + () => {}, + () => {} +], callback); + +steed.series([ + () => {}, + () => {} +]); + +var data: any[] = []; +function steedProcess(item: any, callback: (error: Error, result: any) => void) { } +steed.map(data, steedProcess, (error, results) => { + console.log(results); +}); + +var openFiles = ['file1', 'file2']; + +var saveFile = (file: string, cb: (error: Error) => void) => {}; +steed.each(openFiles, saveFile, (error: Error) => {}); +steed.eachSeries(openFiles, saveFile, (error: Error) => {}); + +// Control Flow // + +steed.series([ + callback => { + callback(undefined, 'one'); + }, + callback => { + callback(undefined, 'two'); + }, +], + (error, results) => {}); + +steed.series([ + callback => { + callback(undefined, 'one'); + }, + callback => { + callback(undefined, 'two'); + }, +], + (error, results) => {}); + +steed.series({ + one(callback) { + setTimeout(() => { + callback(undefined, 1); + }, 200); + }, + two(callback) { + setTimeout(() => { + callback(undefined, 2); + }, 100); + }, +}, + (error, results) => {}); + +steed.series({ + one(callback) { + setTimeout(() => { + callback(undefined, 1); + }, 200); + }, + two(callback) { + setTimeout(() => { + callback(undefined, 2); + }, 100); + }, +}, + (error, results) => {}); + +steed.parallel([ + callback => { + setTimeout(() => { + callback(undefined, 'one'); + }, 200); + }, + callback => { + setTimeout(() => { + callback(undefined, 'two'); + }, 100); + }, +], + (error, results) => {}); + +steed.parallel([ + callback => { + setTimeout(() => { + callback(undefined, 'one'); + }, 200); + }, + callback => { + setTimeout(() => { + callback(undefined, 'two'); + }, 100); + }, +], + (error, results) => {}); + + +steed.parallel({ + one(callback) { + setTimeout(() => { + callback(undefined, 1); + }, 200); + }, + two(callback) { + setTimeout(() => { + callback(undefined, 2); + }, 100); + }, +}, + (error, results) => {}); + +steed.parallel({ + one(callback) { + setTimeout(() => { + callback(undefined, 1); + }, 200); + }, + two(callback) { + setTimeout(() => { + callback(undefined, 2); + }, 100); + }, +}, + (error, results) => {}); + +function whileFn(callback: any) { + count++; + setTimeout(callback, 1000); +} + +function whileTest() { return count < 5; } +var count = 0; + +steed.waterfall([ + (callback: any) => { + callback(null, 'one', 'two'); + }, + (arg1: any, arg2: any, callback: any) => { + callback(null, 'three'); + }, + (arg1: any, callback: any) => { + callback(null, 'done'); + } +], (error, result) => {}); + + +var q = steed.queue((task: any, callback: () => void) => { + console.log('hello ' + task.name); + callback(); +}, 2); + + +q.drain = () => { + console.log('all items have been processed'); +}; + +q.push({ name: 'foo' }); + +q.push({ name: 'bar' }, err => { + console.log('finished processing bar'); +}); + +q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], (error: Error) => { + console.log('finished processing bar'); +}); + +q.unshift({ name: 'foo' }); + +q.unshift({ name: 'bar' }, err => { + console.log('finished processing bar'); +}); + +q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], (error: Error) => { + console.log('finished processing bar'); +}); + +var qLength: number = q.length(); +var qIsIdle: boolean = q.idle(); + +q.saturated = () => { + console.log('queue is saturated.'); +}; + +q.empty = () => { + console.log('queue is empty.'); +}; + +q.drain = () => { + console.log('queue was drained.'); +}; + +q.pause(); +q.resume(); +q.kill(); + +// tests for strongly typed tasks +var q2 = steed.queue((task: string, callback: () => void) => { + console.log('Task: ' + task); + callback(); +}, 1); + +q2.push('task1'); + +q2.push('task2', error => { + console.log('Finished tasks'); +}); + +q2.push(['task3', 'task4', 'task5'], (error: Error) => { + console.log('Finished tasks'); +}); + +q2.unshift('task1'); + +q2.unshift('task2', error => { + console.log('Finished tasks'); +}); + +q2.unshift(['task3', 'task4', 'task5'], (error: Error) => { + console.log('Finished tasks'); +}); + +steed.parallel([ + (callback: (error: Error, val: string) => void) => { }, + callback => {} +], + (error: Error, results: string[]) => { + steed.series([ + callback => { }, + function email_link(callback) { } + ]); + }); + +// each + +steed.each({ + a: 1, + b: 2 +}, (val: number, next: steed.ErrorCallback): void => { + + setTimeout((): void => { + + console.log(`steed.each: ${val}`); + + next(); + + }, 500); + +}, (err?: Error): void => { + + console.log("steed.each: done."); + +}); + +steed.eachSeries({ + a: 1, + b: 2 +}, (val: number, next: steed.ErrorCallback): void => { + + setTimeout((): void => { + + console.log(`steed.eachSeries: ${val}`); + + next(); + + }, 500); + +}, (err?: Error): void => { + + console.log("steed.eachSeries: done."); + +}); + +// map + +steed.map({ + a: 1, + b: 2, + c: 3 +}, (val: number, next: steed.SteedResultCallback): void => { + + setTimeout((): void => { + + console.log(`steed.map: ${val}`); + + next(undefined as any, val.toString()); + + }, 500); + +}, (error: Error, results: string[]): void => { + + console.log("steed.map: done with results", results); + +}); + +steed.mapSeries({ + a: 1, + b: 2, + c: 3 +}, (val: number, next: steed.SteedResultCallback): void => { + + setTimeout((): void => { + + console.log(`steed.mapSeries: ${val}`); + + next(undefined as any, val.toString()); + + }, 500); + +}, (error: Error, results: string[]): void => { + + console.log("steed.mapSeries: done with results", results); + +}); diff --git a/steed/tsconfig.json b/steed/tsconfig.json new file mode 100644 index 0000000000..54a669803d --- /dev/null +++ b/steed/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", + "steed-tests.ts" + ] +} \ No newline at end of file diff --git a/steed/tslint.json b/steed/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/steed/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/storejs/index.d.ts b/storejs/index.d.ts index ad5d8e979c..0068d94722 100644 --- a/storejs/index.d.ts +++ b/storejs/index.d.ts @@ -16,10 +16,11 @@ interface StoreJSStatic { getAll(): any; serialize(value: any): string; deserialize(value: string): any; + forEach(command: (key: string, value: any) => void): void; } declare var store: StoreJSStatic; declare module 'store' { - export = store; + export = store; } diff --git a/storejs/storejs-tests.ts b/storejs/storejs-tests.ts index 19e0ae898b..13c937c3c9 100644 --- a/storejs/storejs-tests.ts +++ b/storejs/storejs-tests.ts @@ -5,7 +5,7 @@ import * as store from 'store'; store.set('username', 'marcus'); // Get 'username' -var userName:any = store.get('username'); +var userName: any = store.get('username'); var all: Object = store.getAll(); @@ -22,3 +22,10 @@ store.set('user', { name: 'marcus', likes: 'javascript' }); var user: any = store.get('user'); alert(user.name + ' likes ' + user.likes); +// Get all stored values +store.getAll().user.name; + +// Loop over all stored values +store.forEach(function(key, val) { + console.log(key, '==', val); +}); diff --git a/strip-ansi/strip-ansi-tests.ts b/strip-ansi/strip-ansi-tests.ts index 6d38a0ed49..12e60b5e82 100644 --- a/strip-ansi/strip-ansi-tests.ts +++ b/strip-ansi/strip-ansi-tests.ts @@ -1,4 +1,4 @@ import stripAnsi = require('strip-ansi'); stripAnsi('\u001b[4mcake\u001b[0m'); -//=> 'cake' \ No newline at end of file +// => 'cake' \ No newline at end of file diff --git a/strip-bom/strip-bom-tests.ts b/strip-bom/strip-bom-tests.ts index dc63d80303..79aaa3daae 100644 --- a/strip-bom/strip-bom-tests.ts +++ b/strip-bom/strip-bom-tests.ts @@ -1,4 +1,4 @@ import stripBom = require('strip-bom'); stripBom('\uFEFFunicorn'); -//=> 'unicorn' \ No newline at end of file +// => 'unicorn' \ No newline at end of file diff --git a/stripe/index.d.ts b/stripe/index.d.ts index a7d887c747..3e5d902060 100644 --- a/stripe/index.d.ts +++ b/stripe/index.d.ts @@ -1,6 +1,10 @@ -// Type definitions for stripe 0.0 +// Type definitions for stripe 2.x // Project: https://stripe.com/ -// Definitions by: Andy Hawkins , Eric J. Smith , Amrit Kahlon , Adam Cmiel +// Definitions by: Andy Hawkins +// Eric J. Smith +// Amrit Kahlon +// Adam Cmiel +// Justin Leider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare const Stripe: StripeStatic; @@ -12,13 +16,13 @@ interface StripeStatic { validateExpiry(month: string, year: string): boolean; validateCVC(cardCVC: string): boolean; cardType(cardNumber: string): StripeCardDataBrand; - getToken(token: string, responseHandler: (status: number, response: StripeTokenResponse) => void): void; - card: StripeCardData; - createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; + getToken(token: string, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + card: StripeCard; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; bankAccount: StripeBankAccount; } -interface StripeTokenData { +interface StripeCardTokenData { number: string; exp_month?: number; exp_year?: number; @@ -35,7 +39,7 @@ interface StripeTokenData { interface StripeTokenResponse { id: string; - card: StripeCardData; + client_ip: string; created: number; livemode: boolean; object: string; @@ -44,6 +48,10 @@ interface StripeTokenResponse { error?: StripeError; } +interface StripeCardTokenResponse extends StripeTokenResponse { + card: StripeCard; +} + interface StripeError { type: string; code: string; @@ -53,7 +61,7 @@ interface StripeError { type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; -interface StripeCardData { +interface StripeCard { object: string; last4: string; exp_month: number; @@ -67,7 +75,10 @@ interface StripeCardData { address_zip?: string; address_country?: string; brand?: StripeCardDataBrand; - createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + validateCardNumber(cardNumber: string): boolean; + validateExpiry(month: string, year: string): boolean; + validateCVC(cardCVC: string): boolean; } interface StripeBankAccount { @@ -85,8 +96,7 @@ interface StripeBankTokenParams { account_holder_type: string; } -interface StripeBankTokenResponse { - id: string; +interface StripeBankTokenResponse extends StripeTokenResponse { bank_account: { country: string; bank_name: string; @@ -94,12 +104,6 @@ interface StripeBankTokenResponse { validated: boolean; object: string; }; - created: number; - livemode: boolean; - type: string; - object: string; - used: boolean; - error?: StripeError; } interface StripeApplePay { @@ -134,7 +138,7 @@ interface StripeApplePayLineItem { } interface StripeApplePaySessionResult { - token: StripeTokenResponse; + token: StripeCardTokenResponse; shippingContact?: StripeApplePayPaymentContact; shippingMethod?: StripeApplePayShippingMethod; } diff --git a/stripe/stripe-tests.ts b/stripe/stripe-tests.ts index 44aa09d216..56e6343f5c 100644 --- a/stripe/stripe-tests.ts +++ b/stripe/stripe-tests.ts @@ -1,4 +1,4 @@ -function success(card: StripeCardData) { +function success(card: StripeCard) { console.log(card.brand && card.brand.toString()); } @@ -6,7 +6,7 @@ const cardNumber = '4242424242424242'; const isValid = Stripe.validateCardNumber(cardNumber); if (isValid) { - const tokenData: StripeTokenData = { + const tokenData: StripeCardTokenData = { number: cardNumber, exp_month: 1, exp_year: 2100, diff --git a/stripe/tslint.json b/stripe/tslint.json index f9e30021f4..377cc837d4 100644 --- a/stripe/tslint.json +++ b/stripe/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/strong-cluster-control/index.d.ts b/strong-cluster-control/index.d.ts index e0bb92b82f..5037aed03b 100644 --- a/strong-cluster-control/index.d.ts +++ b/strong-cluster-control/index.d.ts @@ -43,7 +43,7 @@ declare namespace StrongClusterControl { * @description Start the controller * @param [options] - An options object, no default, and options object is not required. * @param [options.size] - Number of workers that should be running, the default is to not control the number of workers - * @param [options.env=null] - Environment properties object passed to cluster.fork() if the controller has to start a worker to resize the cluster, default is null. + * @param [options.env=null] - Environment properties object passed to cluster.fork() if the controller has to start a worker to resize the cluster, default is null. * @param [options.shutdownTimeout=5000] - Number of milliseconds to wait after shutdown before terminating a worker, the default is 5 seconds * @param [options.terminateTimeout=5000] - Number of milliseconds to wait after terminate before killing a worker, the default is 5 seconds * @param [options.throttoleDelay] - Number of milliseconds to delay restarting workers after they are exiting abnormally. Abnormal is defined as as not suicide. diff --git a/strong-cluster-control/tsconfig.json b/strong-cluster-control/tsconfig.json index 3623adaea2..6d625c44b6 100644 --- a/strong-cluster-control/tsconfig.json +++ b/strong-cluster-control/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -17,4 +19,4 @@ "index.d.ts", "strong-cluster-control-tests.ts" ] -} +} \ No newline at end of file diff --git a/supertest-as-promised/index.d.ts b/supertest-as-promised/index.d.ts index db0bf18e81..385f25867b 100644 --- a/supertest-as-promised/index.d.ts +++ b/supertest-as-promised/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SuperTest as Promised v2.0.2 +// Type definitions for SuperTest as Promised 2.0 // Project: https://github.com/WhoopInc/supertest-as-promised // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/supertest-as-promised/supertest-as-promised-tests.ts b/supertest-as-promised/supertest-as-promised-tests.ts index d6eb5771c9..c20f9a92b6 100644 --- a/supertest-as-promised/supertest-as-promised-tests.ts +++ b/supertest-as-promised/supertest-as-promised-tests.ts @@ -10,13 +10,13 @@ var app = express(); request(app) .get("/user") .expect(200) - .then(function (res) { + .then(res => { return request(app) .post("/kittens") .send({ userId: res}) .expect(201); }) - .then(function (res) { + .then(res => { // ... }); @@ -25,12 +25,12 @@ request(app) request(app) .get("/kittens") .expect(200) - .then(function (res) { + .then(res => { // ... }); -describe("GET /kittens", function () { - it("should work", function () { +describe("GET /kittens", () => { + it("should work", () => { return request(app).get("/kittens").expect(200); }); }); @@ -41,18 +41,18 @@ var agent = request.agent(app); agent .get("/ugly-kitteh") .expect(404) - .then(function () { + .then(() => { // ... - }) + }); // Promisey goodness request(app) .get("/kittens") .expect(201) - .then(function (res) { /* ... */ }) + .then(res => { /* ... */ }) // I'm a real promise now! - .catch(function (err) { /* ... */ }) + .catch(err => { /* ... */ }); request(app) .get("/kittens") @@ -60,4 +60,4 @@ request(app) .toPromise() // I'm a real promise now! .delay(10) - .then(function (res) { /* ... */ }) + .then(res => { /* ... */ }); diff --git a/supertest-as-promised/tslint.json b/supertest-as-promised/tslint.json new file mode 100644 index 0000000000..105f5736e6 --- /dev/null +++ b/supertest-as-promised/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false + } +} diff --git a/swagger-express-mw/swagger-express-mw-tests.ts b/swagger-express-mw/swagger-express-mw-tests.ts index 78fc26889c..a066071758 100644 --- a/swagger-express-mw/swagger-express-mw-tests.ts +++ b/swagger-express-mw/swagger-express-mw-tests.ts @@ -1,8 +1,8 @@ import * as SwaggerExpress from "swagger-express-mw"; import * as express from "express"; -let app = express(); -let config: SwaggerExpress.Config = { +const app = express(); +const config: SwaggerExpress.Config = { appRoot: __dirname }; @@ -17,12 +17,12 @@ SwaggerExpress.create(config, (err, middleware) => { }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerExpress.Config = { +const configComplex: SwaggerExpress.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -32,7 +32,7 @@ let configComplex: SwaggerExpress.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-hapi/swagger-hapi-tests.ts b/swagger-hapi/swagger-hapi-tests.ts index 50d3954975..3d894aafba 100644 --- a/swagger-hapi/swagger-hapi-tests.ts +++ b/swagger-hapi/swagger-hapi-tests.ts @@ -9,7 +9,7 @@ var config = { appRoot: __dirname // required config } as SwaggerHapi.Config; -SwaggerHapi.create(config, function(err, swaggerHapi) { +SwaggerHapi.create(config, (err, swaggerHapi) => { if (err) { throw err; } var port = process.env.PORT || 10010; @@ -19,22 +19,22 @@ SwaggerHapi.create(config, function(err, swaggerHapi) { // }; if (swaggerHapi.config.swagger !== undefined) { - let appRootFromMw = swaggerHapi.config.swagger.appRoot; + const appRootFromMw = swaggerHapi.config.swagger.appRoot; } - app.register(swaggerHapi.plugin, function(err) { + app.register(swaggerHapi.plugin, err => { if (err) { return console.error("Failed to load plugin:", err); } // stat app etc.. }); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerHapi.Config = { +const configComplex: SwaggerHapi.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -44,7 +44,7 @@ let configComplex: SwaggerHapi.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-node-runner/swagger-node-runner-tests.ts b/swagger-node-runner/swagger-node-runner-tests.ts index 49538d3825..cff8e9d570 100644 --- a/swagger-node-runner/swagger-node-runner-tests.ts +++ b/swagger-node-runner/swagger-node-runner-tests.ts @@ -5,17 +5,17 @@ import * as Hapi from "hapi"; import * as restify from "restify"; import * as sails from "sails.io.js"; -let config: SwaggerNodeRunner.Config = { +const config: SwaggerNodeRunner.Config = { appRoot: __dirname }; // Express middleware -let expressApp = express(); +const expressApp = express(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; // or handle error } - let expressMiddleware = runner.expressMiddleware(); + const expressMiddleware = runner.expressMiddleware(); expressMiddleware.register(expressApp); const port = process.env.PORT || 10010; @@ -23,14 +23,14 @@ SwaggerNodeRunner.create(config, (err, runner) => { }); -//Connect middleware -let connectApp = connect(); +// Connect middleware +const connectApp = connect(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let conncetMiddleware = runner.connectMiddleware(); + const connectMiddleware = runner.connectMiddleware(); - conncetMiddleware.register(connectApp); + connectMiddleware.register(connectApp); var port = process.env.PORT || 10010; connectApp.listen(port); }); @@ -40,16 +40,16 @@ SwaggerNodeRunner.create(config, (err, runner) => { SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let sailsMw = runner.sailsMiddleware(); - if(typeof sailsMw.chain !== 'function' || !sailsMw.runner) { + const sailsMw = runner.sailsMiddleware(); + if (typeof sailsMw.chain !== 'function' || !sailsMw.runner) { // do nothing } }); -//Hapi Middleware +// Hapi Middleware var hapiapp = new Hapi.Server(); -SwaggerNodeRunner.create(config, function(err, runner) { +SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } var port = process.env.PORT || 10010; @@ -57,15 +57,15 @@ SwaggerNodeRunner.create(config, function(err, runner) { // hapiapp.address = function() { // return { port }; // }; - let hapiMiddleware = runner.hapiMiddleware(); + const hapiMiddleware = runner.hapiMiddleware(); if (hapiMiddleware.config.swagger !== undefined) { - let appRootFromMw = hapiMiddleware.config.swagger.appRoot; + const appRootFromMw = hapiMiddleware.config.swagger.appRoot; } - let pluginAttributes = hapiMiddleware.plugin.register.attributes.name + hapiMiddleware.plugin.register.attributes.version; + const pluginAttributes = hapiMiddleware.plugin.register.attributes.name + hapiMiddleware.plugin.register.attributes.version; - hapiapp.register(hapiMiddleware.plugin, function(err) { + hapiapp.register(hapiMiddleware.plugin, err => { if (err) { return console.error("Failed to load plugin:", err); } // stat app etc.. }); @@ -73,25 +73,25 @@ SwaggerNodeRunner.create(config, function(err, runner) { // Restify Middelware -let app = restify.createServer(); -SwaggerNodeRunner.create(config, function(err, runner) { +const app = restify.createServer(); +SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let restifyMiddelware = runner.restifyMiddleware() + const restifyMiddelware = runner.restifyMiddleware(); restifyMiddelware.register(app); - let port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; app.listen(port); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerNodeRunner.Config = { +const configComplex: SwaggerNodeRunner.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -101,7 +101,7 @@ let configComplex: SwaggerNodeRunner.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-parser/tslint.json b/swagger-parser/tslint.json index ec365f164b..377cc837d4 100644 --- a/swagger-parser/tslint.json +++ b/swagger-parser/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/swagger-restify-mw/swagger-restify-mw-tests.ts b/swagger-restify-mw/swagger-restify-mw-tests.ts index c8bd436c7c..73568b2153 100644 --- a/swagger-restify-mw/swagger-restify-mw-tests.ts +++ b/swagger-restify-mw/swagger-restify-mw-tests.ts @@ -1,28 +1,28 @@ import * as SwaggerRestify from "swagger-restify-mw"; import * as restify from "restify"; -let app = restify.createServer(); +const app = restify.createServer(); -let config = { +const config = { appRoot: __dirname // required config } as SwaggerRestify.Config; -SwaggerRestify.create(config, function(err, swaggerRestify) { +SwaggerRestify.create(config, (err, swaggerRestify) => { if (err) { throw err; } swaggerRestify.register(app); - let port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; app.listen(port); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerRestify.Config = { +const configComplex: SwaggerRestify.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -32,7 +32,7 @@ let configComplex: SwaggerRestify.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-sails-hook/swagger-sails-hook-tests.ts b/swagger-sails-hook/swagger-sails-hook-tests.ts index ee023047c3..c1b73a08b7 100644 --- a/swagger-sails-hook/swagger-sails-hook-tests.ts +++ b/swagger-sails-hook/swagger-sails-hook-tests.ts @@ -11,8 +11,8 @@ const mockSailsApp = { }; // create and register hook -let swaggerHookRef = swaggerSailsHook(mockSailsApp); -if(typeof swaggerHookRef.routes.after['/*'] === 'function') { +const swaggerHookRef = swaggerSailsHook(mockSailsApp); +if (typeof swaggerHookRef.routes.after['/*'] === 'function') { // right type } diff --git a/swagger-schema-official/swagger-schema-official-tests.ts b/swagger-schema-official/swagger-schema-official-tests.ts index 79eedfa076..42e35483ea 100644 --- a/swagger-schema-official/swagger-schema-official-tests.ts +++ b/swagger-schema-official/swagger-schema-official-tests.ts @@ -1,5 +1,7 @@ import * as swagger from "swagger-schema-official"; +// tslint:disable:max-line-length + const apiExample: swagger.Spec = { "swagger": "2.0", "info": { diff --git a/swagger-schema-official/tslint.json b/swagger-schema-official/tslint.json index ec365f164b..6721a6962c 100644 --- a/swagger-schema-official/tslint.json +++ b/swagger-schema-official/tslint.json @@ -1,3 +1,6 @@ { - "extends": "../tslint.json" + "extends": "../tslint.json", + "rules": { + "object-literal-key-quotes": false + } } diff --git a/swiper/index.d.ts b/swiper/index.d.ts index cb6ff159f1..99cdc714d9 100644 --- a/swiper/index.d.ts +++ b/swiper/index.d.ts @@ -1,106 +1,216 @@ -// Type definitions for Swiper 2.0.0 +// Type definitions for Swiper 3.4 // Project: https://github.com/nolimits4web/Swiper -// Definitions by: Sebastián Galiano +// Definitions by: Sebastián Galiano , Luca Trazzi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - interface SwiperOptions { - speed?: number; - autoplay?: number; - mode?: string; - loop?: boolean; - loopAdditionalSlides?: number; - slidesPerView?: any; - slidesPerGroup?: number; - calculateHeight?: boolean; - updateOnImagesReady?: boolean; - releaseFormElements?: boolean; - watchActiveIndex?: boolean; - visibilityFullFit?: boolean; - autoResize?: boolean; - resizeReInit?: boolean; - DOMAnimation?: boolean; - resistance?: any; - noSwiping?: boolean; - preventLinks?: boolean; initialSlide?: number; - useCSS3Transforms?: boolean; + direction?: string; + speed?: number; + setWrapperSize?: boolean; + virtualTranslate?: boolean; + width?: number; + height?: number; + autoHeight?: boolean; + roundLengths?: boolean; + nested?: boolean; - // Free Mode and Scroll Container + // Autoplay + autoplay?: number; + autoplayStopOnLast?: boolean; + autoplayDisableOnInteraction?: boolean; + + // Progress + watchSlidesProgress?: boolean; + watchSlidesVisibility?: boolean; + + // Freemode freeMode?: boolean; - freeModeFluid?: boolean; - scrollContainer?: boolean; - momentumRatio?: number; - momentumBounce?: boolean; - momentumBounceRatio?: number; + freeModeMomentum?: boolean; + freeModeMomentumRatio?: number; + freeModeMomentumBounce?: boolean; + freeModeMomentumBounceRatio?: number; + freeModeMinimumVelocity?: number; + freeModeSticky?: boolean; - // Slides offset + // Effects + effect?: string; + fade?: {}; + cube?: {}; + coverflow?: {}; + flip?: {}; + + // Parallax + parallax?: boolean; + + // Slides grid + spaceBetween?: number; + slidesPerView?: number | string; + slidesPerColumn?: number; + slidesPerColumnFill?: string; + slidesPerGroup?: number; centeredSlides?: boolean; - offsetPxBefore?: number; - offsetPxAfter?: number; - offsetSlidesBefore?: number; - offsetSlidesAfter?: number; + slidesOffsetBefore?: number; + slidesOffsetAfter?: number; - // Touch/mouse interactions - touchRatio?: number; - simulateTouch?: boolean; - onlyExternal?: boolean; - followFinger?: boolean; + // Grab Cursor grabCursor?: boolean; - shortSwipes?: boolean; - moveStartThreshold?: number; - // Navigation - keyboardControl?: boolean; - mousewheelControl?: boolean; - nextButton?: string | HTMLElement; - prevButton?: string | HTMLElement; + // Touches + touchEventsTarget?: string; + touchRatio?: number; + touchAngle?: number; + simulateTouch?: boolean; + shortSwipes?: boolean; + longSwipes?: boolean; + longSwipesRatio?: number; + longSwipesMs?: number; + followFinger?: boolean; + onlyExternal?: boolean; + threshold?: number; + touchMoveStopPropagation?: boolean; + iOSEdgeSwipeDetection?: boolean; + iOSEdgeSwipeThreshold?: number; + + // Touch Resistance + resistance?: boolean; + resistanceRatio?: number; + + // Clicks + preventClicks?: boolean; + preventClicksPropagation?: boolean; + slideToClickedSlide?: boolean; + + // Swiping / No swiping + allowSwipeToPrev?: boolean; + allowSwipeToNext?: boolean; + noSwiping?: boolean; + noSwipingClass?: string; + swipeHandler?: string | Element; + + // Navigation Controls + uniqueNavElements?: boolean; // Pagination - pagination?: any; + pagination?: string | Element; + paginationType?: string; + paginationHide?: boolean; paginationClickable?: boolean; - paginationAsRange?: boolean; - createPagination?: boolean; + paginationElement?: string; + paginationBulletRender?: (swiper: Swiper, index: number, className: string) => void; + paginationFractionRender?: (swiper: Swiper, currentClassName: string, totalClassName: string) => void; + paginationProgressRender?: (swiper: Swiper, progressbarClass: string) => void; + paginationCustomRender?: (swiper: Swiper, current: number, total: number) => void; + + // Navigation Buttons + nextButton?: string | Element; + prevButton?: string | Element; + + // Scollbar + scrollbar?: string | Element | SwiperScrollbarOptions; + scrollbarHide?: boolean; + scrollbarDraggable?: boolean; + scrollbarSnapOnRelease?: boolean; + + + // Accessibility + a11y?: boolean; + prevSlideMessage?: string; + nextSlideMessage?: string; + firstSlideMessage?: string; + lastSlideMessage?: string; + paginationBulletMessage?: string; + + + // Keyboard / Mousewheel + keyboardControl?: boolean; + mousewheelControl?: boolean; + mousewheelForceToAxis?: boolean; + mousewheelReleaseOnEdges?: boolean; + mousewheelInvert?: boolean; + mousewheelSensitivity?: number; + + // Hash Navigation + hashnav?: boolean; + hashnavWatchState?: boolean; + history?: string; + + + // Images + preloadImages?: boolean; + updateOnImagesReady?: boolean; + lazyLoading?: boolean; + lazyLoadingInPrevNext?: boolean; + lazyLoadingInPrevNextAmount?: number; + lazyLoadingOnTransitionStart?: boolean; + + // Loop + loop?: boolean; + loopAdditionalSlides?: number; + loopedSlides?: number; + + zoom?: boolean; + + // Controller + control?: Swiper; + controlInverse?: boolean; + controlBy?: string; + + // Observer + observer?: boolean; + observeParents?: boolean; + + // Breakpoints + breakpoints?: {}; + + // Callbacks + runCallbacksOnInit?: boolean; + onInit?: (swiper: Swiper) => void; + onSlideChangeStart?: (swiper: Swiper) => void; + onSlideChangeEnd?: (swiper: Swiper) => void; + onSlideNextStart?: (swiper: Swiper) => void; + onSlideNextEnd?: (swiper: Swiper) => void; + onSlidePrevStart?: (swiper: Swiper) => void; + onSlidePrevEnd?: (swiper: Swiper) => void; + onTransitionStart?: (swiper: Swiper) => void; + onTransitionEnd?: (swiper: Swiper) => void; + onTouchStart?: (swiper: Swiper, event: Event) => void; + onTouchMove?: (swiper: Swiper, event: Event) => void; + onTouchMoveOpposite?: (swiper: Swiper, event: Event) => void; + onSliderMove?: (swiper: Swiper, event: Event) => void; + onTouchEnd?: (swiper: Swiper, event: Event) => void; + onClick?: (swiper: Swiper, event: Event) => void; + onTap?: (swiper: Swiper, event: Event) => void; + onDoubleTap?: (swiper: Swiper, event: Event) => void; + onImagesReady?: (swiper: Swiper) => void; + onProgress?: (swiper: Swiper, progress: number) => void; + onReachBeginning?: (swiper: Swiper) => void; + onReachEnd?: (swiper: Swiper) => void; + onDestroy?: (swiper: Swiper) => void; + onSetTranslate?: (swiper: Swiper, translate: any) => void; + onSetTransition?: (swiper: Swiper, transition: any) => void; + onAutoplay?: (swiper: Swiper) => void; + onAutoplayStart?: (swiper: Swiper) => void; + onAutoplayStop?: (swiper: Swiper) => void; + onLazyImageLoad?: (swiper: Swiper, slide: any, image: any) => void; + onLazyImageReady?: (swiper: Swiper, slide: any, image: any) => void; + onPaginationRendered?: (swiper: Swiper, paginationContainer: any) => void; // Namespace - wrapperClass?: string; slideClass?: string; slideActiveClass?: string; slideVisibleClass?: string; - slideElement?: string; - noSwipingClass?: string; - paginationElement?: string; - paginationElementClass?: string; - paginationActiveClass?: string; - paginationVisibleClass?: string; - - // Callbacks - queueStartCallbacks?: boolean; - queueEndCallbacks?: boolean; - onTouchStart?: (swiper: Swiper) => void; - onTouchMove?: (swiper: Swiper) => void; - onTouchEnd?: (swiper: Swiper) => void; - onSlideReset?: (swiper: Swiper) => void; - onSlideChangeStart?: (swiper: Swiper) => void; - onSlideChangeEnd?: (swiper: Swiper) => void; - onSlideClick?: (swiper: Swiper) => void; - onSlideTouch?: (swiper: Swiper) => void; - onImagesReady?: (swiper: Swiper) => void; - onMomentumBounce?: (swiper: Swiper) => void; - onResistanceBefore?: (swiper: Swiper, distance: any) => void; - onResistanceAfter?: (swiper: Swiper, distance: any) => void; - - // Slides Loader - loader?: { - slides?: any[]; - slidesHTMLType?: string; - surroundGroups?: number; - logic?: string; - loadAllSlides?: boolean; - }; - - // Plugins - scrollbar?: SwiperScrollbarOptions; + slideDuplicateClass?: string; + slideNextClass?: string; + slidePrevClass?: string; + wrapperClass?: string; + bulletClass?: string; + bulletActiveClass?: string; + paginationHiddenClass?: string; + paginationCurrentClass?: string; + paginationTotalClass?: string; + paginationProgressbarClass?: string; + buttonDisabledClass?: string; } interface SwiperScrollbarOptions { @@ -122,7 +232,7 @@ declare class SwiperSlide { } declare class Swiper { - constructor(container: string|Element, options?: SwiperOptions); + constructor(container: string | Element, options?: SwiperOptions); // Properties width: number; @@ -164,7 +274,7 @@ declare class Swiper { wrapperTransitionEnd(callback: () => void, permanent: boolean): void; // Init/reset - destroy(removeResizeEvent?: boolean): void; + destroy(deleteInstance: boolean, cleanupStyles: boolean): void; reInit(forceCalcSlides?: boolean): void; resizeFix(reInit?: boolean): void; @@ -179,27 +289,46 @@ declare class Swiper { setWrapperTransition(duration: any): void; // Slides API + slides: SwiperSlide[]; - createSlide(html: string, slideClassList?: string, element?: string): SwiperSlide; - appendSlide(html: string, slideClassList?: string, element?: string): SwiperSlide; - appendSlide(slideInstance: HTMLElement): SwiperSlide; - prependSlide(html: string, slideClassList?: string, element?: string): SwiperSlide; - prependSlide(slideInstance: HTMLElement): SwiperSlide; - insertSlideAfter(index: number, html: string, slideClassList?: string, element?: string): SwiperSlide; - insertSlideAfter(index: number, slideInstance: HTMLElement): SwiperSlide; - removeSlide(index: number): boolean; - removeLastSlide(): boolean; + + slidePrev(runCallbacks?: boolean, speed?: number): void; + slideNext(runCallbacks?: boolean, speed?: number): void; + slideTo(index: number, runCallbacks?: boolean, speed?: number): void; + update(updateTranslate?: boolean): void; + onResize(): void; + detachEvents(): void; + attachEvents(): void; + + appendSlide(slides: HTMLElement | string | string[]): void; + prependSlide(slides: HTMLElement | string | string[]): void; + removeSlide(slideIndex: number): void; removeAllSlides(): void; - getSlide(index: number): SwiperSlide; - getLastSlide(): SwiperSlide; - getFirstSlide(): SwiperSlide; + + lockSwipeToNext(): void; + unlockSwipeToNext(): void; + lockSwipeToPrev(): void; + unlockSwipeToPrev(): void; + lockSwipes(): void; + unlockSwipes(): void; + disableMousewheelControl(): void; + enableMousewheelControl(): void; + disableKeyboardControl(): void; + enableKeyboardControl(): void; + disableTouchContro(): void; + enableTouchContro(): void; + unsetGrabCursor(): void; + setGrabCursor(): void; + + plugins?: { + debugger?: (swiper: any, params: any) => void; + }; } declare module "swiper" { const swiper: { - new (element: Element, options?: SwiperOptions): Swiper; - new (element: string, options?: SwiperOptions): Swiper; - }; + new (element: Element | string, options?: SwiperOptions): Swiper; + }; export = swiper; } diff --git a/swiper/swiper-tests.ts b/swiper/swiper-tests.ts index 12abcc8944..6decd155e0 100644 --- a/swiper/swiper-tests.ts +++ b/swiper/swiper-tests.ts @@ -7,324 +7,560 @@ // 01-default.html function defaultDemo() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - loop: true, - grabCursor: true, + var swiper = new Swiper('.swiper-container'); +} +// 02-responsive.html +function responsive() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', paginationClickable: true }); - - $('.arrow-left').on('click', function (e) { - e.preventDefault(); - mySwiper.swipePrev(); - }); - - $('.arrow-right').on('click', function (e) { - e.preventDefault(); - mySwiper.swipeNext(); - }); } - -// 02-vertical-mode.html -function verticalMode() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', +// 03-vertical.html +function vertical() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', paginationClickable: true, - mode: 'vertical' + direction: 'vertical' }); } - -// 03-dynamic-slides.html -function dynamicSlides() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true - }); - - function randomColor() { - var colors = ('blue red green orange pink').split(' '); - return colors[Math.floor(Math.random() * colors.length)]; - } - - var count = 4; - - $('.sdl-append').click(function (e) { - e.preventDefault(); - mySwiper.appendSlide('
Slide ' + (++count) + '
', 'swiper-slide ' + randomColor() + '-slide') - }); - - $('.sdl-prepend').click(function (e) { - e.preventDefault(); - mySwiper.prependSlide('
Slide ' + (++count) + '
', 'swiper-slide ' + randomColor() + '-slide') - }); - - $('.sdl-swap').click(function (e) { - e.preventDefault(); - mySwiper - .getFirstSlide() - .insertAfter(1); - }); - - $('.sdl-insert').click(function (e) { - e.preventDefault(); - mySwiper - .createSlide('
Slide ' + (++count) + '
', 'swiper-slide ' + randomColor() + '-slide') - .insertAfter(0); - }); - - $('.sdl-remove1').click(function (e) { - e.preventDefault(); - mySwiper.removeSlide(0); - }); - - $('.sdl-removel').click(function (e) { - e.preventDefault(); - mySwiper.removeLastSlide(); - }); - - $('.sdl-remove2').click(function (e) { - e.preventDefault(); - mySwiper.removeSlide(1); - }); -} - -// 04-scroll-container.html -function scrollContainer() { - var mySwiper = new Swiper('.swiper-container', { - scrollContainer: true, - scrollbar: { - container: '.swiper-scrollbar' - } - }); -} - -// 05-free-mode.html -function freeMode() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', +// 04-space-between.html +function spaceBetween() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', paginationClickable: true, - freeMode: true, - freeModeFluid: true + spaceBetween: 30, }); } - -// 06-carousel-mode.html -function carouselMode() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true, - slidesPerView: 3 - }); -} - -// 07-carousel-loop.html -function carouselLoop() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true, +// 05-slides-per-view.html +function slidesPerView() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', slidesPerView: 3, + paginationClickable: true, + spaceBetween: 30 + }); +} +// 06-slides-per-view-auto.html +function slidesPerViewAuto() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + slidesPerView: 'auto', + paginationClickable: true, + spaceBetween: 30 + }); +} +// 07-centered.html +function centered() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + slidesPerView: 4, + centeredSlides: true, + paginationClickable: true, + spaceBetween: 30 + }); +} +// 08-centered-auto.html +function centeredAuto() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + slidesPerView: 'auto', + centeredSlides: true, + paginationClickable: true, + spaceBetween: 30 + }); +} +// 09-freemode.html +function freemode() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + slidesPerView: 3, + paginationClickable: true, + spaceBetween: 30, + freeMode: true + }); +} +// 10-slides-per-column.html +function slidesPerColumn() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + slidesPerView: 3, + slidesPerColumn: 2, + paginationClickable: true, + spaceBetween: 30 + }); +} +// 11-nested.html +function nested() { + var swiperH = new Swiper('.swiper-container-h', { + pagination: '.swiper-pagination-h', + paginationClickable: true, + spaceBetween: 50 + }); + var swiperV = new Swiper('.swiper-container-v', { + pagination: '.swiper-pagination-v', + paginationClickable: true, + direction: 'vertical', + spaceBetween: 50 + }); +} +// 12-grab-cursor.html +function grabCursor() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + slidesPerView: 4, + centeredSlides: true, + paginationClickable: true, + spaceBetween: 30, + grabCursor: true + }); +} +// 13-scrollbar.html +function scrollbar() { + var swiper = new Swiper('.swiper-container', { + scrollbar: '.swiper-scrollbar', + scrollbarHide: true, + slidesPerView: 'auto', + centeredSlides: true, + spaceBetween: 30, + grabCursor: true + }); +} +// 14-nav-arrows.html +function navArrows() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + spaceBetween: 30 + }); +} +// 15-infinite-loop.html +function infiniteLoop() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + slidesPerView: 1, + paginationClickable: true, + spaceBetween: 30, loop: true }); } - -// 08-nested.html -function nested() { - var swiperParent = new Swiper('.swiper-parent', { - pagination: '.pagination-parent', +// 16-effect-fade.html +function effectFade() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', paginationClickable: true, - slidesPerView: 3 - }); - - var swiperNested1 = new Swiper('.swiper-nested-1', { - mode: 'vertical', - pagination: '.pagination-nested-1', - paginationClickable: true, - slidesPerView: 2 - }); - - var swiperNested2 = new Swiper('.swiper-nested-2', { - mode: 'vertical', - pagination: '.pagination-nested-2', - paginationClickable: true, - slidesPerView: 2 + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + spaceBetween: 30, + effect: 'fade' }); } - -// 09-nested-loop.html -function nestedLoop() { - var swiperParent = new Swiper('.swiper-parent', { - pagination: '.pagination-parent', +// 17-effect-cube.html +function effectCube() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + effect: 'cube', + grabCursor: true, + cube: { + shadow: true, + slideShadows: true, + shadowOffset: 20, + shadowScale: 0.94 + } + }); +} +// 18-effect-coverflow.html +function effectCoverflow() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + effect: 'coverflow', + grabCursor: true, + centeredSlides: true, + slidesPerView: 'auto', + coverflow: { + rotate: 50, + stretch: 0, + depth: 100, + modifier: 1, + slideShadows: true + } + }); +} +// 19-keyboard-control.html +function keyboardControl() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + slidesPerView: 1, paginationClickable: true, + spaceBetween: 30, + keyboardControl: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + }); +} +// 20-mousewheel-control.html +function mousewheelControl() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + direction: 'vertical', + slidesPerView: 1, + paginationClickable: true, + spaceBetween: 30, + mousewheelControl: true + }); +} +// 21-autoplay.html +function autoplay() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + paginationClickable: true, + spaceBetween: 30, + centeredSlides: true, + autoplay: 2500, + autoplayDisableOnInteraction: false + }); +} +// 22-dynamic-slides.html +function dynamicSlides() { + var appendNumber = 4; + var prependNumber = 1; + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + slidesPerView: 3, + centeredSlides: true, + paginationClickable: true, + spaceBetween: 30, + }); + document.querySelector('.prepend-2-slides').addEventListener('click', e => { + e.preventDefault(); + swiper.prependSlide([ + '
Slide ' + (--prependNumber) + '
', + '
Slide ' + (--prependNumber) + '
' + ]); + }); + document.querySelector('.prepend-slide').addEventListener('click', e => { + e.preventDefault(); + swiper.prependSlide('
Slide ' + (--prependNumber) + '
'); + }); + document.querySelector('.append-slide').addEventListener('click', e => { + e.preventDefault(); + swiper.appendSlide('
Slide ' + (++appendNumber) + '
'); + }); + document.querySelector('.append-2-slides').addEventListener('click', e => { + e.preventDefault(); + swiper.appendSlide([ + '
Slide ' + (++appendNumber) + '
', + '
Slide ' + (++appendNumber) + '
' + ]); + }); +} +// 23-thumbs-gallery-loop.html +function thumbsGalleryLoop() { + var galleryTop = new Swiper('.gallery-top', { + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + spaceBetween: 10, loop: true, - slidesPerView: 3 + loopedSlides: 5, // looped slides should be the same }); + var galleryThumbs = new Swiper('.gallery-thumbs', { + spaceBetween: 10, + slidesPerView: 4, + touchRatio: 0.2, + loop: true, + loopedSlides: 5, // looped slides should be the same + slideToClickedSlide: true + }); + galleryTop.params.control = galleryThumbs; + galleryThumbs.params.control = galleryTop; - var swiperNested1 = new Swiper('.swiper-nested', { - mode: 'vertical', - pagination: '.pagination-nested', - paginationClickable: true, - slidesPerView: 2 - }); } - -// 10-tabs.html -function tabs() { - var tabsSwiper = new Swiper('.swiper-container', { - onlyExternal: true, - speed: 500 +// 23-thumbs-gallery.html +function thumbsGallery() { + var galleryTop = new Swiper('.gallery-top', { + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + spaceBetween: 10, }); - - $(".tabs a").on('touchstart mousedown', function (e) { - e.preventDefault(); - $(".tabs .active").removeClass('active'); - $(this).addClass('active'); - tabsSwiper.swipeTo($(this).index()); - }); - - $(".tabs a").click(function (e) { - e.preventDefault(); - }); -} - -// 11-tabs-feedback.html -function tabsFeedback() { - var tabsSwiper = new Swiper('.swiper-container', { - speed: 500, - onSlideChangeStart: function () { - $(".tabs .active").removeClass('active'); - $(".tabs a").eq(tabsSwiper.activeIndex).addClass('active'); - } - }); - - $(".tabs a").on('touchstart mousedown', function (e) { - e.preventDefault(); - $(".tabs .active").removeClass('active'); - $(this).addClass('active'); - tabsSwiper.swipeTo($(this).index()); - }); - - $(".tabs a").click(function (e) { - e.preventDefault(); - }); -} - -// 12-partial-display.html -function partialDisplay() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true, - slidesPerView: 'auto' - }); -} - -// 13-threshold.html -function threshold() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true, - moveStartThreshold: 100 - }); -} - -// 14-different-widths.html -function differentWidths() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true, - slidesPerView: 'auto' - }); -} - -// 15-centered-slides.html -function centeredSlides() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true, + var galleryThumbs = new Swiper('.gallery-thumbs', { + spaceBetween: 10, centeredSlides: true, - slidesPerView: 'auto' + slidesPerView: 'auto', + touchRatio: 0.2, + slideToClickedSlide: true }); -} + galleryTop.params.control = galleryThumbs; + galleryThumbs.params.control = galleryTop; -// 16-visibility-api.html -function visibilityApi() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', +} +// 24-multiple-swipers.html +function multipleSwipers() { + var swiper1 = new Swiper('.swiper1', { + pagination: '.swiper-pagination1', paginationClickable: true, - centeredSlides: true, - slidesPerView: 3, - watchActiveIndex: true + spaceBetween: 30, + }); + var swiper2 = new Swiper('.swiper2', { + pagination: '.swiper-pagination2', + paginationClickable: true, + spaceBetween: 30, + }); + var swiper3 = new Swiper('.swiper3', { + pagination: '.swiper-pagination3', + paginationClickable: true, + spaceBetween: 30, }); } - -// 17 - responsive.html -function responsive() { - var mySwiper = new Swiper('.swiper-container', { - pagination: '.pagination', - paginationClickable: true +// 25-hash-navigation.html +function hashNavigation() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + spaceBetween: 30, + hashnav: true, + hashnavWatchState: true }); } - - -// -// Scrollbar -// - -// demo-1.html -function demo1() { - var mySwiper = new Swiper('.swiper-container', { - scrollbar: { - container: '.swiper-scrollbar', - hide: false, - draggable: false +// 26-rtl.html +function rtl() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev' + }); +} +// 27-jquery.html +function jquery() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev' + }); +} +// 28-parallax.html +function parallax() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + parallax: true, + speed: 600, + }); +} +// 29-custom-pagination.html +function customPagination() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + paginationBulletRender(swiper, index, className) { + return '' + (index + 1) + ''; } }); } - -// demo-2.html -function demo2() { - var mySwiper = new Swiper('.swiper-container', { - scrollbar: { - container: '.swiper-scrollbar', - hide: false, - draggable: true - } +// 30-lazy-load-images.html +function lazyLoadImages() { + var swiper = new Swiper('.swiper-container', { + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + pagination: '.swiper-pagination', + paginationClickable: true, + // Disable preloading of all images + preloadImages: false, + // Enable lazy loading + lazyLoading: true }); } - -// demo-3.html -function demo3() { - var mySwiper = new Swiper('.swiper-container', { - scrollbar: { - container: '.swiper-scrollbar', - hide: true, - draggable: true - } - }); +// 31-custom-plugin.html +function customPlugin() { + /* ======== + Debugger plugin, simple demo plugin to console.log some of callbacks + ======== */ + Swiper.prototype.plugins.debugger = (swiper: any, params: any) => { + if (!params) return; + // Need to return object with properties that names are the same as callbacks + return { + onInit(swiper: any) { + console.log('onInit'); + }, + onClick(swiper: any, e: any) { + console.log('onClick'); + }, + onTap(swiper: any, e: any) { + console.log('onTap'); + }, + onDoubleTap(swiper: any, e: any) { + console.log('onDoubleTap'); + }, + onSliderMove(swiper: any, e: any) { + console.log('onSliderMove'); + }, + onSlideChangeStart(swiper: any) { + console.log('onSlideChangeStart'); + }, + onSlideChangeEnd(swiper: any) { + console.log('onSlideChangeEnd'); + }, + onTransitionStart(swiper: any) { + console.log('onTransitionStart'); + }, + onTransitionEnd(swiper: any) { + console.log('onTransitionEnd'); + }, + onReachBeginning(swiper: any) { + console.log('onReachBeginning'); + }, + onReachEnd(swiper: any) { + console.log('onReachEnd'); + } + }; + }; } - -// demo-4.html -function demo4() { - var mySwiper = new Swiper('.swiper-container', { - slidesPerView: 3, - scrollbar: { - container: '.swiper-scrollbar', - hide: false, - draggable: true, - snapOnRelease: true - } - }); -} - -// demo-5.html -function demo5() { - var mySwiper = new Swiper('.swiper-container', { - scrollContainer: true, +// 32-scroll-container.html +function scrollContainer() { + var swiper = new Swiper('.swiper-container', { + scrollbar: '.swiper-scrollbar', + direction: 'vertical', + slidesPerView: 'auto', mousewheelControl: true, - mode: 'vertical', - scrollbar: { - container: '.swiper-scrollbar', - hide: true, - draggable: false + freeMode: true + }); +} +// 32-slideable-menu.html +function slideableMenu() { + var toggleMenu = () => { + if (swiper.previousIndex === 0) + swiper.slidePrev(); + } + , menuButton = document.getElementsByClassName('menu-button')[0] + , swiper = new Swiper('.swiper-container', { + slidesPerView: 'auto' + , initialSlide: 1 + , resistanceRatio: .00000000000001 + , onSlideChangeStart: (slider) => { + if (slider.activeIndex === 0) { + menuButton.classList.add('cross'); + menuButton.removeEventListener('click', toggleMenu, false); + } else + menuButton.classList.remove('cross'); + } + , onSlideChangeEnd: (slider) => { + if (slider.activeIndex === 0) + menuButton.removeEventListener('click', toggleMenu, false); + else + menuButton.addEventListener('click', toggleMenu, false); + } + , slideToClickedSlide: true + }); +} +// 33-responsive-breakpoints.html +function responsiveBreakpoints() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + slidesPerView: 5, + spaceBetween: 50, + breakpoints: { + 1024: { + slidesPerView: 4, + spaceBetween: 40 + }, + 768: { + slidesPerView: 3, + spaceBetween: 30 + }, + 640: { + slidesPerView: 2, + spaceBetween: 20 + }, + 320: { + slidesPerView: 1, + spaceBetween: 10 + } } }); -} \ No newline at end of file +} +// 34-autoheight.html +function autoheight() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + paginationClickable: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + autoHeight: true, // enable auto height + }); +} +// 35-effect-flip.html +function effectFlip() { + var swiper = new Swiper('.swiper-container', { + pagination: '.swiper-pagination', + effect: 'flip', + grabCursor: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev' + }); +} +// 36-pagination-fraction.html +function paginationFraction() { + var swiper = new Swiper('.swiper-container', { + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + pagination: '.swiper-pagination', + paginationType: 'fraction' + }); +} +// 37-pagination-progress.html +function paginationProgress() { + var swiper = new Swiper('.swiper-container', { + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + pagination: '.swiper-pagination', + paginationType: 'progress' + }); +} +// 38-history.html +function historyDemo() { + var swiper = new Swiper('.swiper-container', { + spaceBetween: 50, + slidesPerView: 2, + centeredSlides: true, + slideToClickedSlide: true, + grabCursor: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev', + scrollbar: '.swiper-scrollbar', + pagination: '.swiper-pagination', + history: 'slide', + }); +} +// 38-jquery-ie9-loop.html +function jqueryIe9Loop() { + var swiper = new Swiper('.swiper-container', { + loop: true, + pagination: '.swiper-pagination', + paginationClickable: true, + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev' + }); +} +// 39-zoom.html +function zoom() { + var swiper = new Swiper('.swiper-container', { + zoom: true, + pagination: '.swiper-pagination', + nextButton: '.swiper-button-next', + prevButton: '.swiper-button-prev' + }); +} diff --git a/swiper/tslint.json b/swiper/tslint.json new file mode 100644 index 0000000000..0b14fdec0d --- /dev/null +++ b/swiper/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/swiper/v2/index.d.ts b/swiper/v2/index.d.ts new file mode 100644 index 0000000000..a5a98b691f --- /dev/null +++ b/swiper/v2/index.d.ts @@ -0,0 +1,204 @@ +// Type definitions for Swiper 2.0.0 +// Project: https://github.com/nolimits4web/Swiper +// Definitions by: Sebastián Galiano +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +interface SwiperOptions { + speed?: number; + autoplay?: number; + mode?: string; + loop?: boolean; + loopAdditionalSlides?: number; + slidesPerView?: any; + slidesPerGroup?: number; + calculateHeight?: boolean; + updateOnImagesReady?: boolean; + releaseFormElements?: boolean; + watchActiveIndex?: boolean; + visibilityFullFit?: boolean; + autoResize?: boolean; + resizeReInit?: boolean; + DOMAnimation?: boolean; + resistance?: any; + noSwiping?: boolean; + preventLinks?: boolean; + initialSlide?: number; + useCSS3Transforms?: boolean; + + // Free Mode and Scroll Container + freeMode?: boolean; + freeModeFluid?: boolean; + scrollContainer?: boolean; + momentumRatio?: number; + momentumBounce?: boolean; + momentumBounceRatio?: number; + + // Slides offset + centeredSlides?: boolean; + offsetPxBefore?: number; + offsetPxAfter?: number; + offsetSlidesBefore?: number; + offsetSlidesAfter?: number; + + // Touch/mouse interactions + touchRatio?: number; + simulateTouch?: boolean; + onlyExternal?: boolean; + followFinger?: boolean; + grabCursor?: boolean; + shortSwipes?: boolean; + moveStartThreshold?: number; + + // Navigation + keyboardControl?: boolean; + mousewheelControl?: boolean; + nextButton?: string | HTMLElement; + prevButton?: string | HTMLElement; + + // Pagination + pagination?: any; + paginationClickable?: boolean; + paginationAsRange?: boolean; + createPagination?: boolean; + + // Namespace + wrapperClass?: string; + slideClass?: string; + slideActiveClass?: string; + slideVisibleClass?: string; + slideElement?: string; + noSwipingClass?: string; + paginationElement?: string; + paginationElementClass?: string; + paginationActiveClass?: string; + paginationVisibleClass?: string; + + // Callbacks + queueStartCallbacks?: boolean; + queueEndCallbacks?: boolean; + onTouchStart?: (swiper: Swiper) => void; + onTouchMove?: (swiper: Swiper) => void; + onTouchEnd?: (swiper: Swiper) => void; + onSlideReset?: (swiper: Swiper) => void; + onSlideChangeStart?: (swiper: Swiper) => void; + onSlideChangeEnd?: (swiper: Swiper) => void; + onSlideClick?: (swiper: Swiper) => void; + onSlideTouch?: (swiper: Swiper) => void; + onImagesReady?: (swiper: Swiper) => void; + onMomentumBounce?: (swiper: Swiper) => void; + onResistanceBefore?: (swiper: Swiper, distance: any) => void; + onResistanceAfter?: (swiper: Swiper, distance: any) => void; + + // Slides Loader + loader?: { + slides?: any[]; + slidesHTMLType?: string; + surroundGroups?: number; + logic?: string; + loadAllSlides?: boolean; + }; + + // Plugins + scrollbar?: SwiperScrollbarOptions; +} + +interface SwiperScrollbarOptions { + container: string; // Default: '.swiper-scrollbar' + draggable?: boolean; // Default: true + hide?: boolean; // Default: true + snapOnRelease?: boolean; // Default: false +} + +declare class SwiperSlide { + append(): SwiperSlide; + clone(): SwiperSlide; + getWidth(): number; + getHeight(): number; + getOffset(): { top: number; left: number; }; + insertAfter(index: number): SwiperSlide; + prepend(): SwiperSlide; + remove(): void; +} + +declare class Swiper { + constructor(container: string | Element, options?: SwiperOptions); + + // Properties + width: number; + height: number; + params: any; + positions: any; + + // Feature detection + support: { + touch: boolean; + transforms: boolean; + transforms3d: boolean; + transitions: boolean; + }; + + // Browser detection + browser: { + ie8: boolean; + ie10: boolean; + }; + + // Navigation + activeIndex: number; + activeLoopIndex: number; + activeLoaderIndex: number; + previousIndex: number; + swipeNext(internal?: boolean): boolean; + swipePrev(internal?: boolean): boolean; + swipeReset(): boolean; + swipeTo(index: number, speed?: number, runCallbacks?: boolean): boolean; + activeSlide(): SwiperSlide; + updateActiveSlide(index: number): void; + + // Events + touches: any; + isTouched: boolean; + clickedSlideIndex: number; + clickedSlide: SwiperSlide; + wrapperTransitionEnd(callback: () => void, permanent: boolean): void; + + // Init/reset + destroy(removeResizeEvent?: boolean): void; + reInit(forceCalcSlides?: boolean): void; + resizeFix(reInit?: boolean): void; + + // Autoplaying + autoplay: boolean; + startAutoplay(): void; + stopAutoplay(): void; + + // Other methods + getWrapperTranslate(axis: string): number; // 'x' or 'y' + setWrapperTranslate(x: number, y: number, z: number): void; + setWrapperTransition(duration: any): void; + + // Slides API + slides: SwiperSlide[]; + createSlide(html: string, slideClassList?: string, element?: string): SwiperSlide; + appendSlide(html: string, slideClassList?: string, element?: string): SwiperSlide; + appendSlide(slideInstance: HTMLElement): SwiperSlide; + prependSlide(html: string, slideClassList?: string, element?: string): SwiperSlide; + prependSlide(slideInstance: HTMLElement): SwiperSlide; + insertSlideAfter(index: number, html: string, slideClassList?: string, element?: string): SwiperSlide; + insertSlideAfter(index: number, slideInstance: HTMLElement): SwiperSlide; + removeSlide(index: number): boolean; + removeLastSlide(): boolean; + removeAllSlides(): void; + getSlide(index: number): SwiperSlide; + getLastSlide(): SwiperSlide; + getFirstSlide(): SwiperSlide; +} + +declare module "swiper" { + const swiper: { + new (element: Element | string, options?: SwiperOptions): Swiper; + }; + + export = swiper; +} diff --git a/swiper/v2/swiper-tests.ts b/swiper/v2/swiper-tests.ts new file mode 100644 index 0000000000..ad1180a352 --- /dev/null +++ b/swiper/v2/swiper-tests.ts @@ -0,0 +1,330 @@ + +/// + +// +// Main demos +// + +// 01-default.html +function defaultDemo() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + loop: true, + grabCursor: true, + paginationClickable: true + }); + + $('.arrow-left').on('click', e => { + e.preventDefault(); + mySwiper.swipePrev(); + }); + + $('.arrow-right').on('click', e => { + e.preventDefault(); + mySwiper.swipeNext(); + }); +} + +// 02-vertical-mode.html +function verticalMode() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + mode: 'vertical' + }); +} + +// 03-dynamic-slides.html +function dynamicSlides() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true + }); + + function randomColor() { + var colors = ('blue red green orange pink').split(' '); + return colors[Math.floor(Math.random() * colors.length)]; + } + + var count = 4; + + $('.sdl-append').click(e => { + e.preventDefault(); + mySwiper.appendSlide('
Slide ' + (++count) + '
', 'swiper-slide ' + randomColor() + '-slide'); + }); + + $('.sdl-prepend').click(e => { + e.preventDefault(); + mySwiper.prependSlide('
Slide ' + (++count) + '
', 'swiper-slide ' + randomColor() + '-slide'); + }); + + $('.sdl-swap').click(e => { + e.preventDefault(); + mySwiper + .getFirstSlide() + .insertAfter(1); + }); + + $('.sdl-insert').click(e => { + e.preventDefault(); + mySwiper + .createSlide('
Slide ' + (++count) + '
', 'swiper-slide ' + randomColor() + '-slide') + .insertAfter(0); + }); + + $('.sdl-remove1').click(e => { + e.preventDefault(); + mySwiper.removeSlide(0); + }); + + $('.sdl-removel').click(e => { + e.preventDefault(); + mySwiper.removeLastSlide(); + }); + + $('.sdl-remove2').click(e => { + e.preventDefault(); + mySwiper.removeSlide(1); + }); +} + +// 04-scroll-container.html +function scrollContainer() { + var mySwiper = new Swiper('.swiper-container', { + scrollContainer: true, + scrollbar: { + container: '.swiper-scrollbar' + } + }); +} + +// 05-free-mode.html +function freeMode() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + freeMode: true, + freeModeFluid: true + }); +} + +// 06-carousel-mode.html +function carouselMode() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + slidesPerView: 3 + }); +} + +// 07-carousel-loop.html +function carouselLoop() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + slidesPerView: 3, + loop: true + }); +} + +// 08-nested.html +function nested() { + var swiperParent = new Swiper('.swiper-parent', { + pagination: '.pagination-parent', + paginationClickable: true, + slidesPerView: 3 + }); + + var swiperNested1 = new Swiper('.swiper-nested-1', { + mode: 'vertical', + pagination: '.pagination-nested-1', + paginationClickable: true, + slidesPerView: 2 + }); + + var swiperNested2 = new Swiper('.swiper-nested-2', { + mode: 'vertical', + pagination: '.pagination-nested-2', + paginationClickable: true, + slidesPerView: 2 + }); +} + +// 09-nested-loop.html +function nestedLoop() { + var swiperParent = new Swiper('.swiper-parent', { + pagination: '.pagination-parent', + paginationClickable: true, + loop: true, + slidesPerView: 3 + }); + + var swiperNested1 = new Swiper('.swiper-nested', { + mode: 'vertical', + pagination: '.pagination-nested', + paginationClickable: true, + slidesPerView: 2 + }); +} + +// 10-tabs.html +function tabs() { + var tabsSwiper = new Swiper('.swiper-container', { + onlyExternal: true, + speed: 500 + }); + + $(".tabs a").on('touchstart mousedown', e => { + e.preventDefault(); + $(".tabs .active").removeClass('active'); + $(this).addClass('active'); + tabsSwiper.swipeTo($(this).index()); + }); + + $(".tabs a").click(e => { + e.preventDefault(); + }); +} + +// 11-tabs-feedback.html +function tabsFeedback() { + var tabsSwiper = new Swiper('.swiper-container', { + speed: 500, + onSlideChangeStart: () => { + $(".tabs .active").removeClass('active'); + $(".tabs a").eq(tabsSwiper.activeIndex).addClass('active'); + } + }); + + $(".tabs a").on('touchstart mousedown', e => { + e.preventDefault(); + $(".tabs .active").removeClass('active'); + $(this).addClass('active'); + tabsSwiper.swipeTo($(this).index()); + }); + + $(".tabs a").click(e => { + e.preventDefault(); + }); +} + +// 12-partial-display.html +function partialDisplay() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + slidesPerView: 'auto' + }); +} + +// 13-threshold.html +function threshold() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + moveStartThreshold: 100 + }); +} + +// 14-different-widths.html +function differentWidths() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + slidesPerView: 'auto' + }); +} + +// 15-centered-slides.html +function centeredSlides() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + centeredSlides: true, + slidesPerView: 'auto' + }); +} + +// 16-visibility-api.html +function visibilityApi() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true, + centeredSlides: true, + slidesPerView: 3, + watchActiveIndex: true + }); +} + +// 17 - responsive.html +function responsive() { + var mySwiper = new Swiper('.swiper-container', { + pagination: '.pagination', + paginationClickable: true + }); +} + + +// +// Scrollbar +// + +// demo-1.html +function demo1() { + var mySwiper = new Swiper('.swiper-container', { + scrollbar: { + container: '.swiper-scrollbar', + hide: false, + draggable: false + } + }); +} + +// demo-2.html +function demo2() { + var mySwiper = new Swiper('.swiper-container', { + scrollbar: { + container: '.swiper-scrollbar', + hide: false, + draggable: true + } + }); +} + +// demo-3.html +function demo3() { + var mySwiper = new Swiper('.swiper-container', { + scrollbar: { + container: '.swiper-scrollbar', + hide: true, + draggable: true + } + }); +} + +// demo-4.html +function demo4() { + var mySwiper = new Swiper('.swiper-container', { + slidesPerView: 3, + scrollbar: { + container: '.swiper-scrollbar', + hide: false, + draggable: true, + snapOnRelease: true + } + }); +} + +// demo-5.html +function demo5() { + var mySwiper = new Swiper('.swiper-container', { + scrollContainer: true, + mousewheelControl: true, + mode: 'vertical', + scrollbar: { + container: '.swiper-scrollbar', + hide: true, + draggable: false + } + }); +} \ No newline at end of file diff --git a/swiper/v2/tsconfig.json b/swiper/v2/tsconfig.json new file mode 100644 index 0000000000..6ef8f1f2c8 --- /dev/null +++ b/swiper/v2/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "swiper": [ + "swiper/v2" + ], + "swiper/*": [ + "swiper/v2/*" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "swiper-tests.ts" + ] +} \ No newline at end of file diff --git a/swiper/v2/tslint.json b/swiper/v2/tslint.json new file mode 100644 index 0000000000..8ab1b996c9 --- /dev/null +++ b/swiper/v2/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false, + "dt-header": false + } +} diff --git a/systemjs/index.d.ts b/systemjs/index.d.ts index 428e303442..44bee39900 100644 --- a/systemjs/index.d.ts +++ b/systemjs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SystemJS 0.19.29 +// Type definitions for SystemJS 0.20.5 // Project: https://github.com/systemjs/systemjs // Definitions by: Ludovic HENIN , Nathan Walker , Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -29,7 +29,7 @@ declare namespace SystemJSLoader { */ type Transpiler = "plugin-traceur" | "plugin-babel" | "plugin-typescript" | "traceur" | "babel" | "typescript" | boolean; - type ConfigMap = PackageList; + type ConfigMap = PackageList>; type ConfigMeta = PackageList; @@ -257,7 +257,7 @@ declare namespace SystemJSLoader { /** * This represents the System base class, which can be extended or reinstantiated to create a custom System instance. */ - constructor: new () => System; + constructor: new() => System; /** * Deletes a module from the registry by normalized name. @@ -270,6 +270,11 @@ declare namespace SystemJSLoader { get(moduleName: string): any; get(moduleName: string): TModule; + /** + * Returns a clone of the internal SystemJS configuration in use. + */ + getConfig(): Config + /** * Returns whether a given module exists in the registry by normalized module name. */ @@ -282,6 +287,12 @@ declare namespace SystemJSLoader { import(moduleName: string, normalizedParentName?: string): Promise; import(moduleName: string, normalizedParentName?: string): Promise; + /** + * Given any object, returns true if the object is either a SystemJS module or native JavaScript module object, and false otherwise. + * Useful for interop scenarios. + */ + isModule(object: any): boolean; + /** * Given a plain JavaScript object, return an equivalent Module object. * Useful when writing a custom instantiate hook or using System.set. @@ -320,7 +331,6 @@ declare namespace SystemJSLoader { */ loads: PackageList; } - } declare var SystemJS: SystemJSLoader.System; diff --git a/systemjs/systemjs-tests.ts b/systemjs/systemjs-tests.ts index 3c2f8ebadc..fa0ddbedaf 100644 --- a/systemjs/systemjs-tests.ts +++ b/systemjs/systemjs-tests.ts @@ -1,14 +1,12 @@ +import SystemJS = require('systemjs'); - -import System = require('systemjs'); - -System.config({ +SystemJS.config({ baseURL: '/app' }); -System.import('main.js'); +SystemJS.import('main.js'); -System.config({ +SystemJS.config({ // or 'traceur' or 'typescript' transpiler: 'babel', // or traceurOptions or typescriptOptions @@ -18,22 +16,33 @@ System.config({ }); -System.config({ +SystemJS.config({ map: { traceur: 'path/to/traceur.js' } }); -System.transpiler = 'traceur'; +SystemJS.config({ + map: { + 'local/package': { + x: 'vendor/x.js' + }, + 'another/package': { + x: 'vendor/y.js' + } + } +}); + +SystemJS.transpiler = 'traceur'; // loads './app.js' from the current directory -System.import('./app.js').then(function (m) { +SystemJS.import('./app.js').then(function (m) { console.log(m); }); -System.import('lodash').then(function (_) { +SystemJS.import('lodash').then(function (_) { console.log(_); }); -const clonedSystemJS = new System.constructor(); +const clonedSystemJSJS = new SystemJS.constructor(); diff --git a/table/table-tests.ts b/table/table-tests.ts index 4dc6541bb5..f3f4662b69 100644 --- a/table/table-tests.ts +++ b/table/table-tests.ts @@ -8,8 +8,6 @@ const data = [ ['john', 'doe'] ]; -const config: table.TableUserConfig = { - border: border -}; +const config: table.TableUserConfig = { border }; table.table(data, config); diff --git a/tape/index.d.ts b/tape/index.d.ts index 4fc331c402..85af8d06ad 100644 --- a/tape/index.d.ts +++ b/tape/index.d.ts @@ -125,59 +125,59 @@ declare namespace tape { /** * Assert that a === b with an optional description msg. */ - equal(a: any, b: any, msg?: string): void; - equals(a: any, b: any, msg?: string): void; - isEqual(a: any, b: any, msg?: string): void; - is(a: any, b: any, msg?: string): void; - strictEqual(a: any, b: any, msg?: string): void; - strictEquals(a: any, b: any, msg?: string): void; + equal(actual: any, expected: any, msg?: string): void; + equals(actual: any, expected: any, msg?: string): void; + isEqual(actual: any, expected: any, msg?: string): void; + is(actual: any, expected: any, msg?: string): void; + strictEqual(actual: any, expected: any, msg?: string): void; + strictEquals(actual: any, expected: any, msg?: string): void; /** * Assert that a !== b with an optional description msg. */ - notEqual(a: any, b: any, msg?: string): void; - notEquals(a: any, b: any, msg?: string): void; - notStrictEqual(a: any, b: any, msg?: string): void; - notStrictEquals(a: any, b: any, msg?: string): void; - isNotEqual(a: any, b: any, msg?: string): void; - isNot(a: any, b: any, msg?: string): void; - not(a: any, b: any, msg?: string): void; - doesNotEqual(a: any, b: any, msg?: string): void; - isInequal(a: any, b: any, msg?: string): void; + notEqual(actual: any, expected: any, msg?: string): void; + notEquals(actual: any, expected: any, msg?: string): void; + notStrictEqual(actual: any, expected: any, msg?: string): void; + notStrictEquals(actual: any, expected: any, msg?: string): void; + isNotEqual(actual: any, expected: any, msg?: string): void; + isNot(actual: any, expected: any, msg?: string): void; + not(actual: any, expected: any, msg?: string): void; + doesNotEqual(actual: any, expected: any, msg?: string): void; + isInequal(actual: any, expected: any, msg?: string): void; /** * Assert that a and b have the same structure and nested values using node's deepEqual() algorithm with strict comparisons (===) on leaf nodes and an optional description msg. */ - deepEqual(a: any, b: any, msg?: string): void; - deepEquals(a: any, b: any, msg?: string): void; - isEquivalent(a: any, b: any, msg?: string): void; - same(a: any, b: any, msg?: string): void; + deepEqual(actual: any, expected: any, msg?: string): void; + deepEquals(actual: any, expected: any, msg?: string): void; + isEquivalent(actual: any, expected: any, msg?: string): void; + same(actual: any, expected: any, msg?: string): void; /** * Assert that a and b do not have the same structure and nested values using node's deepEqual() algorithm with strict comparisons (===) on leaf nodes and an optional description msg. */ - notDeepEqual(a: any, b: any, msg?: string): void; - notEquivalent(a: any, b: any, msg?: string): void; - notDeeply(a: any, b: any, msg?: string): void; - notSame(a: any, b: any, msg?: string): void; - isNotDeepEqual(a: any, b: any, msg?: string): void; - isNotDeeply(a: any, b: any, msg?: string): void; - isNotEquivalent(a: any, b: any, msg?: string): void; - isInequivalent(a: any, b: any, msg?: string): void; + notDeepEqual(actual: any, expected: any, msg?: string): void; + notEquivalent(actual: any, expected: any, msg?: string): void; + notDeeply(actual: any, expected: any, msg?: string): void; + notSame(actual: any, expected: any, msg?: string): void; + isNotDeepEqual(actual: any, expected: any, msg?: string): void; + isNotDeeply(actual: any, expected: any, msg?: string): void; + isNotEquivalent(actual: any, expected: any, msg?: string): void; + isInequivalent(actual: any, expected: any, msg?: string): void; /** * Assert that a and b have the same structure and nested values using node's deepEqual() algorithm with loose comparisons (==) on leaf nodes and an optional description msg. */ - deepLooseEqual(a: any, b: any, msg?: string): void; - looseEqual(a: any, b: any, msg?: string): void; - looseEquals(a: any, b: any, msg?: string): void; + deepLooseEqual(actual: any, expected: any, msg?: string): void; + looseEqual(actual: any, expected: any, msg?: string): void; + looseEquals(actual: any, expected: any, msg?: string): void; /** * Assert that a and b do not have the same structure and nested values using node's deepEqual() algorithm with loose comparisons (==) on leaf nodes and an optional description msg. */ - notDeepLooseEqual(a: any, b: any, msg?: string): void; - notLooseEqual(a: any, b: any, msg?: string): void; - notLooseEquals(a: any, b: any, msg?: string): void; + notDeepLooseEqual(actual: any, expected: any, msg?: string): void; + notLooseEqual(actual: any, expected: any, msg?: string): void; + notLooseEquals(actual: any, expected: any, msg?: string): void; /** * Assert that the function call fn() throws an exception. diff --git a/tcomb/index.d.ts b/tcomb/index.d.ts index 4b00616e26..abfa163b98 100644 --- a/tcomb/index.d.ts +++ b/tcomb/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for tcomb v1.0.3 +// Type definitions for tcomb 1.0 // Project: http://gcanti.github.io/tcomb/guide/index.html // Definitions by: Hans Windhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,14 +26,14 @@ declare namespace TComb { Func: Func_Static; func: { (domain: TCombBase[], codomain: TCombBase, name?: string): Func_Static; - (domain: TCombBase, codomain: TCombBase, name?: string) : Func_Static; - } + (domain: TCombBase, codomain: TCombBase, name?: string): Func_Static; + }; Err: Err_Static; Re: Re_Static; Dat: Dat_Static; Type: Type_Static; - irreducible: (name: string, is: TypePredicate) => TCombBase; - struct: (props: Object, name?: string) => Struct_Static; + irreducible(name: string, is: TypePredicate): TCombBase; + struct(props: Object, name?: string): Struct_Static; Union: Union_Static; Maybe: Maybe_Static; @@ -43,15 +43,15 @@ declare namespace TComb { maybe(type: TCombBase, name?: string): Maybe_Static; Tuple: Tuple_Static; - tuple:(types: TCombBase[], name?: string)=> Tuple_Static; + tuple(types: TCombBase[], name?: string): Tuple_Static; Subtype: Subtype_Static; List: List_Static; - list:(type: TCombBase, name?: string)=> List_Static; + list(type: TCombBase, name?: string): List_Static; Dict: Dict_Static; - dict:(domain: TCombBase, codomain: TCombBase, name?: string)=> Dict_Static; + dict(domain: TCombBase, codomain: TCombBase, name?: string): Dict_Static; subtype(type: TCombBase, predicate: TypePredicate, name?: string): Subtype_Static; @@ -260,7 +260,7 @@ declare namespace TComb { * @param name - Useful for debugging purposes. */ - export module enums { + export namespace enums { /** * @param keys - Array of enums. * @param name - Useful for debugging purposes. diff --git a/tcomb/tcomb-tests.ts b/tcomb/tcomb-tests.ts index d34d6feec8..02982faae7 100644 --- a/tcomb/tcomb-tests.ts +++ b/tcomb/tcomb-tests.ts @@ -6,9 +6,11 @@ // tests adapted from/for tcomb's test folder +// tslint:disable:no-construct + 'use strict'; import assert = require('assert'); -var t = require('../index'); +import t = require("tcomb"); var Any = t.Any; var Nil = t.Nil; @@ -38,11 +40,11 @@ var format = t.format; // setup // -var ok = function (x:any) { assert.strictEqual(true, x); }; -var ko = function (x:any) { assert.strictEqual(false, x); }; +var ok = (x: any) => { assert.strictEqual(true, x); }; +var ko = (x: any) => { assert.strictEqual(false, x); }; var eq = assert.deepEqual; -var throwsWithMessage = function (f:any, message:any) { - assert.throws(f, function (err:any) { +var throwsWithMessage = (f: any, message: any) => { + assert.throws(f, (err: any) => { ok(err instanceof Error); eq(err.message, message); return true; @@ -50,30 +52,30 @@ var throwsWithMessage = function (f:any, message:any) { }; var doesNotThrow = assert.doesNotThrow; -var noop = function () {}; +var noop = () => {}; var Point = struct({ x: Num, y: Num }); -describe('update', function () { +describe('update', () => { var update = t.update; var Tuple = tuple([Str, Num]); var List = list(Num); var Dict = dict(Str, Num); - it('should handle $set command', function () { + it('should handle $set command', () => { var instance = 1; var actual = update(instance, {$set: 2}); eq(actual, 2); var instance2 = [1, 2, 3]; - actual = update(instance2, {1: {'$set': 4}}); + actual = update(instance2, {1: {$set: 4}}); eq(instance2, [1, 2, 3]); eq(actual, [1, 4, 3]); }); - it('$set and null value, fix #65', function () { + it('$set and null value, fix #65', () => { var NullStruct = struct({a: Num, b: maybe(Num)}); var instance = new NullStruct({a: 1}); var updated = update(instance, {b: {$set: 2}}); @@ -81,76 +83,74 @@ describe('update', function () { eq(updated, {a: 1, b: 2}); }); - it('should handle $apply command', function () { - var $apply = function (n:any) { return n + 1; }; + it('should handle $apply command', () => { + var $apply = (n: any) => n + 1; var instance = 1; - var actual = update(instance, {$apply: $apply}); + var actual = update(instance, {$apply}); eq(actual, 2); var instance2 = [1, 2, 3]; - actual = update(instance2, {1: {'$apply': $apply}}); + actual = update(instance2, {1: {$apply}}); eq(instance2, [1, 2, 3]); eq(actual, [1, 3, 3]); }); - it('should handle $unshift command', function () { - var actual = update([1, 2, 3], {'$unshift': [4]}); + it('should handle $unshift command', () => { + var actual = update([1, 2, 3], {$unshift: [4]}); eq(actual, [4, 1, 2, 3]); - actual = update([1, 2, 3], {'$unshift': [4, 5]}); + actual = update([1, 2, 3], {$unshift: [4, 5]}); eq(actual, [4, 5, 1, 2, 3]); - actual = update([1, 2, 3], {'$unshift': [[4, 5]]}); + actual = update([1, 2, 3], {$unshift: [[4, 5]]}); eq(actual, [[4, 5], 1, 2, 3]); }); - it('should handle $push command', function () { - var actual = update([1, 2, 3], {'$push': [4]}); + it('should handle $push command', () => { + var actual = update([1, 2, 3], {$push: [4]}); eq(actual, [1, 2, 3, 4]); - actual = update([1, 2, 3], {'$push': [4, 5]}); + actual = update([1, 2, 3], {$push: [4, 5]}); eq(actual, [1, 2, 3, 4, 5]); - actual = update([1, 2, 3], {'$push': [[4, 5]]}); + actual = update([1, 2, 3], {$push: [[4, 5]]}); eq(actual, [1, 2, 3, [4, 5]]); }); - it('should handle $splice command', function () { + it('should handle $splice command', () => { var instance = [1, 2, {a: [12, 17, 15]}]; var actual = update(instance, {2: {a: {$splice: [[1, 1, 13, 14]]}}}); eq(instance, [1, 2, {a: [12, 17, 15]}]); eq(actual, [1, 2, {a: [12, 13, 14, 15]}]); }); - it('should handle $remove command', function () { + it('should handle $remove command', () => { var instance = {a: 1, b: 2}; - var actual = update(instance, {'$remove': ['a']}); + var actual = update(instance, {$remove: ['a']}); eq(instance, {a: 1, b: 2}); eq(actual, {b: 2}); }); - it('should handle $swap command', function () { + it('should handle $swap command', () => { var instance = [1, 2, 3, 4]; - var actual = update(instance, {'$swap': {from: 1, to: 2}}); + var actual = update(instance, {$swap: {from: 1, to: 2}}); eq(instance, [1, 2, 3, 4]); eq(actual, [1, 3, 2, 4]); }); - describe('structs', function () { + describe('structs', () => { var instance = new Point({x: 0, y: 1}); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {x: {$set: 1}}); eq(instance, {x: 0, y: 1}); eq(updated, {x: 1, y: 1}); }); - it('should handle $apply command', function () { - var updated = update(instance, {x: {$apply: function (x:any) { - return x + 2; - }}}); + it('should handle $apply command', () => { + var updated = update(instance, {x: {$apply: (x: any) => x + 2}}); eq(instance, {x: 0, y: 1}); eq(updated, {x: 2, y: 1}); }); - it('should handle $merge command', function () { - var updated = update(instance, {'$merge': {x: 2, y: 2}}); + it('should handle $merge command', () => { + var updated = update(instance, {$merge: {x: 2, y: 2}}); eq(instance, {x: 0, y: 1}); eq(updated, {x: 2, y: 2}); var Nested = struct({ @@ -162,78 +162,78 @@ describe('update', function () { }) }); instance = new Nested({a: 1, b: {c: 2, d: 3, e: 4}}); - updated = update(instance, {b: {'$merge': {c: 5, e: 6}}}); + updated = update(instance, {b: {$merge: {c: 5, e: 6}}}); eq(instance, {a: 1, b: {c: 2, d: 3, e: 4}}); eq(updated, {a: 1, b: {c: 5, d: 3, e: 6}}); }); }); - describe('tuples', function () { + describe('tuples', () => { var instance = Tuple(['a', 1]); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {0: {$set: 'b'}}); eq(updated, ['b', 1]); }); }); - describe('lists', function () { + describe('lists', () => { var instance = List([1, 2, 3, 4]); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {2: {$set: 5}}); eq(updated, [1, 2, 5, 4]); }); - it('should handle $splice command', function () { + it('should handle $splice command', () => { var updated = update(instance, {$splice: [[1, 2, 5, 6]]}); eq(updated, [1, 5, 6, 4]); }); - it('should handle $concat command', function () { + it('should handle $concat command', () => { var updated = update(instance, {$push: [5]}); eq(updated, [1, 2, 3, 4, 5]); updated = update(instance, {$push: [5, 6]}); eq(updated, [1, 2, 3, 4, 5, 6]); }); - it('should handle $prepend command', function () { + it('should handle $prepend command', () => { var updated = update(instance, {$unshift: [5]}); eq(updated, [5, 1, 2, 3, 4]); updated = update(instance, {$unshift: [5, 6]}); eq(updated, [5, 6, 1, 2, 3, 4]); }); - it('should handle $swap command', function () { + it('should handle $swap command', () => { var updated = update(instance, {$swap: {from: 1, to: 2}}); eq(updated, [1, 3, 2, 4]); }); }); - describe('dicts', function () { + describe('dicts', () => { var instance = Dict({a: 1, b: 2}); - it('should handle $set command', function () { + it('should handle $set command', () => { var updated = update(instance, {a: {$set: 2}}); eq(updated, {a: 2, b: 2}); }); - it('should handle $remove command', function () { + it('should handle $remove command', () => { var updated = update(instance, {$remove: ['a']}); eq(updated, {b: 2}); }); }); - describe('memory saving', function () { + describe('memory saving', () => { - it('should reuse members that are not updated', function () { + it('should reuse members that are not updated', () => { var Struct = struct({ a: Num, b: Str, @@ -244,7 +244,7 @@ describe('update', function () { a: 1, b: 'one', c: [1000, 1000000] - },{ + }, { a: 2, b: 'two', c: [2000, 2000000] @@ -262,9 +262,9 @@ describe('update', function () { }); }); - describe('all together now', function () { + describe('all together now', () => { - it('should handle mixed commands', function () { + it('should handle mixed commands', () => { var Struct = struct({ a: Num, b: Tuple, @@ -291,7 +291,7 @@ describe('update', function () { }); }); - it('should handle nested structures', function () { + it('should handle nested structures', () => { var Struct = struct({ a: struct({ b: tuple([ @@ -323,42 +323,42 @@ describe('update', function () { // assert // -describe('assert', function () { +describe('assert', () => { var assert = t.assert; - it('should nor throw when guard is true', function () { + it('should nor throw when guard is true', () => { assert(true); }); - it('should throw a default message', function () { - throwsWithMessage(function () { + it('should throw a default message', () => { + throwsWithMessage(() => { assert(1 === 2 + 1); }, 'assert failed'); }); - it('should throw the specified message', function () { - throwsWithMessage(function () { + it('should throw the specified message', () => { + throwsWithMessage(() => { assert(1 === 2 + 1, 'my message'); }, 'my message'); }); - it('should format the specified message', function () { - throwsWithMessage(function () { + it('should format the specified message', () => { + throwsWithMessage(() => { assert(1 === 2 + 1, '%s !== %s', 1, 2); }, '1 !== 2'); }); - it('should handle custom fail behaviour', function () { + it('should handle custom fail behaviour', () => { var fail = t.fail; - t.fail = function (message) { + t.fail = message => { try { throw new Error(message); } catch (e) { eq(e.message, 'report error'); } }; - doesNotThrow(function () { + doesNotThrow(() => { assert(1 === 2 + 1, 'report error'); }); t.fail = fail; @@ -370,48 +370,48 @@ describe('assert', function () { // utils // -describe('format(str, [...])', function () { +describe('format(str, [...])', () => { - it('should format strings', function () { + it('should format strings', () => { eq(format('%s', 'a'), 'a'); eq(format('%s', 2), '2'); eq(format('%s === %s', 1, 1), '1 === 1'); }); - it('should format JSON', function () { + it('should format JSON', () => { eq(format('%j', {a: 1}), '{"a":1}'); }); - it('should handle undefined formatters', function () { + it('should handle undefined formatters', () => { eq(format('%o', 'a'), '%o a'); }); - it('should handle escaping %', function () { + it('should handle escaping %', () => { eq(format('%%s'), '%s'); }); - it('should not consume an argument with a single %', function () { + it('should not consume an argument with a single %', () => { eq(format('%s%', '100'), '100%'); }); - it('should handle less arguments than placeholders', function () { + it('should handle less arguments than placeholders', () => { eq(format('%s %s', 'a'), 'a %s'); }); - it('should handle more arguments than placeholders', function () { + it('should handle more arguments than placeholders', () => { eq(format('%s', 'a', 'b', 'c'), 'a b c'); }); - it('should be extensible', function () { - (format).formatters.l = function (x:any) { return x.length; }; + it('should be extensible', () => { + ( format).formatters.l = (x: any) => x.length; eq(format('%l', ['a', 'b', 'c']), '3'); }); }); -describe('mixin(x, y, [overwrite])', function () { +describe('mixin(x, y, [overwrite])', () => { - it('should mix two objects', function () { + it('should mix two objects', () => { var o1 = {a: 1}; var o2 = {b: 2}; var o3 = mixin(o1, o2); @@ -420,15 +420,15 @@ describe('mixin(x, y, [overwrite])', function () { eq(o3.b, 2); }); - it('should throw if a property already exists', function () { - throwsWithMessage(function () { + it('should throw if a property already exists', () => { + throwsWithMessage(() => { var o1 = {a: 1}; var o2 = {a: 2, b: 2}; mixin(o1, o2); }, 'Cannot overwrite property a'); }); - it('should not throw if a property already exists but overwrite = true', function () { + it('should not throw if a property already exists but overwrite = true', () => { var o1 = {a: 1}; var o2 = {a: 2, b: 2}; var o3 = mixin(o1, o2, true); @@ -436,38 +436,38 @@ describe('mixin(x, y, [overwrite])', function () { eq(o3.b, 2); }); - it('should not mix prototype properties', function () { + it('should not mix prototype properties', () => { function F() {} F.prototype.method = noop; - var source = new (F)(); + var source = new ( F)(); var target = {}; mixin(target, source); - eq((target).method, undefined); + eq(( target).method, undefined); }); }); -describe('getFunctionName(f, [defaultName])', function () { +describe('getFunctionName(f, [defaultName])', () => { var getFunctionName = t.getFunctionName; - it('should return the name of a named function', function () { + it('should return the name of a named function', () => { eq(getFunctionName(function myfunc(){}), 'myfunc'); }); - it('should return the value of `displayName` if specified', function () { + it('should return the value of `displayName` if specified', () => { var f = function myfunc(){}; - (f).displayName = 'mydisplayname'; + ( f).displayName = 'mydisplayname'; eq(getFunctionName(f), 'mydisplayname'); }); - it('should fallback on function arity if nothing is specified', function () { - eq(getFunctionName(function (a:any, b:any, c:any) { return a + b + c; }), ''); + it('should fallback on function arity if nothing is specified', () => { + eq(getFunctionName((a: any, b: any, c: any) => a + b + c), ''); }); }); -describe('getTypeName(type)', function () { +describe('getTypeName(type)', () => { var UnnamedStruct = struct({}); var NamedStruct = struct({}, 'NamedStruct'); @@ -480,7 +480,7 @@ describe('getTypeName(type)', function () { var UnnamedTuple = tuple([Str, Num]); var NamedTuple = tuple([Str, Num], 'NamedTuple'); var UnnamedSubtype = subtype(Str, function notEmpty(x) { return x !== ''; }); - var NamedSubtype = subtype(Str, function (x) { return x !== ''; }, 'NamedSubtype'); + var NamedSubtype = subtype(Str, x => x !== '', 'NamedSubtype'); var UnnamedList = list(Str); var NamedList = list(Str, 'NamedList'); var UnnamedDict = dict(Str, Str); @@ -488,7 +488,7 @@ describe('getTypeName(type)', function () { var UnnamedFunc = func(Str, Str); var NamedFunc = func(Str, Str, 'NamedFunc'); - it('should return the name of a named type', function () { + it('should return the name of a named type', () => { eq(getTypeName(NamedStruct), 'NamedStruct'); eq(getTypeName(NamedUnion), 'NamedUnion'); eq(getTypeName(NamedMaybe), 'NamedMaybe'); @@ -500,7 +500,7 @@ describe('getTypeName(type)', function () { eq(getTypeName(NamedFunc), 'NamedFunc'); }); - it('should return a meaningful name of a unnamed type', function () { + it('should return a meaningful name of a unnamed type', () => { eq(getTypeName(UnnamedStruct), '{}'); eq(getTypeName(UnnamedUnion), 'Str | Num'); eq(getTypeName(UnnamedMaybe), '?Str'); @@ -518,29 +518,27 @@ describe('getTypeName(type)', function () { // Any // -describe('Any', function () { +describe('Any', () => { var T = Any; - describe('constructor', function () { + describe('constructor', () => { - it('should behave like identity', function () { + it('should behave like identity', () => { eq(Any('a'), 'a'); }); - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var x = new (T)(); - /* jshint ignore:end */ + it('should throw if used with new', () => { + throwsWithMessage(() => { + var x = new ( T)(); }, 'Operator `new` is forbidden for type `Any`'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should always return true', function () { + it('should always return true', () => { ok(T.is(null)); ok(T.is(undefined)); ok(T.is(0)); @@ -562,7 +560,7 @@ describe('Any', function () { // irreducible types // -describe('irreducible types constructors', function () { +describe('irreducible types constructors', () => { [ {T: Nil, x: null}, @@ -575,19 +573,17 @@ describe('irreducible types constructors', function () { {T: Err, x: new Error()}, {T: Re, x: /a/}, {T: Dat, x: new Date()} - ].forEach(function (o) { + ].forEach(o => { var { T, x } = o; - it('should accept only valid values', function () { - eq((T)(x), x); + it('should accept only valid values', () => { + eq(( T)(x), x); }); - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var x = new (T) (); - /* jshint ignore:end */ + it('should throw if used with new', () => { + throwsWithMessage(() => { + var x = new ( T) (); }, 'Operator `new` is forbidden for type `' + getTypeName(T) + '`'); }); @@ -595,16 +591,16 @@ describe('irreducible types constructors', function () { }); -describe('Nil', function () { +describe('Nil', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is null or undefined', function () { + it('should return true when x is null or undefined', () => { ok(Nil.is(null)); ok(Nil.is(undefined)); }); - it('should return false when x is neither null nor undefined', function () { + it('should return false when x is neither null nor undefined', () => { ko(Nil.is(0)); ko(Nil.is(true)); ko(Nil.is('')); @@ -621,16 +617,16 @@ describe('Nil', function () { }); -describe('Bool', function () { +describe('Bool', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is true or false', function () { + it('should return true when x is true or false', () => { ok(Bool.is(true)); ok(Bool.is(false)); }); - it('should return false when x is neither true nor false', function () { + it('should return false when x is neither true nor false', () => { ko(Bool.is(null)); ko(Bool.is(undefined)); ko(Bool.is(0)); @@ -648,19 +644,17 @@ describe('Bool', function () { }); -describe('Num', function () { +describe('Num', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a number', function () { + it('should return true when x is a number', () => { ok(Num.is(0)); ok(Num.is(1)); - /* jshint ignore:start */ ko(Num.is(new Number(1))); - /* jshint ignore:end */ }); - it('should return false when x is not a number', function () { + it('should return false when x is not a number', () => { ko(Num.is(NaN)); ko(Num.is(Infinity)); ko(Num.is(-Infinity)); @@ -681,19 +675,17 @@ describe('Num', function () { }); -describe('Str', function () { +describe('Str', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a string', function () { + it('should return true when x is a string', () => { ok(Str.is('')); ok(Str.is('a')); - /* jshint ignore:start */ ko(Str.is(new String('a'))); - /* jshint ignore:end */ }); - it('should return false when x is not a string', function () { + it('should return false when x is not a string', () => { ko(Str.is(NaN)); ko(Str.is(Infinity)); ko(Str.is(-Infinity)); @@ -714,15 +706,15 @@ describe('Str', function () { }); -describe('Arr', function () { +describe('Arr', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an array', function () { + it('should return true when x is an array', () => { ok(Arr.is([])); }); - it('should return false when x is not an array', function () { + it('should return false when x is not an array', () => { ko(Arr.is(NaN)); ko(Arr.is(Infinity)); ko(Arr.is(-Infinity)); @@ -743,17 +735,17 @@ describe('Arr', function () { }); -describe('Obj', function () { +describe('Obj', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an object', function () { + it('should return true when x is an object', () => { function A() {} ok(Obj.is({})); - ok(Obj.is(new (A)())); + ok(Obj.is(new ( A)())); }); - it('should return false when x is not an object', function () { + it('should return false when x is not an object', () => { ko(Obj.is(null)); ko(Obj.is(undefined)); ko(Obj.is(0)); @@ -766,28 +758,24 @@ describe('Obj', function () { }); -describe('Func', function () { +describe('Func', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a function', function () { + it('should return true when x is a function', () => { ok(Func.is(noop)); - /* jshint ignore:start */ ok(Func.is(new Function())); - /* jshint ignore:end */ }); - it('should return false when x is not a function', function () { + it('should return false when x is not a function', () => { ko(Func.is(null)); ko(Func.is(undefined)); ko(Func.is(0)); ko(Func.is('')); ko(Func.is([])); - /* jshint ignore:start */ ko(Func.is(new String('1'))); ko(Func.is(new Number(1))); ko(Func.is(new Boolean())); - /* jshint ignore:end */ ko(Func.is(/a/)); ko(Func.is(new RegExp('a'))); ko(Func.is(new Error())); @@ -798,25 +786,23 @@ describe('Func', function () { }); -describe('Err', function () { +describe('Err', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an error', function () { + it('should return true when x is an error', () => { ok(Err.is(new Error())); }); - it('should return false when x is not an error', function () { + it('should return false when x is not an error', () => { ko(Err.is(null)); ko(Err.is(undefined)); ko(Err.is(0)); ko(Err.is('')); ko(Err.is([])); - /* jshint ignore:start */ ko(Err.is(new String('1'))); ko(Err.is(new Number(1))); ko(Err.is(new Boolean())); - /* jshint ignore:end */ ko(Err.is(/a/)); ko(Err.is(new RegExp('a'))); ko(Err.is(new Date())); @@ -826,26 +812,24 @@ describe('Err', function () { }); -describe('Re', function () { +describe('Re', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a regexp', function () { + it('should return true when x is a regexp', () => { ok(Re.is(/a/)); ok(Re.is(new RegExp('a'))); }); - it('should return false when x is not a regexp', function () { + it('should return false when x is not a regexp', () => { ko(Re.is(null)); ko(Re.is(undefined)); ko(Re.is(0)); ko(Re.is('')); ko(Re.is([])); - /* jshint ignore:start */ ko(Re.is(new String('1'))); ko(Re.is(new Number(1))); ko(Re.is(new Boolean())); - /* jshint ignore:end */ ko(Re.is(new Error())); ko(Re.is(new Date())); }); @@ -854,25 +838,23 @@ describe('Re', function () { }); -describe('Dat', function () { +describe('Dat', () => { - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is a Dat', function () { + it('should return true when x is a Dat', () => { ok(Dat.is(new Date())); }); - it('should return false when x is not a Dat', function () { + it('should return false when x is not a Dat', () => { ko(Dat.is(null)); ko(Dat.is(undefined)); ko(Dat.is(0)); ko(Dat.is('')); ko(Dat.is([])); - /* jshint ignore:start */ ko(Dat.is(new String('1'))); ko(Dat.is(new Number(1))); ko(Dat.is(new Boolean())); - /* jshint ignore:end */ ko(Dat.is(new Error())); ko(Dat.is(/a/)); ko(Dat.is(new RegExp('a'))); @@ -886,30 +868,30 @@ describe('Dat', function () { // struct // -describe('struct', function () { +describe('struct', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (struct)(); + throwsWithMessage(() => { + ( struct)(); }, 'Invalid argument `props` = `undefined` supplied to `struct` combinator'); - throwsWithMessage(function () { + throwsWithMessage(() => { struct({a: null}); }, 'Invalid argument `props` = `[object Object]` supplied to `struct` combinator'); - throwsWithMessage(function () { - (struct)({}, 1); + throwsWithMessage(() => { + ( struct)({}, 1); }, 'Invalid argument `name` = `1` supplied to `struct` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should be idempotent', function () { + it('should be idempotent', () => { var T = Point; var p1 = T({x: 0, y: 0}); var p2 = T(p1); @@ -918,29 +900,29 @@ describe('struct', function () { eq(p2 === p1, true); }); - it('should accept only valid values', function () { - throwsWithMessage(function () { + it('should accept only valid values', () => { + throwsWithMessage(() => { Point(1); }, 'Invalid argument `value` = `1` supplied to struct type `{x: Num, y: Num}`'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the struct', function () { + it('should return true when x is an instance of the struct', () => { var p = new Point({ x: 1, y: 2 }); ok(Point.is(p)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = struct({name: Str}); var instance = new Type({name: 'Giulio'}); - it('should return a new instance', function () { + it('should return a new instance', () => { var newInstance = Type.update(instance, {name: {$set: 'Canti'}}); ok(Type.is(newInstance)); eq( ( instance).name, 'Giulio'); @@ -949,31 +931,31 @@ describe('struct', function () { }); - describe('#extend(props, [name])', function () { + describe('#extend(props, [name])', () => { - it('should extend an existing struct', function () { + it('should extend an existing struct', () => { var Point = struct({ x: Num, y: Num }, 'Point'); var Point3D = Point.extend({z: Num}, 'Point3D'); eq(getTypeName(Point3D), 'Point3D'); - eq((Point3D).meta.props.x, Num); - eq((Point3D).meta.props.y, Num); - eq((Point3D).meta.props.z, Num); + eq(( Point3D).meta.props.x, Num); + eq(( Point3D).meta.props.y, Num); + eq(( Point3D).meta.props.z, Num); }); - it('should handle an array as argument', function () { + it('should handle an array as argument', () => { var Type = struct({a: Str}, 'Type'); var Mixin = [{b: Num, c: Bool}]; var NewType = Type.extend(Mixin, 'NewType'); eq(getTypeName(NewType), 'NewType'); - eq((NewType).meta.props.a, Str); - eq((NewType).meta.props.b, Num); - eq((NewType).meta.props.c, Bool); + eq(( NewType).meta.props.a, Str); + eq(( NewType).meta.props.b, Num); + eq(( NewType).meta.props.c, Bool); }); - it('should handle a struct (or list of structs) as argument', function () { + it('should handle a struct (or list of structs) as argument', () => { var A = struct({a: Str}, 'A'); var B = struct({b: Str}, 'B'); var C = struct({c: Str}, 'C'); @@ -987,18 +969,20 @@ describe('struct', function () { }); }); - it('should support prototypal inheritance', function () { + it('should support prototypal inheritance', () => { + interface Rectangle { w: number; h: number; area(): number; }; var Rectangle = struct({ w: Num, h: Num }, 'Rectangle'); - Rectangle.prototype.area = function () { + Rectangle.prototype.area = function(this: Rectangle) { return this.w * this.h; }; + interface Cube extends Rectangle { l: number; } var Cube = Rectangle.extend({ l: Num }); - Cube.prototype.volume = function () { + Cube.prototype.volume = function(this: Cube) { return this.area() * this.l; }; @@ -1008,8 +992,8 @@ describe('struct', function () { assert('function' === typeof Cube.prototype.volume); assert(Cube.prototype.constructor === Cube); - var c = new Cube({w:2, h:2, l:2}); - eq((c).volume(), 8); + var c = new Cube({w: 2, h: 2, l: 2}); + eq(( c).volume(), 8); }); }); @@ -1020,46 +1004,44 @@ describe('struct', function () { // enums // -describe('enums', function () { +describe('enums', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (enums)(); + throwsWithMessage(() => { + ( enums)(); }, 'Invalid argument `map` = `undefined` supplied to `enums` combinator'); - throwsWithMessage(function () { - (enums)({}, 1); + throwsWithMessage(() => { + ( enums)({}, 1); }, 'Invalid argument `name` = `1` supplied to `enums` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var T = enums({a: 0}, 'T'); - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var x = new (T)('a'); - /* jshint ignore:end */ + it('should throw if used with new', () => { + throwsWithMessage(() => { + var x = new ( T)('a'); }, 'Operator `new` is forbidden for type `T`'); }); - it('should accept only valid values', function () { - eq((T)('a'), 'a'); - throwsWithMessage(function () { - (T)('b'); + it('should accept only valid values', () => { + eq(( T)('a'), 'a'); + throwsWithMessage(() => { + ( T)('b'); }, 'Invalid argument `value` = `b` supplied to enums type `T`, expected one of ["a"]'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { var Direction = enums({ North: 0, @@ -1070,32 +1052,32 @@ describe('enums', function () { 2.5: 'South-East' }); - it('should return true when x is an instance of the enum', function () { + it('should return true when x is an instance of the enum', () => { ok(Direction.is('North')); ok(Direction.is(1)); ok(Direction.is('1')); ok(Direction.is(2.5)); }); - it('should return false when x is not an instance of the enum', function () { + it('should return false when x is not an instance of the enum', () => { ko(Direction.is('North-East')); ko(Direction.is(2)); }); }); - describe('#of(keys)', function () { + describe('#of(keys)', () => { - it('should return an enum', function () { - var Size = (enums).of(['large', 'small', 1, 10.9]); ///!!! + it('should return an enum', () => { + var Size = ( enums).of(['large', 'small', 1, 10.9]); ///!!! ok(Size.meta.map.large === 'large'); ok(Size.meta.map.small === 'small'); ok(Size.meta.map['1'] === 1); ok(Size.meta.map[10.9] === 10.9); }); - it('should handle a string', function () { - var Size = (enums).of('large small 10'); + it('should handle a string', () => { + var Size = ( enums).of('large small 10'); ok(Size.meta.map.large === 'large'); ok(Size.meta.map.small === 'small'); ok(Size.meta.map['10'] === '10'); @@ -1110,7 +1092,7 @@ describe('enums', function () { // union // -describe('union', function () { +describe('union', () => { var Circle = struct({ center: Point, @@ -1124,81 +1106,79 @@ describe('union', function () { var Shape = union([Circle, Rectangle], 'Shape'); - Shape.dispatch = function (values) { + Shape.dispatch = values => { assert(Obj.is(values)); return values.hasOwnProperty('center') ? Circle : Rectangle; }; - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (union)(); + throwsWithMessage(() => { + ( union)(); }, 'Invalid argument `types` = `undefined` supplied to `union` combinator'); - throwsWithMessage(function () { + throwsWithMessage(() => { union([]); }, 'Invalid argument `types` = `` supplied to `union` combinator, provide at least two types'); - throwsWithMessage(function () { + throwsWithMessage(() => { union([Circle]); }, 'Invalid argument `types` = `Circle` supplied to `union` combinator, provide at least two types'); - throwsWithMessage(function () { - (union)([Circle, Point], 1); + throwsWithMessage(() => { + ( union)([Circle, Point], 1); }, 'Invalid argument `name` = `1` supplied to `union` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should throw when dispatch() is not implemented', function () { - throwsWithMessage(function () { + it('should throw when dispatch() is not implemented', () => { + throwsWithMessage(() => { var T = union([Str, Num], 'T'); T.dispatch = null; T(1); }, 'Unimplemented `dispatch()` function for union type `T`'); }); - it('should have a default dispatch() implementation', function () { + it('should have a default dispatch() implementation', () => { var T = union([Str, Num], 'T'); eq(T(1), 1); }); - it('should throw when dispatch() does not return a type', function () { - throwsWithMessage(function () { + it('should throw when dispatch() does not return a type', () => { + throwsWithMessage(() => { var T = union([Str, Num], 'T'); T(true); }, 'The `dispatch()` function of union type `T` returns no type constructor'); }); - it('should build instances when dispatch() is implemented', function () { + it('should build instances when dispatch() is implemented', () => { var circle = Shape({center: {x: 0, y: 0}, radius: 10}); ok(Circle.is(circle)); }); - it('should throw if used with new and union types are not instantiables with new', function () { - throwsWithMessage(function () { + it('should throw if used with new and union types are not instantiables with new', () => { + throwsWithMessage(() => { var T = union([Str, Num], 'T'); - T.dispatch = function () { return Str; }; - /* jshint ignore:start */ + T.dispatch = () => Str; var x = new T('a'); - /* jshint ignore:end */ }, 'Operator `new` is forbidden for type `T`'); }); - it('should not throw if used with new and union types are instantiables with new', function () { - doesNotThrow(function () { + it('should not throw if used with new and union types are instantiables with new', () => { + doesNotThrow(() => { Shape({center: {x: 0, y: 0}, radius: 10}); }); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var p1 = Shape({center: {x: 0, y: 0}, radius: 10}); var p2 = Shape(p1); eq(Object.isFrozen(p1), true); @@ -1208,9 +1188,9 @@ describe('union', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the union', function () { + it('should return true when x is an instance of the union', () => { var p = new Circle({center: { x: 0, y: 0 }, radius: 10}); ok(Shape.is(p)); }); @@ -1223,56 +1203,54 @@ describe('union', function () { // maybe // -describe('maybe', function () { +describe('maybe', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (maybe)(); + throwsWithMessage(() => { + ( maybe)(); }, 'Invalid argument `type` = `undefined` supplied to `maybe` combinator'); - throwsWithMessage(function () { - (maybe)(Point, 1); + throwsWithMessage(() => { + ( maybe)(Point, 1); }, 'Invalid argument `name` = `1` supplied to `maybe` combinator'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var MaybeStr = maybe(Str); ok(maybe(MaybeStr) === MaybeStr); }); - it('should be noop with Any', function () { + it('should be noop with Any', () => { ok(maybe(Any) === Any); }); - it('should be noop with Nil', function () { - ok((maybe)(Nil) === Nil); + it('should be noop with Nil', () => { + ok(( maybe)(Nil) === Nil); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should throw if used with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ + it('should throw if used with new', () => { + throwsWithMessage(() => { var T = maybe(Str, 'T'); - var x = new (T)(); - /* jshint ignore:end */ + var x = new ( T)(); }, 'Operator `new` is forbidden for type `T`'); }); - it('should coerce values', function () { + it('should coerce values', () => { var T = maybe(Point); eq(T(null), null); eq(T(undefined), null); ok(Point.is(T({x: 0, y: 0}))); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = maybe(Point); var p1 = T({x: 0, y: 0}); var p2 = T(p1); @@ -1283,9 +1261,9 @@ describe('maybe', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the maybe', function () { + it('should return true when x is an instance of the maybe', () => { var Radio = maybe(Str); ok(Radio.is('a')); ok(Radio.is(null)); @@ -1300,50 +1278,50 @@ describe('maybe', function () { // tuple // -describe('tuple', function () { +describe('tuple', () => { var Area = tuple([Num, Num], 'Area'); - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (tuple)(); + throwsWithMessage(() => { + ( tuple)(); }, 'Invalid argument `types` = `undefined` supplied to `tuple` combinator'); - throwsWithMessage(function () { - (tuple)([Point, Point], 1); + throwsWithMessage(() => { + ( tuple)([Point, Point], 1); }, 'Invalid argument `name` = `1` supplied to `tuple` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var S = struct({}, 'S'); var T = tuple([S, S], 'T'); - it('should coerce values', function () { + it('should coerce values', () => { var t = T([{}, {}]); ok(S.is(( t)[0])); ok(S.is(( t)[1])); }); - it('should accept only valid values', function () { + it('should accept only valid values', () => { - throwsWithMessage(function () { + throwsWithMessage(() => { T(1); }, 'Invalid argument `value` = `1` supplied to tuple type `T`, expected an `Arr` of length `2`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T([1, 1]); }, 'Invalid argument `value` = `1` supplied to struct type `S`'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = tuple([Str, Num]); var p1 = T(['a', 1]); var p2 = T(p1); @@ -1354,30 +1332,30 @@ describe('tuple', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { - it('should return true when x is an instance of the tuple', function () { + it('should return true when x is an instance of the tuple', () => { ok(Area.is([1, 2])); }); - it('should return false when x is not an instance of the tuple', function () { + it('should return false when x is not an instance of the tuple', () => { ko(Area.is([1])); ko(Area.is([1, 2, 3])); ko(Area.is([1, 'a'])); }); - it('should not depend on `this`', function () { + it('should not depend on `this`', () => { ok([[1, 2]].every(Area.is)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = tuple([Str, Num]); var instance = Type(['a', 1]); - it('should return a new instance', function () { + it('should return a new instance', () => { var newInstance = Type.update(instance, {0: {$set: 'b'}}); assert(Type.is(newInstance)); assert(( instance)[0] === 'a'); @@ -1392,47 +1370,47 @@ describe('tuple', function () { // list // -describe('list', function () { +describe('list', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (list)(); + throwsWithMessage(() => { + ( list)(); }, 'Invalid argument `type` = `undefined` supplied to `list` combinator'); - throwsWithMessage(function () { - (list)(Point, 1); + throwsWithMessage(() => { + ( list)(Point, 1); }, 'Invalid argument `name` = `1` supplied to `list` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var S = struct({}, 'S'); var T = list(S, 'T'); - it('should coerce values', function () { + it('should coerce values', () => { var t = T([{}]); ok(S.is(( t)[0])); }); - it('should accept only valid values', function () { + it('should accept only valid values', () => { - throwsWithMessage(function () { + throwsWithMessage(() => { T(1); }, 'Invalid argument `value` = `1` supplied to list type `T`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T([1]); }, 'Invalid argument `value` = `1` supplied to struct type `S`'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = list(Num); var p1 = T([1, 2]); var p2 = T(p1); @@ -1443,32 +1421,32 @@ describe('list', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { var Path = list(Point); var p1 = new Point({x: 0, y: 0}); var p2 = new Point({x: 1, y: 1}); - it('should return true when x is a list', function () { + it('should return true when x is a list', () => { ok(Path.is([p1, p2])); }); - it('should not depend on `this`', function () { + it('should not depend on `this`', () => { ok([[p1, p2]].every(Path.is)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = list(Str); var instance = Type(['a', 'b']); - it('should return a new instance', function () { - var newInstance = Type.update(instance, {'$push': ['c']}); + it('should return a new instance', () => { + var newInstance = Type.update(instance, {$push: ['c']}); assert(Type.is(newInstance)); - assert((instance).length === 2); - assert((newInstance).length === 3); + assert(( instance).length === 2); + assert(( newInstance).length === 3); }); }); @@ -1479,80 +1457,76 @@ describe('list', function () { // subtype // -describe('subtype', function () { +describe('subtype', () => { - var True = function () { return true; }; + var True = () => true; - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (subtype)(); + throwsWithMessage(() => { + ( subtype)(); }, 'Invalid argument `type` = `undefined` supplied to `subtype` combinator'); - throwsWithMessage(function () { + throwsWithMessage(() => { subtype(Point, null); }, 'Invalid argument `predicate` = `null` supplied to `subtype` combinator'); - throwsWithMessage(function () { - (subtype)(Point, True, 1); + throwsWithMessage(() => { + ( subtype)(Point, True, 1); }, 'Invalid argument `name` = `1` supplied to `subtype` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { - it('should throw if used with new and a type that is not instantiable with new', function () { - throwsWithMessage(function () { - /* jshint ignore:start */ - var T = subtype(Str, function () { return true; }, 'T'); + it('should throw if used with new and a type that is not instantiable with new', () => { + throwsWithMessage(() => { + var T = subtype(Str, () => true, 'T'); var x = new( T)(); - /* jshint ignore:end */ }, 'Operator `new` is forbidden for type `T`'); }); - it('should coerce values', function () { - var T = subtype(Point, function () { return true; }); + it('should coerce values', () => { + var T = subtype(Point, () => true); var p = T({x: 0, y: 0}); ok(Point.is(p)); }); - it('should accept only valid values', function () { - var predicate = function (p:any) { return p.x > 0; }; + it('should accept only valid values', () => { + var predicate = (p: any) => p.x > 0; var T = subtype(Point, predicate, 'T'); - throwsWithMessage(function () { + throwsWithMessage(() => { T({x: 0, y: 0}); }, 'Invalid argument `value` = `[object Object]` supplied to subtype type `T`'); }); }); - describe('#is(x)', function () { + describe('#is(x)', () => { - var Positive = subtype(Num, function (n) { - return n >= 0; - }); + var Positive = subtype(Num, n => n >= 0); - it('should return true when x is a subtype', function () { + it('should return true when x is a subtype', () => { ok(Positive.is(1)); }); - it('should return false when x is not a subtype', function () { + it('should return false when x is not a subtype', () => { ko(Positive.is(-1)); }); }); - describe('#update()', function () { + describe('#update()', () => { - var Type = subtype(Str, function (s) { return s.length > 2; }); + var Type = subtype(Str, s => s.length > 2); var instance = Type('abc'); - it('should return a new instance', function () { - var newInstance = Type.update(instance, {'$set': 'bca'}); + it('should return a new instance', () => { + var newInstance = Type.update(instance, {$set: 'bca'}); assert(Type.is(newInstance)); eq(newInstance, 'bca'); }); @@ -1565,58 +1539,56 @@ describe('subtype', function () { // dict // -describe('dict', function () { +describe('dict', () => { - describe('combinator', function () { + describe('combinator', () => { - it('should throw if used with wrong arguments', function () { + it('should throw if used with wrong arguments', () => { - throwsWithMessage(function () { - (dict)(); + throwsWithMessage(() => { + ( dict)(); }, 'Invalid argument `domain` = `undefined` supplied to `dict` combinator'); - throwsWithMessage(function () { - (dict)(Str); + throwsWithMessage(() => { + ( dict)(Str); }, 'Invalid argument `codomain` = `undefined` supplied to `dict` combinator'); - throwsWithMessage(function () { - (dict)(Str, Point, 1); + throwsWithMessage(() => { + ( dict)(Str, Point, 1); }, 'Invalid argument `name` = `1` supplied to `dict` combinator'); }); }); - describe('constructor', function () { + describe('constructor', () => { var S = struct({}, 'S'); - var Domain = subtype(Str, function (x) { - return x !== 'forbidden'; - }, 'Domain'); + var Domain = subtype(Str, x => x !== 'forbidden', 'Domain'); var T = dict(Domain, S, 'T'); - it('should coerce values', function () { + it('should coerce values', () => { var t = T({a: {}}); - ok(S.is((t).a)); + ok(S.is(( t).a)); }); - it('should accept only valid values', function () { + it('should accept only valid values', () => { - throwsWithMessage(function () { + throwsWithMessage(() => { T(1); }, 'Invalid argument `value` = `1` supplied to dict type `T`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T({a: 1}); }, 'Invalid argument `value` = `1` supplied to struct type `S`'); - throwsWithMessage(function () { + throwsWithMessage(() => { T({forbidden: {}}); }, 'Invalid argument `value` = `forbidden` supplied to subtype type `Domain`'); }); - it('should be idempotent', function () { + it('should be idempotent', () => { var T = dict(Str, Str); var p1 = T({a: 'a', b: 'b'}); var p2 = T(p1); @@ -1627,32 +1599,32 @@ describe('dict', function () { }); - describe('#is(x)', function () { + describe('#is(x)', () => { var T = dict(Str, Point); var p1 = new Point({x: 0, y: 0}); var p2 = new Point({x: 1, y: 1}); - it('should return true when x is a list', function () { + it('should return true when x is a list', () => { ok(T.is({a: p1, b: p2})); }); - it('should not depend on `this`', function () { + it('should not depend on `this`', () => { ok([{a: p1, b: p2}].every(T.is)); }); }); - describe('#update()', function () { + describe('#update()', () => { var Type = dict(Str, Str); var instance = Type({p1: 'a', p2: 'b'}); - it('should return a new instance', function () { + it('should return a new instance', () => { var newInstance = Type.update(instance, {p2: {$set: 'c'}}); ok(Type.is(newInstance)); - eq((instance).p2, 'b'); - eq((newInstance).p2, 'c'); + eq(( instance).p2, 'b'); + eq(( newInstance).p2, 'c'); }); }); @@ -1663,84 +1635,78 @@ describe('dict', function () { // func // -describe('func', function () { +describe('func', () => { - it('should handle a no types', function () { + it('should handle a no types', () => { var T = func([], Str); eq(T.meta.domain.length, 0); - var getGreeting = T.of(function () { return 'Hi'; }); + var getGreeting = T.of(() => 'Hi'); eq(getGreeting(), 'Hi'); }); - it('should handle a single type', function () { + it('should handle a single type', () => { var T = func(Num, Num); eq(T.meta.domain.length, 1); ok(T.meta.domain[0] === Num); }); - it('should automatically instrument a function', function () { + it('should automatically instrument a function', () => { var T = func(Num, Num); - var f = function () { return 'hi'; }; + var f = () => 'hi'; ok(T.is(T(f))); }); - describe('of', function () { + describe('of', () => { - it('should check the arguments', function () { + it('should check the arguments', () => { var T = func([Num, Num], Num); - var sum = T.of(function (a:any, b:any) { - return a + b; - }); + var sum = T.of((a: any, b: any) => a + b); eq(sum(1, 2), 3); - throwsWithMessage(function () { + throwsWithMessage(() => { sum(1, 2, 3); }, 'Invalid argument `value` = `1,2,3` supplied to tuple type `[Num, Num]`, expected an `Arr` of length `2`'); - throwsWithMessage(function () { + throwsWithMessage(() => { sum('a', 2); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); }); - it('should check the return value', function () { + it('should check the return value', () => { var T = func([Num, Num], Num); - var sum = T.of(function () { + var sum = T.of(() => { return 'a'; }); - throwsWithMessage(function () { + throwsWithMessage(() => { sum(1, 2); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); }); - it('should preserve `this`', function () { + it('should preserve `this`', () => { var o = {name: 'giulio'}; - (o).getTypeName = func([], Str).of(function () { + ( o).getTypeName = func([], Str).of(function(this: any) { return this.name; }); - eq((o).getTypeName(), 'giulio'); + eq(( o).getTypeName(), 'giulio'); }); - it('should handle function types', function () { + it('should handle function types', () => { var A = func([Str], Str); var B = func([Str, A], Str); - var f = A.of(function (s:any) { - return s + '!'; - }); - var g = B.of(function (str:any, strAction:any) { - return strAction(str); - }); + var f = A.of((s: any) => s + '!'); + var g = B.of((str: any, strAction: any) => strAction(str)); eq(g('hello', f), 'hello!'); }); - it('should be idempotent', function () { - var f = function (s:any) { return s; }; + it('should be idempotent', () => { + var f = (s: any) => s; var g = func([Str], Str).of(f); var h = func([Str], Str).of(g); ok(h === g); @@ -1748,13 +1714,11 @@ describe('func', function () { }); - describe('currying', function () { + describe('currying', () => { - it('should curry functions', function () { + it('should curry functions', () => { var Type = func([Num, Num, Num], Num); - var sum = Type.of(function (a:any, b:any, c:any) { - return a + b + c; - }); + var sum = Type.of((a: any, b: any, c: any) => a + b + c); eq(sum(1, 2, 3), 6); eq(sum(1, 2)(3), 6); eq(sum(1)(2, 3), 6); @@ -1768,18 +1732,16 @@ describe('func', function () { ok(CurriedType.is(sum1)); }); - it('should throw if partial arguments are wrong', function () { + it('should throw if partial arguments are wrong', () => { var T = func([Num, Num], Num); - var sum = T.of(function (a:any, b:any) { - return a + b; - }); + var sum = T.of((a: any, b: any) => a + b); - throwsWithMessage(function () { + throwsWithMessage(() => { sum('a'); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); - throwsWithMessage(function () { + throwsWithMessage(() => { var sum1 = sum(1); sum1('a'); }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); diff --git a/tcomb/tsconfig.json b/tcomb/tsconfig.json index 214f9a631b..91290a69e2 100644 --- a/tcomb/tsconfig.json +++ b/tcomb/tsconfig.json @@ -5,7 +5,7 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, + "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ diff --git a/tcomb/tslint.json b/tcomb/tslint.json new file mode 100644 index 0000000000..c3d18eb9dd --- /dev/null +++ b/tcomb/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "forbidden-types": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false + } +} diff --git a/three/index.d.ts b/three/index.d.ts index 3b0917f577..7b76100c17 100644 --- a/three/index.d.ts +++ b/three/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for three.js 0.83 // Project: http://mrdoob.github.com/three.js/ -// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot +// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -20,6 +20,9 @@ /// /// /// +/// +/// +/// declare namespace THREE { export const REVISION: string; @@ -217,7 +220,7 @@ declare namespace THREE { // Triangle Draw modes export enum TrianglesDrawModes { } - export const TrianglesDrawModesMode: TrianglesDrawModes; + export const TrianglesDrawMode: TrianglesDrawModes; export const TriangleStripDrawMode: TrianglesDrawModes; export const TriangleFanDrawMode: TrianglesDrawModes; @@ -1996,7 +1999,7 @@ declare namespace THREE { mimeType: MimeType; path: string; responseType: string; - withCredentials: string + withCredentials: string; load(url: string, onLoad?: (responseText: string) => void, onProgress?: (request: ProgressEvent) => void, onError?:(event: ErrorEvent) => void): any; setMimeType(mimeType: MimeType): FileLoader; @@ -3586,6 +3589,10 @@ declare namespace THREE { export class Spherical { constructor(radius?: number, phi?: number, theta?: number); + radius: number; + phi: number; + theta: number; + set(radius: number, phi: number, theta: number): Spherical; clone(): this; copy(other: this): this; diff --git a/three/test/examples/ctm/ctmloader.ts b/three/test/examples/ctm/ctmloader.ts new file mode 100644 index 0000000000..e35cffb6a4 --- /dev/null +++ b/three/test/examples/ctm/ctmloader.ts @@ -0,0 +1,7 @@ +/// + +let _ctmloader = new THREE.CTMLoader(); +_ctmloader.load('https://github.com/mrdoob/three.js/blob/master/examples/models/ctm/ben.ctm', (geo: any) => { + console.log(geo.position); +}); + diff --git a/three/test/examples/octree.ts b/three/test/examples/octree.ts new file mode 100644 index 0000000000..de7de86ac7 --- /dev/null +++ b/three/test/examples/octree.ts @@ -0,0 +1,11 @@ +/// + +let _octree = new THREE.Octree({ + underferred: false, + depthMax: Infinity, + objectsThreshold: 8, + overlapPct: 0.15, +}); + +console.log(_octree.getDepthEnd()); + diff --git a/three/three-FirstPersonControls.d.ts b/three/three-FirstPersonControls.d.ts index e66e728459..0f85f90bdd 100644 --- a/three/three-FirstPersonControls.d.ts +++ b/three/three-FirstPersonControls.d.ts @@ -8,6 +8,7 @@ declare namespace THREE { class FirstPersonControls { constructor(object: Camera, domElement?: HTMLElement); + object: THREE.Object3D; target: THREE.Vector3; domElement: HTMLCanvasElement | HTMLDocument; @@ -38,7 +39,9 @@ declare namespace THREE { moveRight: boolean; freeze: boolean; mouseDragOn: boolean; + update(delta: number): void; + dispose(): void; } } diff --git a/three/three-canvasrenderer.d.ts b/three/three-canvasrenderer.d.ts index 159c606273..c37f223c56 100644 --- a/three/three-canvasrenderer.d.ts +++ b/three/three-canvasrenderer.d.ts @@ -1,10 +1,10 @@ // Type definitions for three.js (CanvasRenderer.js) // Project: https://github.com/mrdoob/three.js/blob/master/examples/js/renderers/CanvasRenderer.js -// Definitions by: Satoru Kimura +// Definitions by: Satoru Kimura < https://github.com/gyohk > // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace THREE { - export interface SpriteCanvasMaterialParameters extends MaterialParameters{ + export interface SpriteCanvasMaterialParameters extends MaterialParameters { color?: number; program?: (context: any, color: Color) => void; } @@ -30,27 +30,45 @@ declare namespace THREE { autoClear: boolean; sortObjects: boolean; sortElements: boolean; - info: { render: { vertices: number; faces: number; }; }; + info: {render: {vertices: number; faces: number;};}; supportsVertexTextures(): void; + setFaceCulling(): void; + getPixelRatio(): number; + setPixelRatio(value: number): void; + setSize(width: number, height: number, updateStyle?: boolean): void; + setViewport(x: number, y: number, width: number, height: number): void; + setScissor(): void; + enableScissorTest(): void; - setClearColor(color: Color, opacity?: number): void; - setClearColor(color: string, opacity?: number): void; - setClearColor(color: number, opacity?: number): void; + + setClearColor(color: Color | string | number, opacity?: number): void; + + // setClearColor(color: string, opacity?: number): void; + // setClearColor(color: number, opacity?: number): void; + setClearColorHex(hex: number, alpha?: number): void; + getClearColor(): Color; + getClearAlpha(): number; + getMaxAnisotropy(): number; + clear(): void; + clearColor(): void; + clearDepth(): void; + clearStencil(): void; + render(scene: Scene, camera: Camera): void; } } diff --git a/three/three-colladaLoader.d.ts b/three/three-colladaLoader.d.ts new file mode 100644 index 0000000000..6bdec6a9da --- /dev/null +++ b/three/three-colladaLoader.d.ts @@ -0,0 +1,23 @@ +// Type definitions for three.js (ColladaLoader2.js) +// NOTE : These typings are for the loader named ColladaLoader2.js +// supplied by the npm package @types/three 0.81. +// Definitions by: Brandon Roberge + +declare namespace THREE { + export interface ColladaLoaderReturnType { + + } + export class ColladaModel { + animations: any[]; + kinematics: any; + scene: THREE.Scene; + library: any; + } + export class ColladaLoader { + constructor(); + + load(url: string, onLoad: (model: ColladaModel) => void, onProgress?: (request: ProgressEvent) => void, onError?:(event: ErrorEvent) => void): void; + setCrossOrigin(value: any): void; + parse(text: string): ColladaModel; + } +} \ No newline at end of file diff --git a/three/three-copyshader.d.ts b/three/three-copyshader.d.ts index ff28c682ee..05ff6a5f04 100644 --- a/three/three-copyshader.d.ts +++ b/three/three-copyshader.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { - export var CopyShader: Shader; + export var CopyShader: Shader; } diff --git a/three/three-css3drenderer.d.ts b/three/three-css3drenderer.d.ts index 7f015d4e69..94acb9f5cc 100644 --- a/three/three-css3drenderer.d.ts +++ b/three/three-css3drenderer.d.ts @@ -7,7 +7,6 @@ // https://github.com/mrdoob/three.js/issues/4783 - declare namespace THREE { class CSS3DObject extends Object3D { constructor(element: any); @@ -24,9 +23,10 @@ declare namespace THREE { class CSS3DRenderer { constructor(); - domElement:HTMLElement; + domElement: HTMLElement; setSize(width: number, height: number): void; + render(scene: THREE.Scene, camera: THREE.Camera): void; } } diff --git a/three/three-ctmloader.d.ts b/three/three-ctmloader.d.ts new file mode 100644 index 0000000000..0dd56a3b9a --- /dev/null +++ b/three/three-ctmloader.d.ts @@ -0,0 +1,36 @@ +// Type definitions for three.js (CTMLoader.js) +// Project: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/ctm/CTMLoader.js +// Definitions by: Hou Chunlei +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace THREE { + export class CTMLoader extends THREE.Loader { + constructor(); + + /** + * load multiple CTM parts defined in JSON. + * @param url(required) + * @param callback(required) + * @param parameters + */ + loadParts(url: string, callback: () => any, parameters?: any): any; + + /** + * Load CTMLoader compressed models + * @param url(required) + * @param callback(required) + * @param parameters + */ + load(url: string, callback: (geo: any) => any, parameters?: any): any; + + /** + * create buffergeometry by ctm file. + * @param file(required) + * @param callback(required) + */ + createModel(file: string, callback: () => any): any; + + } +} diff --git a/three/three-editorcontrols.d.ts b/three/three-editorcontrols.d.ts index 9ed2a0ceb5..6f2e6402ed 100644 --- a/three/three-editorcontrols.d.ts +++ b/three/three-editorcontrols.d.ts @@ -4,22 +4,25 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { - class EditorControls extends EventDispatcher { + class EditorControls extends EventDispatcher { - constructor(object: Camera, domElement?:HTMLElement); + constructor(object: Camera, domElement?: HTMLElement); - enabled: boolean; - center: THREE.Vector3; + enabled: boolean; + center: THREE.Vector3; - focus(target: THREE.Object3D, frame: boolean): void; - pan(delta: THREE.Vector3): void; - zoom(delta: THREE.Vector3): void; - rotate(delta: THREE.Vector3): void; - dispose(): void; + focus(target: THREE.Object3D, frame: boolean): void; - } + pan(delta: THREE.Vector3): void; + + zoom(delta: THREE.Vector3): void; + + rotate(delta: THREE.Vector3): void; + + dispose(): void; + + } } diff --git a/three/three-effectcomposer.d.ts b/three/three-effectcomposer.d.ts index 16ed7d33a5..45b586aa55 100644 --- a/three/three-effectcomposer.d.ts +++ b/three/three-effectcomposer.d.ts @@ -4,25 +4,27 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - - declare namespace THREE { - export class EffectComposer { - constructor( renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget); + export class EffectComposer { + constructor(renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget); - renderTarget1: WebGLRenderTarget; - renderTarget2: WebGLRenderTarget; - writeBuffer: WebGLRenderTarget; - readBuffer: WebGLRenderTarget; - passes: any[]; - copyPass: ShaderPass; + renderTarget1: WebGLRenderTarget; + renderTarget2: WebGLRenderTarget; + writeBuffer: WebGLRenderTarget; + readBuffer: WebGLRenderTarget; + passes: any[]; + copyPass: ShaderPass; - swapBuffers(): void; - addPass(pass: any): void; - insertPass(pass: any, index: number): void; - render(delta?: number): void; - reset(renderTarget?: WebGLRenderTarget): void; - setSize( width: number, height: number ): void; - } + swapBuffers(): void; + + addPass(pass: any): void; + + insertPass(pass: any, index: number): void; + + render(delta?: number): void; + + reset(renderTarget?: WebGLRenderTarget): void; + + setSize(width: number, height: number): void; + } } diff --git a/three/three-maskpass.d.ts b/three/three-maskpass.d.ts index 8cabf2b8ad..15847324dd 100644 --- a/three/three-maskpass.d.ts +++ b/three/three-maskpass.d.ts @@ -4,26 +4,25 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { - export class MaskPass { - constructor( scene: Scene, camera: Camera); + export class MaskPass { + constructor(scene: Scene, camera: Camera); - scene: Scene; - camera: Camera; - enabled: boolean; - clear: boolean; - needsSwap: boolean; - inverse: boolean; + scene: Scene; + camera: Camera; + enabled: boolean; + clear: boolean; + needsSwap: boolean; + inverse: boolean; render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number): void; - } + } - export class ClearMaskPass { - constructor(); + export class ClearMaskPass { + constructor(); - enabled: boolean; + enabled: boolean; render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number): void; - } + } } diff --git a/three/three-octree.d.ts b/three/three-octree.d.ts new file mode 100644 index 0000000000..dc534f98bc --- /dev/null +++ b/three/three-octree.d.ts @@ -0,0 +1,42 @@ +// Type definitions for three.js (Octree.js) +// Project: https://github.com/mrdoob/three.js/blob/master/examples/js/Octree.js +// Definitions by: Hou Chunlei +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace THREE { + export class Octree { + constructor(parameters?: any); + + update(): void; + + add(object: any, options?: any): any; + + addDeferred(object: any, options?: any): any; + + addObjectData(object: any, part: any): any; + + remove(object: any): any; + + extend(octree: Octree): any; + + rebuild(): any; + + updateObject(object: any): any; + + search(position: THREE.Vector3, radius: number, organizeByObject: boolean, direction: THREE.Vector3): any; + + setRoot(root: any): any; + + getDepthEnd(): number; + + getNodeCountEnd(): number; + + getObjectCountEnd(): number; + + toConsole(): any; + + + } +} diff --git a/three/three-orbitcontrols.d.ts b/three/three-orbitcontrols.d.ts index 6ed41b4bf4..6f098d320d 100644 --- a/three/three-orbitcontrols.d.ts +++ b/three/three-orbitcontrols.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { class OrbitControls { constructor(object: Camera, domElement?: HTMLElement); @@ -34,29 +33,43 @@ declare namespace THREE { minAzimuthAngle: number; maxAzimuthAngle: number; enableKeys: boolean; - keys: { LEFT: number; UP: number; RIGHT: number; BOTTOM: number; }; - mouseButtons: { ORBIT: MOUSE; ZOOM: MOUSE; PAN: MOUSE; }; + keys: {LEFT: number; UP: number; RIGHT: number; BOTTOM: number;}; + mouseButtons: {ORBIT: MOUSE; ZOOM: MOUSE; PAN: MOUSE;}; enableDamping: boolean; dampingFactor: number; rotateLeft(angle?: number): void; + rotateUp(angle?: number): void; + panLeft(distance?: number): void; + panUp(distance?: number): void; + pan(deltaX: number, deltaY: number): void; + dollyIn(dollyScale: number): void; + dollyOut(dollyScale: number): void; + update(): void; + reset(): void; + dispose(): void; + getPolarAngle(): number; + getAzimuthalAngle(): number; // EventDispatcher mixins addEventListener(type: string, listener: (event: any) => void): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + + dispatchEvent(event: {type: string; target: any;}): void; } } diff --git a/three/three-orthographictrackballcontrols.d.ts b/three/three-orthographictrackballcontrols.d.ts index ea19c2a73d..0051ac9095 100644 --- a/three/three-orthographictrackballcontrols.d.ts +++ b/three/three-orthographictrackballcontrols.d.ts @@ -4,48 +4,53 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare namespace THREE { + export class OrthographicTrackballControls extends EventDispatcher { + constructor(object: Camera, domElement?: HTMLElement); -declare module THREE { - class OrthographicTrackballControls extends EventDispatcher { - constructor(object:Camera, domElement?:HTMLElement); + object: Camera; + domElement: HTMLElement; - object:Camera; - domElement:HTMLElement; + // API + enabled: boolean; + screen: {left: number; top: number; width: number; height: number}; + radius: number; + rotateSpeed: number; + zoomSpeed: number; + panSpeed: number; + noRotate: boolean; + noZoom: boolean; + noPan: boolean; + noRoll: boolean; + staticMoving: boolean; + dynamicDampingFactor: number; + keys: number[]; - // API - enabled:boolean; - screen:{ left: number; top: number; width: number; height: number }; - radius:number; - rotateSpeed:number; - zoomSpeed:number; - panSpeed:number; - noRotate:boolean; - noZoom:boolean; - noPan:boolean; - noRoll:boolean; - staticMoving:boolean; - dynamicDampingFactor:number; - keys:number[]; + target: THREE.Vector3; - target: THREE.Vector3; + position0: THREE.Vector3; + target0: THREE.Vector3; + up0: THREE.Vector3; - position0: THREE.Vector3; - target0: THREE.Vector3; - up0: THREE.Vector3; + left0: number; + right0: number; + top0: number; + bottom0: number; - left0: number; - right0: number; - top0: number; - bottom0: number; + update(): void; - update():void; - reset():void; - checkDistances():void; - zoomCamera():void; - panCamera():void; - rotateCamera():void; + reset(): void; - handleResize():void; - handleEvent(event: any):void; - } + checkDistances(): void; + + zoomCamera(): void; + + panCamera(): void; + + rotateCamera(): void; + + handleResize(): void; + + handleEvent(event: any): void; + } } diff --git a/three/three-projector.d.ts b/three/three-projector.d.ts index ef339b25e3..574d3f969f 100644 --- a/three/three-projector.d.ts +++ b/three/three-projector.d.ts @@ -4,14 +4,13 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { // Renderers / Renderables ///////////////////////////////////////////////////////////////////// export class RenderableObject { constructor(); id: number; - object: Object; + object: any; z: number; } @@ -58,7 +57,7 @@ declare namespace THREE { constructor(); id: number; - object: Object; + object: any; x: number; y: number; z: number; diff --git a/three/three-renderpass.d.ts b/three/three-renderpass.d.ts index 842ad7faf1..01022fd854 100644 --- a/three/three-renderpass.d.ts +++ b/three/three-renderpass.d.ts @@ -4,24 +4,23 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { - export class RenderPass { - constructor( scene: Scene, camera: Camera, overrideMaterial?: Material, clearColor?: Color, clearAlpha?: number ); - constructor( scene: Scene, camera: Camera, overrideMaterial?: Material, clearColor?: string, clearAlpha?: number ); - constructor( scene: Scene, camera: Camera, overrideMaterial?: Material, clearColor?: number, clearAlpha?: number ); + export class RenderPass { + // constructor(scene: Scene, camera: Camera, overrideMaterial?: Material, clearColor?: Color, clearAlpha?: number); + constructor(scene: Scene, camera: Camera, overrideMaterial?: Material, clearColor?: Color | string | number, clearAlpha?: number); + // constructor(scene: Scene, camera: Camera, overrideMaterial?: Material, clearColor?: number, clearAlpha?: number); - scene: Scene; - camera: Camera; - overrideMaterial: Material; - clearColor: any; // Color or string or number - clearAlpha: number; - oldClearColor: Color; - oldClearAlpha: number; - enabled: boolean; - clear: boolean; - needsSwap: boolean; + scene: Scene; + camera: Camera; + overrideMaterial: Material; + clearColor: any; // Color or string or number + clearAlpha: number; + oldClearColor: Color; + oldClearAlpha: number; + enabled: boolean; + clear: boolean; + needsSwap: boolean; render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number): void; - } + } } diff --git a/three/three-shaderpass.d.ts b/three/three-shaderpass.d.ts index cce304b523..8fb9341375 100644 --- a/three/three-shaderpass.d.ts +++ b/three/three-shaderpass.d.ts @@ -4,22 +4,21 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { - export class ShaderPass { - constructor( shader: Shader, textureID?: string ); + export class ShaderPass { + constructor(shader: Shader, textureID?: string); - textureID: string; - uniforms: any; - material: ShaderMaterial; - renderToScreen: boolean; - enabled: boolean; - needsSwap: boolean; - clear: boolean; - camera: Camera; - scene: Scene; - quad: Mesh; + textureID: string; + uniforms: any; + material: ShaderMaterial; + renderToScreen: boolean; + enabled: boolean; + needsSwap: boolean; + clear: boolean; + camera: Camera; + scene: Scene; + quad: Mesh; - render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number): void; - } + render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number): void; + } } diff --git a/three/three-trackballcontrols.d.ts b/three/three-trackballcontrols.d.ts index 59021b17b6..aa81100a0d 100644 --- a/three/three-trackballcontrols.d.ts +++ b/three/three-trackballcontrols.d.ts @@ -4,43 +4,48 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { class TrackballControls extends EventDispatcher { - constructor(object:Camera, domElement?:HTMLElement); + constructor(object: Camera, domElement?: HTMLElement); - object:Camera; - domElement:HTMLElement; + object: Camera; + domElement: HTMLElement; // API - enabled:boolean; - screen:{ left: number; top: number; width: number; height: number }; - rotateSpeed:number; - zoomSpeed:number; - panSpeed:number; - noRotate:boolean; - noZoom:boolean; - noPan:boolean; - noRoll:boolean; - staticMoving:boolean; - dynamicDampingFactor:number; - minDistance:number; - maxDistance:number; - keys:number[]; + enabled: boolean; + screen: {left: number; top: number; width: number; height: number}; + rotateSpeed: number; + zoomSpeed: number; + panSpeed: number; + noRotate: boolean; + noZoom: boolean; + noPan: boolean; + noRoll: boolean; + staticMoving: boolean; + dynamicDampingFactor: number; + minDistance: number; + maxDistance: number; + keys: number[]; target: THREE.Vector3; position0: THREE.Vector3; target0: THREE.Vector3; up0: THREE.Vector3; - update():void; - reset():void; - checkDistances():void; - zoomCamera():void; - panCamera():void; - rotateCamera():void; + update(): void; - handleResize():void; - handleEvent(event: any):void; + reset(): void; + + checkDistances(): void; + + zoomCamera(): void; + + panCamera(): void; + + rotateCamera(): void; + + handleResize(): void; + + handleEvent(event: any): void; } } diff --git a/three/three-transformcontrols.d.ts b/three/three-transformcontrols.d.ts index e6d2638540..5d41149cd5 100644 --- a/three/three-transformcontrols.d.ts +++ b/three/three-transformcontrols.d.ts @@ -4,21 +4,27 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace THREE { - class TransformControls extends Object3D { - constructor(object:Camera, domElement?:HTMLElement); + class TransformControls extends Object3D { + constructor(object: Camera, domElement?: HTMLElement); - object: Object3D; + object: Object3D; - update():void; - detach(): void; - attach(object: Object3D): void; - getMode(): string; - setMode(mode: string): void; - setSnap(snap: any): void; - setSize(size:number):void; - setSpace(space:string):void; + update(): void; - } + detach(): void; + + attach(object: Object3D): void; + + getMode(): string; + + setMode(mode: string): void; + + setSnap(snap: any): void; + + setSize(size: number): void; + + setSpace(space: string): void; + + } } diff --git a/three/three-vrcontrols.d.ts b/three/three-vrcontrols.d.ts index 9fe361bc17..080923b7ef 100644 --- a/three/three-vrcontrols.d.ts +++ b/three/three-vrcontrols.d.ts @@ -8,12 +8,13 @@ declare namespace THREE { export class VRControls { - constructor(camera: Camera, callback?: (param: string)=>void); + constructor(camera: Camera, callback?: (param: string) => void); /** * Update VR Instance Tracking */ update(): void; + zeroSensor(): void; scale: number; diff --git a/three/three-vreffect.d.ts b/three/three-vreffect.d.ts index 764acf1337..0c47318657 100644 --- a/three/three-vreffect.d.ts +++ b/three/three-vreffect.d.ts @@ -8,25 +8,33 @@ declare namespace THREE { export class VREffect { - constructor(renderer: Renderer, callback?: (params: string)=>void); + constructor(renderer: Renderer, callback?: (params: string) => void); + render(scene: Scene, camera: Camera): void; + setSize(width: number, height: number): void; + setFullScreen(flag: boolean): void; + startFullscreen(): void; + FovToNDCScaleOffset(fov: VRFov): VREffectOffset; + FovPortToProjection(fov: VRFov, rightHanded: boolean, zNear: number, zFar: number): Matrix4; + FovToProjection(fov: VRFov, rightHanded: boolean, zNear: number, zFar: number): Matrix4; + setVRDisplay(display: VRDisplay): void; } - export interface VRFov{ + export interface VRFov { leftTan: number; rightTan: number; upTan: number; downTan: number; } - export interface VREffectOffset{ + export interface VREffectOffset { scale: number; offset: number; } diff --git a/three/tsconfig.json b/three/tsconfig.json index e140c6668c..37a325d404 100644 --- a/three/tsconfig.json +++ b/three/tsconfig.json @@ -49,6 +49,8 @@ "test/canvas/canvas_particles_floor.ts", "test/examples/detector.ts", "test/examples/effects/vreffect.ts", - "test/examples/controls/vrcontrols.ts" + "test/examples/controls/vrcontrols.ts", + "test/examples/ctm/ctmloader.ts", + "test/examples/octree.ts" ] -} \ No newline at end of file +} diff --git a/tinymce/tslint.json b/tinymce/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/tinymce/tslint.json +++ b/tinymce/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/transducers-js/index.d.ts b/transducers-js/index.d.ts index 0c63bd11c9..0ac1d18235 100644 --- a/transducers-js/index.d.ts +++ b/transducers-js/index.d.ts @@ -1,304 +1,297 @@ -// Type definitions for transducers-js +// Type definitions for transducers-js 0.4 // Project: https://github.com/cognitect-labs/transducers-js // Definitions by: Colin Kahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'transducers-js' { - export interface IteratorResult { - done: boolean; - value?: T - } - - export interface Iterator { - next (value?: any): IteratorResult; - return? (value?: any): IteratorResult; - throw? (e?: any): IteratorResult; - } - - export interface Reduced { - ['@@transducer/reduced']: boolean; - ['@@transducer/value']: TResult; - } - - export interface Reducer { - (result: TResult, input: TInput): TResult; - } - - export interface Transducer { - (xf: Transformer): Transformer; - } - - export interface CompletingTransformer { - ['@@transducer/init'] (): TResult | void; - ['@@transducer/step'] (result: TResult, input: TInput): TResult | Reduced; - ['@@transducer/result'] (result: TResult): TCompleteResult; - } - - export interface Transformer extends CompletingTransformer { - } - - /** - * Return a reduced value. Reduced values short circuit transduce. - */ - export function reduced (x: TResult): Reduced; - - /** - * Check if a value is reduced. - */ - export function isReduced (x : any) : Boolean; - - /** - * Function composition. Take N function and return their composition. - */ - export function comp (...args: T[]): T; - - /** - * Take a predicate function and return its complement. - */ - export function complement (f: Function): Function; - - /** - * Identity function. - */ - export function identity (arg: T): T; - - export class Map implements Transformer { - constructor (f: (x: TInput) => TOutput, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Mapping transducer constructor - */ - export function map (f: (x: TInput) => TOutput): Transducer; - - export class Filter implements Transformer { - constructor (pred: (x: TInput) => boolean, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Filtering transducer constructor - */ - export function filter (pred: (x: TInput) => boolean): Transducer; - - /** - * Similar to filter except the predicate is used to - * eliminate values. - */ - export function remove (pred: (x: TInput) => boolean): Transducer; - - export class Keep implements Transformer { - constructor (f: (x: TInput) => any, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A keeping transducer. Keep inputs as long as the provided - * function does not return null or undefined. - */ - export function keep (f: (x: TInput) => any): Transducer; - - export class KeepIndexed implements Transformer { - constructor (f: (i: number, x:TInput) => any, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Like keep but the provided function will be passed the - * index as the fist argument. - */ - export function keepIndexed (f: (i: number, x: TInput) => any): Transducer; - - export class Take implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult | Reduced; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A take transducer constructor. Will take n values before - * returning a reduced result. - */ - export function take (n: number): Transducer; - - export class TakeWhile implements Transformer { - constructor (pred: (n: TInput) => boolean, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult | Reduced; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * Like the take transducer except takes as long as the pred - * return true for inputs. - */ - export function takeWhile (pred: (n: TInput) => boolean): Transducer; - - export class TakeNth implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A transducer that takes every Nth input - */ - export function takeNth (n: number): Transducer; - - export class Drop implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A dropping transducer constructor - */ - export function drop (n: number): Transducer; - - export class DropWhile implements Transformer { - constructor (pred: (input: TInput) => boolean, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult; - ['@@transducer/result'] (result: TResult): TResult; - } - - /** - * A dropping transducer that drop inputs as long as - * pred is true. - */ - export function dropWhile (pred: (input: TInput) => boolean): Transducer; - - export class PartitionBy implements Transformer { - constructor (f: (input: TInput) => any, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TResult - } - - /** - * A partitioning transducer. Collects inputs into - * arrays as long as predicate remains true for contiguous - * inputs. - */ - export function partitionBy (f: (input: TInput) => any): Transducer; - - export class PartitionAll implements Transformer { - constructor (n: number, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TResult - } - - /** - * A partitioning transducer. Collects inputs into - * arrays of size N. - */ - export function partitionAll (n: number): Transducer; - - export class Completing implements CompletingTransformer { - constructor (cf: (result: TResult) => TCompleteResult, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TCompleteResult - } - - /** - * A completing transducer constructor. Useful to provide cleanup - * logic at the end of a reduction/transduction. - */ - export function completing (cf: (result: TResult) => TCompleteResult): CompletingTransformer; - - export class Wrap implements Transformer { - constructor (stepFn: Reducer, xf: Transformer); - ['@@transducer/init'] (): TResult; - ['@@transducer/step'] (result: TResult, input: TInput): TResult - ['@@transducer/result'] (result: TResult): TResult - } - - /** - * Take a two-arity reducing function where the first argument is the - * accumluation and the second argument is the next input and convert - * it into a transducer transformer object. - */ - export function wrap (stepFn: Reducer): Transducer; - - /** - * Given a transformer return a concatenating transformer - */ - export function cat (xf: Transformer): Transformer ; - - /** - * A mapping concatenating transformer - */ - export function mapcat (f: (arr: TInput[]) => TOutput[]): Transducer; - - /** - * Given a transducer, a builder function, an initial value - * and a iterable collection - returns the reduction. - */ - export function transduce ( - xf: Transducer, - f: Transformer | Reducer, - init: TResult, - coll: TInput[] | Iterator | string | Object): TResult; - - /** - * Given a transducer, an intial value and a - * collection - returns the reduction. - */ - export function reduce ( - xf: Transducer, - init: TResult, - coll: TInput[] | Iterator | string | Object): TResult - - /** - * Reduce a value into the given empty value using a transducer. - */ - export function into( - empty: TResult, - xf: Transducer, - coll: TInput[] | Iterator | string | Object): TResult; - - /** - * Convert a transducer transformer object into a function so - * that it can be used with existing reduce implementation i.e. native, - * Underscore, lodash - */ - export function toFn ( - xf: Transducer, - builder: Reducer | Transformer - ): Reducer; - - /** - * A transformer which simply returns the first input. - */ - export function first (): Wrap; - - /** - * Ensure that a value is reduced. If already reduced will not re-wrap. - */ - export function ensureReduced (x: TResult | Reduced): Reduced; - - /** - * Ensure a value is not reduced. Unwraps if reduced. - */ - export function unreduced (x: TResult | Reduced): TResult; - - /** - * Returns the value of a reduced result. - */ - export function deref (x: Reduced): TResult; +export interface IteratorResult { + done: boolean; + value?: T; } + +export interface Iterator { + next(value?: any): IteratorResult; + return?(value?: any): IteratorResult; + throw?(e?: any): IteratorResult; +} + +export interface Reduced { + ['@@transducer/reduced']: boolean; + ['@@transducer/value']: TResult; +} + +export type Reducer = (result: TResult, input: TInput) => TResult; + +export type Transducer = (xf: Transformer) => Transformer; + +export interface CompletingTransformer { + ['@@transducer/init'](): TResult | void; + ['@@transducer/step'](result: TResult, input: TInput): TResult | Reduced; + ['@@transducer/result'](result: TResult): TCompleteResult; +} + +export type Transformer = CompletingTransformer; + +/** + * Return a reduced value. Reduced values short circuit transduce. + */ +export function reduced(x: TResult): Reduced; + +/** + * Check if a value is reduced. + */ +export function isReduced(x: any): boolean; + +/** + * Function composition. Take N function and return their composition. + */ +export function comp(...args: T[]): T; + +/** + * Take a predicate function and return its complement. + */ +export function complement(f: Function): Function; + +/** + * Identity function. + */ +export function identity(arg: T): T; + +export class Map implements Transformer { + constructor(f: (x: TInput) => TOutput, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Mapping transducer constructor + */ +export function map(f: (x: TInput) => TOutput): Transducer; + +export class Filter implements Transformer { + constructor(pred: (x: TInput) => boolean, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Filtering transducer constructor + */ +export function filter(pred: (x: TInput) => boolean): Transducer; + +/** + * Similar to filter except the predicate is used to + * eliminate values. + */ +export function remove(pred: (x: TInput) => boolean): Transducer; + +export class Keep implements Transformer { + constructor(f: (x: TInput) => any, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A keeping transducer. Keep inputs as long as the provided + * function does not return null or undefined. + */ +export function keep(f: (x: TInput) => any): Transducer; + +export class KeepIndexed implements Transformer { + constructor(f: (i: number, x: TInput) => any, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Like keep but the provided function will be passed the + * index as the fist argument. + */ +export function keepIndexed(f: (i: number, x: TInput) => any): Transducer; + +export class Take implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult | Reduced; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A take transducer constructor. Will take n values before + * returning a reduced result. + */ +export function take(n: number): Transducer; + +export class TakeWhile implements Transformer { + constructor(pred: (n: TInput) => boolean, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult | Reduced; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * Like the take transducer except takes as long as the pred + * return true for inputs. + */ +export function takeWhile(pred: (n: TInput) => boolean): Transducer; + +export class TakeNth implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A transducer that takes every Nth input + */ +export function takeNth(n: number): Transducer; + +export class Drop implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A dropping transducer constructor + */ +export function drop(n: number): Transducer; + +export class DropWhile implements Transformer { + constructor(pred: (input: TInput) => boolean, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; +} + +/** + * A dropping transducer that drop inputs as long as + * pred is true. + */ +export function dropWhile(pred: (input: TInput) => boolean): Transducer; + +export class PartitionBy implements Transformer { + constructor(f: (input: TInput) => any, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TResult +} + +/** + * A partitioning transducer. Collects inputs into + * arrays as long as predicate remains true for contiguous + * inputs. + */ +export function partitionBy(f: (input: TInput) => any): Transducer; + +export class PartitionAll implements Transformer { + constructor(n: number, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TResult +} + +/** + * A partitioning transducer. Collects inputs into + * arrays of size N. + */ +export function partitionAll(n: number): Transducer; + +export class Completing implements CompletingTransformer { + constructor(cf: (result: TResult) => TCompleteResult, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TCompleteResult +} + +/** + * A completing transducer constructor. Useful to provide cleanup + * logic at the end of a reduction/transduction. + */ +export function completing(cf: (result: TResult) => TCompleteResult): CompletingTransformer; + +export class Wrap implements Transformer { + constructor(stepFn: Reducer, xf: Transformer); + ['@@transducer/init'](): TResult; + ['@@transducer/step'](result: TResult, input: TInput): TResult + ['@@transducer/result'](result: TResult): TResult +} + +/** + * Take a two-arity reducing function where the first argument is the + * accumluation and the second argument is the next input and convert + * it into a transducer transformer object. + */ +export function wrap(stepFn: Reducer): Transducer; + +/** + * Given a transformer return a concatenating transformer + */ +export function cat(xf: Transformer): Transformer ; + +/** + * A mapping concatenating transformer + */ +export function mapcat(f: (arr: TInput[]) => TOutput[]): Transducer; + +/** + * Given a transducer, a builder function, an initial value + * and a iterable collection - returns the reduction. + */ +export function transduce( + xf: Transducer, + f: Transformer | Reducer, + init: TResult, + coll: TInput[] | Iterator | string | Object): TResult; + +/** + * Given a transducer, an intial value and a + * collection - returns the reduction. + */ +export function reduce( + xf: Transducer, + init: TResult, + coll: TInput[] | Iterator | string | Object): TResult; + +/** + * Reduce a value into the given empty value using a transducer. + */ +export function into( + empty: TResult, + xf: Transducer, + coll: TInput[] | Iterator | string | Object): TResult; + +/** + * Convert a transducer transformer object into a function so + * that it can be used with existing reduce implementation i.e. native, + * Underscore, lodash + */ +export function toFn( + xf: Transducer, + builder: Reducer | Transformer +): Reducer; + +/** + * A transformer which simply returns the first input. + */ +export function first(): Wrap; + +/** + * Ensure that a value is reduced. If already reduced will not re-wrap. + */ +export function ensureReduced(x: TResult | Reduced): Reduced; + +/** + * Ensure a value is not reduced. Unwraps if reduced. + */ +export function unreduced(x: TResult | Reduced): TResult; + +/** + * Returns the value of a reduced result. + */ +export function deref(x: Reduced): TResult; diff --git a/transducers-js/transducers-js-tests.ts b/transducers-js/transducers-js-tests.ts index 21c527be41..f40575fe72 100644 --- a/transducers-js/transducers-js-tests.ts +++ b/transducers-js/transducers-js-tests.ts @@ -1,6 +1,3 @@ -/// -/// - // tests taken from https://github.com/cognitect-labs/transducers-js import * as t from 'transducers-js'; @@ -13,16 +10,16 @@ var map = t.map, // basic usage -var inc = function(n: number) { return n + 1; }; -var isEven = function(n: number) { return n % 2 == 0; }; +function inc(n: number) { return n + 1; }; +function isEven(n: number) { return n % 2 === 0; }; var xf = comp(map(inc), filter(isEven)); -console.log(into([], xf, [0,1,2,3,4])); // [2,4] +console.log(into([], xf, [0, 1, 2, 3, 4])); // [2, 4] // integration -var arr = [0,1,2,3,4,5,6,7,8,9,10], - apush = function(arr: number[], x: number) { arr.push(x); return arr; }, +var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + apush = (arr: number[], x: number) => { arr.push(x); return arr; }, xf = comp(map(inc), filter(isEven)), toFn = t.toFn; @@ -33,14 +30,12 @@ _(arr).reduce(toFn(xf, apush), []); // underscore or lodash import * as Immutable from 'immutable'; -var inc = function(n: number): number { return n + 1; }; -var isEven = function(n: number): boolean { return n % 2 == 0; }; -var sum = function(a: number, b: number): number { return a + b; }; +function sum(a: number, b: number): number { return a + b; }; var transduce = t.transduce; var largeVector = Immutable.List(); -for(var i = 0; i < 1000000; i++) { +for (var i = 0; i < 1000000; i++) { largeVector = largeVector.push(i); } @@ -48,121 +43,109 @@ for(var i = 0; i < 1000000; i++) { largeVector.map(inc).filter(isEven).reduce(sum); // faster with transducers -var xf = comp(map(inc),filter(isEven)); +var xf = comp(map(inc), filter(isEven)); transduce(xf, sum, 0, largeVector); // source examples -function mapExample () { - var inc = function(n: number) { return n+1; }; +function mapExample() { var xf = t.map(inc); - t.into([], xf, [1,2,3]); // [2,3,4] + t.into([], xf, [1, 2, 3]); // [2, 3, 4] } -function filterExample () { - var isEven = function(n: number) { return n % 2 == 0; }; +function filterExample() { var xf = t.filter(isEven); - t.into([], xf, [0,1,2,3,4]); // [0,2,4]; + t.into([], xf, [0, 1, 2, 3, 4]); // [0, 2, 4]; } -function removeExample () { - var isEven = function(n: number) { return n % 2 == 0; }; +function removeExample() { var xf = t.remove(isEven); - t.into([], xf, [0,1,2,3,4]); // [1,3]; + t.into([], xf, [0, 1, 2, 3, 4]); // [1, 3]; } -function complementExample () { - var isEven = function(n: number) { return n % 2 == 0; }; +function complementExample() { var isOdd = t.complement(isEven); } -function keepIndexedExample () { - var xf = t.keepIndexed(function(i: number, x: string|number) { if (typeof x == "string") return "cool"; }); - t.into([], xf, [0,1,"foo",3,4,"bar"]); // ["foo","bar"] +function keepIndexedExample() { + var xf = t.keepIndexed((i: number, x: string|number) => { if (typeof x === "string") return "cool"; }); + t.into([], xf, [0, 1, "foo", 3, 4, "bar"]); // ["foo", "bar"] } -function takeExample () { +function takeExample() { var xf = t.take(3); - t.into([], xf, [0,1,2,3,4,5]); // [0,1,2]; + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [0, 1, 2]; } -function takeWhileExample () { - var xf = t.takeWhile(function(n) { return n < 3; }); - t.into([], xf, [0,1,2,3,4,5]); // [0,1,2]; +function takeWhileExample() { + var xf = t.takeWhile(n => n < 3); + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [0, 1, 2]; } -function intoExample () { - var inc = function(n: number) { return n+1; }; - var isEven = function(n: number) { return n % 2 == 0; }; - var apush = function(arr: number[], x: number) { arr.push(x); return arr; }; - var xf = t.comp(t.map(inc),t.filter(isEven)); - t.into([], xf, [1,2,3,4]); // [2,4] +function intoExample() { + var xf = t.comp(t.map(inc), t.filter(isEven)); + t.into([], xf, [1, 2, 3, 4]); // [2, 4] } -function toFnExample () { - var arr = [0,1,2,3,4,5]; - var apush = function(arr: number[], x: number) { arr.push(x); return arr; }; - var xf = t.comp(t.map(inc),t.filter(isEven)); - arr.reduce(t.toFn(xf, apush), []); // [2,4,6] +function toFnExample() { + var arr = [0, 1, 2, 3, 4, 5]; + var xf = t.comp(t.map(inc), t.filter(isEven)); + arr.reduce(t.toFn(xf, apush), []); // [2, 4, 6] } -function takeNthExample () { +function takeNthExample() { var xf = t.takeNth(3); - t.into([], xf, [0,1,2,3,4,5]); // [2,5]; + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [2, 5]; } -function dropExample () { +function dropExample() { var xf = t.drop(3); - t.into([], xf, [0,1,2,3,4,5]); // [3,4,5]; + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [3, 4, 5]; } -function dropWhileExample () { - var xf = t.dropWhile(function(n: number) { return n < 3; }); - t.into([], xf, [0,1,2,3,4,5]); // [3,4,5]; +function dropWhileExample() { + var xf = t.dropWhile(n => n < 3); + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [3, 4, 5]; } -function partitionByExample () { - var xf = t.partitionBy(function(x: string|number) { return typeof x == "string"; }); - t.into([], xf, [0,1,"foo","bar",2,3,"bar","baz"]); // [[0,1],["foo","bar"],[2,3],["bar","baz"]]; +function partitionByExample() { + var xf = t.partitionBy((x: string|number) => typeof x === "string"); + t.into([], xf, [0, 1, "foo", "bar", 2, 3, "bar", "baz"]); // [[0, 1], ["foo", "bar"], [2, 3], ["bar", "baz"]]; } -function partitionAllExample () { +function partitionAllExample() { var xf = t.partitionAll(3); - t.into([], xf, [0,1,2,3,4,5]); // [[0,1,2],[3,4,5]] + t.into([], xf, [0, 1, 2, 3, 4, 5]); // [[0, 1, 2], [3, 4, 5]] } -function wrapExample () { - var arrayPush = t.wrap(function(arr: number[], x: number) { arr.push(x); return arr; }); +function wrapExample() { + var arrayPush = t.wrap((arr: number[], x: number) => { arr.push(x); return arr; }); } -function ensureReducedExample () { +function ensureReducedExample() { var x = t.ensureReduced(1); var y = t.ensureReduced(x); x === y; // true } -function unreducedExample () { +function unreducedExample() { var x = t.reduced(1); t.unreduced(x); // 1 t.unreduced(t.unreduced(x)); // 1 } -function catExample () { - var reverse = function(arr: number[]) { - var arr: number[] = Array.prototype.slice.call(arr, 0); - arr.reverse(); - return arr; - }; - var xf = t.comp(t.map(reverse), t.cat); - t.into([], xf, [[3,2,1],[6,5,4]]); // [1,2,3,4,5,6] +function reverse(arr: number[]) { + var arr: number[] = Array.prototype.slice.call(arr, 0); + arr.reverse(); + return arr; } -function mapcatExample () { - var reverse = function(arr: number[]) { - var arr: number[] = Array.prototype.slice.call(arr, 0); - arr.reverse(); - return arr; - }; +function catExample() { + var xf = t.comp(t.map(reverse), t.cat); + t.into([], xf, [[3, 2, 1], [6, 5, 4]]); // [1, 2, 3, 4, 5, 6] +} + +function mapcatExample() { var xf = t.mapcat(reverse); - t.into([], xf, [[3,2,1],[6,5,4]]); // [1,2,3,4,5,6] + t.into([], xf, [[3, 2, 1], [6, 5, 4]]); // [1, 2, 3, 4, 5, 6] } diff --git a/transducers-js/tslint.json b/transducers-js/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/transducers-js/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/uikit/tslint.json b/uikit/tslint.json index 192203ab54..377cc837d4 100644 --- a/uikit/tslint.json +++ b/uikit/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/uikit/uikit-tests.ts b/uikit/uikit-tests.ts index 200a7a470f..5a28b61682 100644 --- a/uikit/uikit-tests.ts +++ b/uikit/uikit-tests.ts @@ -2,7 +2,7 @@ function testDropdown() { UIkit.dropdown("#parent"); UIkit.dropdown($("#parent")); - let options: UIkit.DropdownOptions = { + const options: UIkit.DropdownOptions = { pos: 'bottom-center', mode: 'click', remaintime: 150, @@ -24,7 +24,7 @@ function testDropdown() { function testModal() { UIkit.modal.alert("Attention!"); - let options: UIkit.ModalOptions = { + const options: UIkit.ModalOptions = { keyboard: true, bgclose: true, minScrollHeight: 150, @@ -37,7 +37,7 @@ function testModal() { UIkit.modal.confirm("Are you sure?", () => {}, () => {}, {}); UIkit.modal.confirm("Are you sure?", () => {}, {}); - UIkit.modal.prompt("Name:", 'value', function (newvalue:string) { + UIkit.modal.prompt("Name:", 'value', (newvalue: string) => { // will be executed on submit. }); var modal = UIkit.modal.blockUI("Any content..."); @@ -62,11 +62,11 @@ function testLightBox() { var element = "#group"; var lightbox = UIkit.lightbox(element, {/* options */}); var lightbox2 = UIkit.lightbox.create([ - {source: 'http://url/to/video.mp4', 'type': 'video'}, - {'source': 'http://url/to/image.jpg', 'type': 'image'} + {source: 'http://url/to/video.mp4', type: 'video'}, + {source: 'http://url/to/image.jpg', type: 'image'} ]); lightbox2.show(); - var lightbox3 = UIkit.lightbox(element) + var lightbox3 = UIkit.lightbox(element); } function testAutoComplete() { @@ -83,20 +83,20 @@ function testHtmlEditor() { } function testSlider() { - var slider = UIkit.slider("element", {}) + var slider = UIkit.slider("element", {}); } function testSlideSet() { - var slideset = UIkit.slideset("element", {}) + var slideset = UIkit.slideset("element", {}); } function testSlideShow() { - var slideshow = UIkit.slideshow("element", {}) + var slideshow = UIkit.slideshow("element", {}); } function testParallax() { - var parallax = UIkit.parallax("element", {}) + var parallax = UIkit.parallax("element", {}); } function testAccordion() { - var accordion = UIkit.accordion("element", {}) + var accordion = UIkit.accordion("element", {}); } @@ -121,7 +121,7 @@ function testNotify() { function testSearch() { - var search = UIkit.search("element", {}) + var search = UIkit.search("element", {}); } function testNestable() { @@ -134,15 +134,15 @@ function testStick() { var sticky = UIkit.sticky('element', {}); } function testTimePicker() { - var timepicker = UIkit.timepicker('element', {}) + var timepicker = UIkit.timepicker('element', {}); } function testTooltip() { - var tooltip = UIkit.tooltip('element', {}) + var tooltip = UIkit.tooltip('element', {}); } function testUpload() { - $(function(){ + $(() => { var progressbar = $("#progressbar"), bar = progressbar.find('.uk-progress-bar'), @@ -152,25 +152,25 @@ function testUpload() { allow : '*.(jpg|jpeg|gif|png)', // allow only images - loadstart: function() { + loadstart() { bar.css("width", "0%").text("0%"); progressbar.removeClass("uk-hidden"); }, - progress: function(percent: number) { + progress(percent: number) { percent = Math.ceil(percent); - bar.css("width", percent+"%").text(percent+"%"); + bar.css("width", percent + "%").text(percent + "%"); }, - allcomplete: function(response: any) { + allcomplete(response: any) { bar.css("width", "100%").text("100%"); - setTimeout(function(){ + setTimeout(() => { progressbar.addClass("uk-hidden"); }, 250); - alert("Upload Completed") + alert("Upload Completed"); } }; @@ -185,15 +185,15 @@ function testUpload() { allow: '*.(jpg|jpeg|gif|png)', // allow only images - loadstart: function () { + loadstart: () => { }, - progress: function (percent:number) { + progress: (percent: number) => { }, - allcomplete: function (response:any) { + allcomplete: (response: any) => { } }); @@ -203,15 +203,15 @@ function testUpload() { allow: '*.(jpg|jpeg|gif|png)', // allow only images - loadstart: function () { + loadstart: () => { }, - progress: function (percent:number) { + progress: (percent: number) => { }, - allcomplete: function (response:any) { + allcomplete: (response: any) => { } }); diff --git a/umzug/index.d.ts b/umzug/index.d.ts index 0395d09fd7..af3618df7e 100644 --- a/umzug/index.d.ts +++ b/umzug/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sequelize/umzug // Definitions by: Ivan Drinchev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// /// diff --git a/universal-router/index.d.ts b/universal-router/index.d.ts index 6acba5c179..e9f64a1846 100644 --- a/universal-router/index.d.ts +++ b/universal-router/index.d.ts @@ -1,70 +1,68 @@ -// Type definitions for universal-router +// Type definitions for universal-router 1.2 // Project: https://github.com/kriasoft/universal-router -// Definitions by: Jack Moore +// Definitions by: Jack Moore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "universal-router" { - /** - * Params is a key/value object that represents extracted URL paramters. Each - * URL parameter resolves to a string. - */ - export interface Params { - [key: string]: string; - } +/** + * Params is a key/value object that represents extracted URL paramters. Each + * URL parameter resolves to a string. + */ +export interface Params { + [key: string]: string; +} - /** - * Context represents the context that is passed as the second argument - * passed to resolve. By default, it only is require to contain a path, but - * can be extended by the way of generics. - */ - export interface Context { - path: string; - } +/** + * Context represents the context that is passed as the second argument + * passed to resolve. By default, it only is require to contain a path, but + * can be extended by the way of generics. + */ +export interface Context { + path: string; +} - /** - * ActionContext is similar to Context, with the exception of an added params - * object. ActionContext is passed as the first argument to the action - * function. - */ - export interface ActionContext extends Context { - params: Params; - } +/** + * ActionContext is similar to Context, with the exception of an added params + * object. ActionContext is passed as the first argument to the action + * function. + */ +export interface ActionContext extends Context { + params: Params; +} - /** - * A Route is a singular route in your application. It contains a path, an - * action function, and optional children which are an array of Route. - * - * @template C User context that is made union with ActionContext. - * @template R Result that every action function resolves to. If the action - * returns a Promise, R can be the type the Promise resolves to. - */ - export interface Route { - path: string; - action: (ctx: ActionContext & C, params: Params) => R | Promise | void; - children?: Routes; - } +/** + * A Route is a singular route in your application. It contains a path, an + * action function, and optional children which are an array of Route. + * + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ +export interface Route { + path: string; + action: (ctx: ActionContext & C, params: Params) => R | Promise | void; + children?: Routes; +} - /** - * Routes in an array of type Route. - * @template C User context that is made union with ActionContext. - * @template R Result that every action function resolves to. If the action - * returns a Promise, R can be the type the Promise resolves to. - */ - export type Routes = Route[]; +/** + * Routes in an array of type Route. + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ +export type Routes = Array>; - /** - * Resolve function that is given routes and a path or context object. - * Returns a Promise that resolves to result of the action function of the - * matched route. - * - * @template C User context that is made union with Context. - * @template R Result that every action function resolves to. If the action - * returns a Promise, R can be the type the Promise resolves to. - * - * @param {Routes | Route} routes - Single route or array of routes. - * @param {string | String | Context & C} pathOrContext - path to resolve or - * context object that contains the path along with other data. - * @return {Promise} - Result of matched action function wrapped in a Promsie. - */ - export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise -} \ No newline at end of file +/** + * Resolve function that is given routes and a path or context object. + * Returns a Promise that resolves to result of the action function of the + * matched route. + * + * @template C User context that is made union with Context. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + * + * @param {Routes | Route} routes - Single route or array of routes. + * @param {string | String | Context & C} pathOrContext - path to resolve or + * context object that contains the path along with other data. + * @return {Promise} - Result of matched action function wrapped in a Promsie. + */ +export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise; diff --git a/universal-router/tsconfig.json b/universal-router/tsconfig.json index 18025f5a22..ca76eb8955 100644 --- a/universal-router/tsconfig.json +++ b/universal-router/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/universal-router/tslint.json b/universal-router/tslint.json new file mode 100644 index 0000000000..f05741c59b --- /dev/null +++ b/universal-router/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} diff --git a/universal-router/universal-router-tests.ts b/universal-router/universal-router-tests.ts index 2d8870952c..5964ee1a90 100644 --- a/universal-router/universal-router-tests.ts +++ b/universal-router/universal-router-tests.ts @@ -59,7 +59,7 @@ const routes5 = [ async action(ctx: ActionContext, { username }: Params) { const waitable = async (name: string) => { console.log(`Welcome ${name}`); - } + }; await waitable(username); } } diff --git a/update-notifier/tslint.json b/update-notifier/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/update-notifier/tslint.json +++ b/update-notifier/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/usb/tslint.json b/usb/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/usb/tslint.json +++ b/usb/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/usb/usb-tests.ts b/usb/usb-tests.ts index f1963307fc..31e287c5b8 100644 --- a/usb/usb-tests.ts +++ b/usb/usb-tests.ts @@ -81,7 +81,7 @@ inEndpoint.direction = "in"; inEndpoint.transferType = 1; inEndpoint.timeout = 1; inEndpoint.descriptor = endpointDesc; -const xferInEndpoint: usb.InEndpoint = inEndpoint.transfer(1, (error: string, data: Buffer) => { return inEndpoint; }); +const xferInEndpoint: usb.InEndpoint = inEndpoint.transfer(1, (error: string, data: Buffer) => inEndpoint); inEndpoint.startPoll(1, 1); inEndpoint.stopPoll(() => null); @@ -95,7 +95,7 @@ outEndpoint.transferWithZLP(new Buffer([]), (error: string) => null); const findByDevice: usb.Device = usb.findByIds(1, 1); usb.on("hey", (device: usb.Device) => null); -const deviceList: Array = usb.getDeviceList(); +const deviceList: usb.Device[] = usb.getDeviceList(); usb.setDebugLevel(1); const CHECK_LIBUSB_CLASS_PER_INTERFACE: number = usb.LIBUSB_CLASS_PER_INTERFACE; diff --git a/user-home/user-home-tests.ts b/user-home/user-home-tests.ts index 41ef1e31a8..056a31095e 100644 --- a/user-home/user-home-tests.ts +++ b/user-home/user-home-tests.ts @@ -1,4 +1,4 @@ import userHome = require('user-home'); console.log(userHome); -//=> '/Users/sindresorhus' \ No newline at end of file +// => '/Users/sindresorhus' \ No newline at end of file diff --git a/validator/index.d.ts b/validator/index.d.ts index 0eae66c3c9..74bf331ed6 100644 --- a/validator/index.d.ts +++ b/validator/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for validator.js v5.7.0 +// Type definitions for validator.js v6.2 // Project: https://github.com/chriso/validator.js -// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad +// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ValidatorJS { @@ -276,6 +276,9 @@ declare namespace ValidatorJS { interface IsIntOptions { min?: number; max?: number; + allow_leading_zeroes?: boolean; + lt?: number; + gt?: number; } // options for IsLength diff --git a/vectorious/index.d.ts b/vectorious/index.d.ts index 63b53d20bf..c68e87236c 100644 --- a/vectorious/index.d.ts +++ b/vectorious/index.d.ts @@ -269,6 +269,8 @@ export class Vector { export class Matrix { T: Matrix; + + shape: number[]; /** * @method constructor @@ -586,4 +588,4 @@ export class Matrix { public toArray (): number[][]; } -export class BLAS {} \ No newline at end of file +export class BLAS {} diff --git a/verror/tslint.json b/verror/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/verror/tslint.json +++ b/verror/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/victory/index.d.ts b/victory/index.d.ts index 9be6990469..70d1ecb6f1 100644 --- a/victory/index.d.ts +++ b/victory/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/FormidableLabs/victory // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/videojs/index.d.ts b/videojs/index.d.ts index 9e4156ece6..5b894b0912 100644 --- a/videojs/index.d.ts +++ b/videojs/index.d.ts @@ -1,63 +1,62 @@ -// Type definitions for Video.js +// Type definitions for Video.js 5.16 // Project: https://github.com/zencoder/video-js // Definitions by: Vincent Bortone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// The Video.js API allows you to interact with the video through Javascript, whether the browser is playing the video through HTML5 video, Flash, or any other supported playback technologies. +// The Video.js API allows you to interact with the video through +// Javascript, whether the browser is playing the video through HTML5 +// video, Flash, or any other supported playback technologies. -interface VideoJSOptions { - techOrder?: string[]; - html5?: Object; - width?: number; - height?: number; - defaultVolume?: number; - children?: Object; - controls?: boolean; - src?: string; - autoplay?: boolean; - preload?: string; +declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; +export = videojs; +export as namespace videojs; + +declare namespace videojs { + + interface PlayerOptions { + techOrder?: string[]; + html5?: any; + width?: number; + height?: number; + defaultVolume?: number; + children?: string[]; + controls?: boolean; + src?: string; + autoplay?: boolean; + preload?: string; + } + + interface Source { + type: string; + src: string; + } + + interface Player { + play(): Player; + pause(): Player; + paused(): boolean; + src(newSource: string | Source | Source[]): Player; + currentTime(seconds: number): Player; + currentTime(): number; + duration(): number; + buffered(): TimeRanges; + bufferedPercent(): number; + volume(percentAsDecimal: number): TimeRanges; + volume(): number; + width(): number; + width(pixels: number): Player; + height(): number; + height(pixels: number): Player; + size(width: number, height: number): Player; + requestFullScreen(): Player; + cancelFullScreen(): Player; + ready(callback: (this: Player) => void ): Player; + on(eventName: string, callback: (eventObject: Event) => void ): void; + off(eventName?: string, callback?: (eventObject: Event) => void ): void; + dispose(): void; + addRemoteTextTrack(options: {}): HTMLTrackElement; + removeRemoteTextTrack(track: HTMLTrackElement): void; + poster(val?: string): string | Player; + playbackRate(rate?: number): number; + } } - -interface VideoJSSource { - type: string; - src: string; -} - -interface VideoJSPlayer { - play(): VideoJSPlayer; - pause(): VideoJSPlayer; - paused(): boolean; - src(newSource: string): VideoJSPlayer; - src(newSource: VideoJSSource): VideoJSPlayer; - src(newSource: VideoJSSource[]): VideoJSPlayer; - currentTime(seconds: number): VideoJSPlayer; - currentTime(): number; - duration(): number; - buffered(): TimeRanges; - bufferedPercent(): number; - volume(percentAsDecimal: number): TimeRanges; - volume(): number; - width(): number; - width(pixels: number): VideoJSPlayer; - height(): number; - height(pixels: number): VideoJSPlayer; - size(width: number, height: number): VideoJSPlayer; - requestFullScreen(): VideoJSPlayer; - cancelFullScreen(): VideoJSPlayer; - ready(callback: () => void ): VideoJSPlayer; - on(eventName: string, callback: (eventObject: Event) => void ): void; - off(eventName: string, callback: () => void ): void; - off(eventName: string): void; - off(): void; - dispose(): void; - addRemoteTextTrack(options : {}) : HTMLTrackElement; - removeRemoteTextTrack(track : HTMLTrackElement) : void; - poster(val?: string) : string|VideoJSPlayer; - playbackRate(rate?: number) : number; -} - -interface VideoJSStatic { - (id: any, options?: VideoJSOptions, ready?: () => void): VideoJSPlayer; -} - -declare var videojs:VideoJSStatic; diff --git a/videojs/tsconfig.json b/videojs/tsconfig.json index b9feff990e..f8dd93e0df 100644 --- a/videojs/tsconfig.json +++ b/videojs/tsconfig.json @@ -6,8 +6,8 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/videojs/tslint.json b/videojs/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/videojs/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/videojs/videojs-tests.ts b/videojs/videojs-tests.ts index 6b2c90184e..6f9907ea1c 100644 --- a/videojs/videojs-tests.ts +++ b/videojs/videojs-tests.ts @@ -1,35 +1,33 @@ // Tests for Video.js API +import * as videojs from 'videojs'; -videojs("example_video_1").ready(function(){ - - var myPlayer:VideoJSPlayer = this; - +videojs("example_video_1").ready(function() { // EXAMPLE: Start playing the video. - myPlayer.play(); + this.play(); - myPlayer.pause(); + this.pause(); - var isPaused: boolean = myPlayer.paused(); - var isPlaying: boolean = !myPlayer.paused(); + var isPaused: boolean = this.paused(); + var isPlaying: boolean = !this.paused(); - myPlayer.src("http://www.example.com/path/to/video.mp4"); + this.src("http://www.example.com/path/to/video.mp4"); - myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); + this.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); - myPlayer.src([ + this.src([ { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } ]); - var whereYouAt: number = myPlayer.currentTime(); + var whereYouAt: number = this.currentTime(); - myPlayer.currentTime(120); // 2 minutes into the video + this.currentTime(120); // 2 minutes into the video - var howLongIsThis: number = myPlayer.duration(); + var howLongIsThis: number = this.duration(); - var bufferedTimeRange: TimeRanges = myPlayer.buffered(); + var bufferedTimeRange: TimeRanges = this.buffered(); // Number of different ranges of time have been buffered. Usually 1. var numberOfRanges: number = bufferedTimeRange.length; @@ -43,31 +41,44 @@ videojs("example_video_1").ready(function(){ // Length in seconds of the first time range var firstRangeLength: number = firstRangeEnd - firstRangeStart; - var howMuchIsDownloaded: number = myPlayer.bufferedPercent(); + var howMuchIsDownloaded: number = this.bufferedPercent(); - var howLoudIsIt: number = myPlayer.volume(); + var howLoudIsIt: number = this.volume(); - myPlayer.volume(0.5); // Set volume to half + this.volume(0.5); // Set volume to half - var howWideIsIt: number = myPlayer.width(); + var howWideIsIt: number = this.width(); - myPlayer.width(640); + this.width(640); - var howTallIsIt: number = myPlayer.height(); + var howTallIsIt: number = this.height(); - myPlayer.height(480); + this.height(480); - myPlayer.size(640,480); + this.size(640, 480); - myPlayer.requestFullScreen(); + this.requestFullScreen(); - myPlayer.cancelFullScreen(); + testEvents(this); +}); - - var myFunc = function(){ - var myPlayer: VideoJSPlayer = this; +function testEvents(myPlayer: videojs.Player) { + const myFunc = function(this: videojs.Player) { // Do something when the event is fired }; - //myPlayer.addEvent("volumechange", myFunc); - //myPlayer.removeEvent("volumechange", myFunc); -}); + myPlayer.on("error", myFunc); + // Removes the specified listener only. + myPlayer.off("error", myFunc); + + + const myFuncWithArg = function(this: videojs.Player, e: Event) { + // Do something when the event is fired + }; + myPlayer.on("volumechange", myFuncWithArg); + // Removes all listeners for the given event type. + myPlayer.off("volumechange"); + + myPlayer.on("loadeddata", () => { /* Some handler. */ }); + // Removes all listeners. + myPlayer.off(); +} diff --git a/vinyl-fs/.editorconfig b/vinyl-fs/.editorconfig new file mode 100644 index 0000000000..831139084b --- /dev/null +++ b/vinyl-fs/.editorconfig @@ -0,0 +1,3 @@ +[*.ts] +indent_style = space +indent_size = 3 diff --git a/vinyl-fs/index.d.ts b/vinyl-fs/index.d.ts index 350ee527b5..4fa6101b69 100644 --- a/vinyl-fs/index.d.ts +++ b/vinyl-fs/index.d.ts @@ -1,25 +1,26 @@ -// Type definitions for vinyl-fs +// Type definitions for vinyl-fs 2.4 // Project: https://github.com/wearefractal/vinyl-fs // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// -/// declare global { namespace NodeJS { interface WritableStream { - write(buffer: any/* Vinyl.File */, cb?: Function): boolean; + write(buffer: any/* Vinyl.File */, cb?: (err?: Error) => void): boolean; } } } -import _events = require("events"); -import File = require("vinyl"); -import globStream = require("glob-stream"); +import * as _events from 'events'; +import * as File from 'vinyl'; +import * as globStream from 'glob-stream'; + +interface SrcOptions extends globStream.Options { + /** Prevents stream from emitting an error when file not found. */ + allowEmpty?: boolean; -interface ISrcOptions extends globStream.Options { /** Specifies the working directory the folder is relative to */ cwd?: string; @@ -62,7 +63,7 @@ interface ISrcOptions extends globStream.Options { * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) * @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream */ -declare function src(globs: string|string[], opt?: ISrcOptions): NodeJS.ReadWriteStream; +declare function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; /** * This is just a glob-watcher @@ -80,7 +81,15 @@ declare function watch(globs: string|string[], cb?: (outEvt: { type: any; path: * Globs are executed in order, so negations should follow positive globs * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) */ -declare function watch(globs: string|string[], opt?: { interval?: number; debounceDelay?: number; cwd?: string; maxListeners?: Function; }, cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; +declare function watch( + globs: string|string[], + opt?: { + interval?: number; + debounceDelay?: number; + cwd?: string; + maxListeners?: () => number; + }, + cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; /** * On write the stream will save the vinyl File to disk at the folder/cwd specified. diff --git a/vinyl-fs/tsconfig.json b/vinyl-fs/tsconfig.json index 60247086b9..d8cea65d47 100644 --- a/vinyl-fs/tsconfig.json +++ b/vinyl-fs/tsconfig.json @@ -1,22 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "vinyl-fs-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vinyl-fs-tests.ts" + ] +} diff --git a/vinyl-fs/tslint.json b/vinyl-fs/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/vinyl-fs/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/vinyl-fs/vinyl-fs-tests.ts b/vinyl-fs/vinyl-fs-tests.ts index 795b38b4aa..33d031f521 100644 --- a/vinyl-fs/vinyl-fs-tests.ts +++ b/vinyl-fs/vinyl-fs-tests.ts @@ -1,12 +1,9 @@ -/// -/// - // from src -import vfs = require('vinyl-fs'); +import * as vfs from 'vinyl-fs'; -import path = require('path'); -import fs = require('fs'); // require('graceful-fs'); +import * as path from 'path'; +import * as fs from 'fs'; // require('graceful-fs'); // import bufEqual = require('buffer-equal'); declare var bufEqual: any; @@ -16,22 +13,22 @@ import File = require('vinyl'); // var spies = require('./spy'); declare var spies: any; -import should = require('should'); -require('mocha'); +import * as should from 'should'; +import 'mocha'; declare var gulp: any; declare var bufferStream: any; -var dataWrap = function (fn: any) { - return function (data: any, enc: any, cb: any) { +var dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { fn(data); cb(); }; }; -describe('source stream', function () { +describe('source stream', () => { - it('should explode on invalid glob (empty)', function (done) { + it('should explode on invalid glob (empty)', done => { var stream: any; try { stream = gulp.src(); @@ -42,7 +39,7 @@ describe('source stream', function () { } }); - it('should explode on invalid glob (number)', function (done) { + it('should explode on invalid glob (number)', done => { var stream: any; try { stream = gulp.src(123); @@ -53,7 +50,7 @@ describe('source stream', function () { } }); - it('should explode on invalid glob (empty array)', function (done) { + it('should explode on invalid glob (empty array)', done => { var stream: any; try { stream = gulp.src([]); @@ -64,7 +61,7 @@ describe('source stream', function () { } }); - it('should pass through writes', function (done) { + it('should pass through writes', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); @@ -75,7 +72,7 @@ describe('source stream', function () { contents: expectedContent }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); bufEqual(buffered[0].contents, expectedContent).should.equal(true); @@ -91,11 +88,11 @@ describe('source stream', function () { stream.end(); }); - it('should glob a file with default settings', function (done) { + it('should glob a file with default settings', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); should.exist(buffered[0].stat); buffered[0].path.should.equal(expectedPath); @@ -111,11 +108,11 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a file with default settings and relative cwd', function (done) { + it('should glob a file with default settings and relative cwd', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); should.exist(buffered[0].stat); buffered[0].path.should.equal(expectedPath); @@ -131,10 +128,10 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a directory with default settings', function (done) { + it('should glob a directory with default settings', done => { var expectedPath = path.join(__dirname, "./fixtures/wow"); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].path.should.equal(expectedPath); buffered[0].isNull().should.equal(true); @@ -149,11 +146,11 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a file with with no contents', function (done) { + it('should glob a file with with no contents', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].path.should.equal(expectedPath); buffered[0].isNull().should.equal(true); @@ -168,22 +165,22 @@ describe('source stream', function () { stream.pipe(bufferStream); }); - it('should glob a file with streaming contents', function (done) { + it('should glob a file with streaming contents', done => { var expectedPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedContent = fs.readFileSync(expectedPath); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); should.exist(buffered[0].stat); buffered[0].path.should.equal(expectedPath); buffered[0].isStream().should.equal(true); var contentBuffer = new Buffer([]); - var contentBufferStream = through(dataWrap(function (data: any) { + var contentBufferStream = through(dataWrap((data: any) => { contentBuffer = Buffer.concat([contentBuffer, data]); })); buffered[0].contents.pipe(contentBufferStream); - buffered[0].contents.once('end', function () { + buffered[0].contents.once('end', () => { bufEqual(contentBuffer, expectedContent); done(); }); @@ -210,28 +207,28 @@ import rimraf = require('rimraf'); // var File = require('vinyl'); // var should = require('should'); -require('mocha'); +// require('mocha'); -var wipeOut = function (cb: any) { +var wipeOut = (cb: any) => { rimraf(path.join(__dirname, "./out-fixtures/"), cb); }; -var dataWrap = function (fn: any) { - return function (data: any, enc: any, cb: any) { +var dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { fn(data); cb(); }; }; -var realMode = function (n: any) { +var realMode = (n: any) => { return n & parseInt("07777", 8); }; -describe('dest stream', function () { +describe('dest stream', () => { beforeEach(wipeOut); afterEach(wipeOut); - it('should explode on invalid folder', function (done) { + it('should explode on invalid folder', done => { var stream: any; try { stream = gulp.dest(); @@ -242,7 +239,7 @@ describe('dest stream', function () { } }); - it('should pass through writes with cwd', function (done) { + it('should pass through writes with cwd', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedFile = new File({ @@ -252,7 +249,7 @@ describe('dest stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -267,7 +264,7 @@ describe('dest stream', function () { stream.end(); }); - it('should pass through writes with default cwd', function (done) { + it('should pass through writes with default cwd', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var expectedFile = new File({ @@ -277,7 +274,7 @@ describe('dest stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -292,7 +289,7 @@ describe('dest stream', function () { stream.end(); }); - it('should not write null files', function (done) { + it('should not write null files', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -306,7 +303,7 @@ describe('dest stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -325,7 +322,7 @@ describe('dest stream', function () { stream.end(); }); - it('should write buffer files to the right folder with relative cwd', function (done) { + it('should write buffer files to the right folder with relative cwd', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -340,7 +337,7 @@ describe('dest stream', function () { contents: expectedContents }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -360,7 +357,7 @@ describe('dest stream', function () { stream.end(); }); - it('should write buffer files to the right folder', function (done) { + it('should write buffer files to the right folder', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -374,12 +371,12 @@ describe('dest stream', function () { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -400,7 +397,7 @@ describe('dest stream', function () { stream.end(); }); - it('should write streaming files to the right folder', function (done) { + it('should write streaming files to the right folder', done => { var inputPath = path.join(__dirname, "./fixtures/test.coffee"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test.coffee"); @@ -415,12 +412,12 @@ describe('dest stream', function () { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -438,14 +435,14 @@ describe('dest stream', function () { bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); stream.pipe(bufferStream); stream.write(expectedFile); - setTimeout(function () { + setTimeout(() => { contentStream.write(expectedContents); contentStream.end(); }, 100); stream.end(); }); - it('should write directories to the right folder', function (done) { + it('should write directories to the right folder', done => { var inputPath = path.join(__dirname, "./fixtures/test"); var inputBase = path.join(__dirname, "./fixtures/"); var expectedPath = path.join(__dirname, "./out-fixtures/test"); @@ -458,15 +455,13 @@ describe('dest stream', function () { cwd: __dirname, path: inputPath, contents: null, - stat: { - isDirectory: function () { - return true; - }, + stat: { + isDirectory: () => true, mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(expectedCwd, 'cwd should have changed'); @@ -487,7 +482,7 @@ describe('dest stream', function () { stream.end(); }); - it('should allow piping multiple dests in streaming mode', function (done) { + it('should allow piping multiple dests in streaming mode', done => { var inputPath1 = path.join(__dirname, "./out-fixtures/multiple-first"); var inputPath2 = path.join(__dirname, "./out-fixtures/multiple-second"); var inputBase = path.join(__dirname, "./out-fixtures/"); @@ -495,20 +490,20 @@ describe('dest stream', function () { var stream1 = vfs.dest('./out-fixtures/', { cwd: __dirname }); var stream2 = vfs.dest('./out-fixtures/', { cwd: __dirname }); var content = fs.readFileSync(srcPath); - var rename = through.obj(function (file: any, _: any, next: any) { + var rename = through.obj((file: any, _: any, next: any) => { file.path = inputPath2; this.push(file); next(); }); - stream1.on('data', function (file: any) { + stream1.on('data', (file: any) => { file.path.should.equal(inputPath1); - }) + }); stream1.pipe(rename).pipe(stream2); - stream2.on('data', function (file: any) { + stream2.on('data', (file: any) => { file.path.should.equal(inputPath2); - }).once('end', function () { + }).once('end', () => { fs.readFileSync(inputPath1, 'utf8').should.equal(content.toString()); fs.readFileSync(inputPath2, 'utf8').should.equal(content.toString()); done(); @@ -519,11 +514,11 @@ describe('dest stream', function () { path: inputPath1, cwd: __dirname, contents: content - }) + }); stream1.write(file); stream1.end(); - }) + }); }); @@ -535,29 +530,29 @@ describe('dest stream', function () { var chmodSpy = spies.chmodSpy; var statSpy = spies.statSpy; -var wipeOut = function (cb: any) { +var wipeOut = (cb: any) => { rimraf(path.join(__dirname, './out-fixtures/'), cb); spies.setError('false'); statSpy.reset(); chmodSpy.reset(); }; -var dataWrap = function (fn: any) { - return function (data: any, enc: any, cb: any) { +var dataWrap = (fn: any) => { + return (data: any, enc: any, cb: any) => { fn(data); cb(); }; }; -var realMode = function (n: any) { +var realMode = (n: any) => { return n & parseInt("07777", 8); }; -describe('symlink stream', function () { +describe('symlink stream', () => { beforeEach(wipeOut); afterEach(wipeOut); - it('should explode on invalid folder', function (done: any) { + it('should explode on invalid folder', (done: any) => { var stream: any; try { stream = gulp.symlink(); @@ -568,7 +563,7 @@ describe('symlink stream', function () { } }); - it('should pass through writes with cwd', function (done) { + it('should pass through writes with cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var expectedFile = new File({ @@ -578,7 +573,7 @@ describe('symlink stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -593,7 +588,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should pass through writes with default cwd', function (done) { + it('should pass through writes with default cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var expectedFile = new File({ @@ -603,7 +598,7 @@ describe('symlink stream', function () { contents: null }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); done(); @@ -618,7 +613,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should make link to the right folder with relative cwd', function (done) { + it('should make link to the right folder with relative cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -633,7 +628,7 @@ describe('symlink stream', function () { contents: expectedContents }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -654,7 +649,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should write buffer files to the right folder with function and relative cwd', function (done) { + it('should write buffer files to the right folder with function and relative cwd', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -669,7 +664,7 @@ describe('symlink stream', function () { contents: expectedContents }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -681,7 +676,7 @@ describe('symlink stream', function () { done(); }; - var stream = vfs.symlink(function (file) { + var stream = vfs.symlink(file => { should.exist(file); file.should.equal(expectedFile); return './out-fixtures'; @@ -694,7 +689,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should write buffer files to the right folder', function (done) { + it('should write buffer files to the right folder', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -708,12 +703,12 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -734,7 +729,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should write streaming files to the right folder', function (done) { + it('should write streaming files to the right folder', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -749,12 +744,12 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: contentStream, - stat: { + stat: { mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -772,14 +767,14 @@ describe('symlink stream', function () { bufferStream = through.obj(dataWrap(buffered.push.bind(buffered)), onEnd); stream.pipe(bufferStream); stream.write(expectedFile); - setTimeout(function () { + setTimeout(() => { contentStream.write(expectedContents); contentStream.end(); }, 100); stream.end(); }); - it('should write directories to the right folder', function (done) { + it('should write directories to the right folder', done => { var inputPath = path.join(__dirname, './fixtures/wow'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/wow'); @@ -792,15 +787,13 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: null, - stat: { - isDirectory: function () { - return true; - }, + stat: { + isDirectory: () => true, mode: expectedMode } }); - var onEnd = function () { + var onEnd = () => { buffered.length.should.equal(1); buffered[0].should.equal(expectedFile); buffered[0].cwd.should.equal(__dirname, 'cwd should have changed'); @@ -821,7 +814,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should use different modes for files and directories', function (done) { + it('should use different modes for files and directories', done => { var inputBase = path.join(__dirname, './fixtures'); var inputPath = path.join(__dirname, './fixtures/wow/suchempty'); var expectedBase = path.join(__dirname, './out-fixtures/wow'); @@ -835,7 +828,7 @@ describe('symlink stream', function () { stat: fs.statSync(inputPath) }); - var onEnd = function () { + var onEnd = () => { realMode(fs.lstatSync(expectedBase).mode).should.equal(expectedDirMode); realMode(buffered[0].stat.mode).should.equal(expectedFileMode); done(); @@ -855,7 +848,7 @@ describe('symlink stream', function () { stream.end(); }); - it('should report IO errors', function (done) { + it('should report IO errors', done => { var inputPath = path.join(__dirname, './fixtures/test.coffee'); var inputBase = path.join(__dirname, './fixtures/'); var expectedPath = path.join(__dirname, './out-fixtures/test.coffee'); @@ -869,7 +862,7 @@ describe('symlink stream', function () { cwd: __dirname, path: inputPath, contents: expectedContents, - stat: { + stat: { mode: expectedMode } }); @@ -878,19 +871,19 @@ describe('symlink stream', function () { fs.chmodSync(expectedBase, 0); var stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); - stream.on('error', function (err:any) { + stream.on('error', (err: any) => { err.code.should.equal('EACCES'); done(); }); stream.write(expectedFile); }); - ['end', 'finish'].forEach(function (eventName) { - it('should emit ' + eventName + ' event', function (done) { + ['end', 'finish'].forEach(eventName => { + it('should emit ' + eventName + ' event', done => { var srcPath = path.join(__dirname, './fixtures/test.coffee'); var stream = vfs.symlink('./out-fixtures/', { cwd: __dirname }); - stream.on(eventName, function () { + stream.on(eventName, () => { done(); }); @@ -904,7 +897,7 @@ describe('symlink stream', function () { stream.end(); }); }); - it('should check if it"s a vinyl file', function () { + it('should check if it"s a vinyl file', () => { var srcPath = path.join(__dirname, './fixtures/test.coffee'); var options = { path: srcPath, @@ -914,5 +907,5 @@ describe('symlink stream', function () { var file = new File(options); File.isVinyl(file).should.equal(true); File.isVinyl(options).should.equal(false); - }) + }); }); diff --git a/vis/index.d.ts b/vis/index.d.ts index 92b6ea6a08..b4e4c61923 100644 --- a/vis/index.d.ts +++ b/vis/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for vis.js 4.17 // Project: https://github.com/almende/vis -// Definitions by: Michaël Bitard , Adrian Caballero , Severin , kaktus40 , Matthieu Maitre +// Definitions by: Michaël Bitard +// Adrian Caballero +// Severin +// kaktus40 +// Matthieu Maitre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped type IdType = string | number; @@ -1497,6 +1501,7 @@ export interface Data { } export interface Node { + group?: string; id?: IdType; label?: string; x?: number; diff --git a/vis/tslint.json b/vis/tslint.json index 2221e40e4a..377cc837d4 100644 --- a/vis/tslint.json +++ b/vis/tslint.json @@ -1 +1 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ "extends": "../tslint.json" } diff --git a/vis/vis-tests.ts b/vis/vis-tests.ts index 804e69d96e..2b3b28fb7b 100644 --- a/vis/vis-tests.ts +++ b/vis/vis-tests.ts @@ -34,7 +34,7 @@ data.add([ ]); // subscribe to any change in the DataSet -data.on('*', function (event, properties, senderId) { +data.on('*', (event, properties, senderId) => { console.log('event', event, properties); }); @@ -54,8 +54,8 @@ console.log('item1', item1); // retrieve a filtered subset of the data var items = data.get({ - filter: function (item) { - return item.group == 1; + filter: (item) => { + return item.group === 1; } }); console.log('filtered items', items); @@ -77,7 +77,7 @@ console.log('formatted items', items); var data = new vis.DataSet(); // subscribe to any change in the DataSet -data.on('*', function (event, properties, senderId) { +data.on('*', (event, properties, senderId) => { console.log('event:', event, 'properties:', properties, 'senderId:', senderId); }); @@ -132,14 +132,14 @@ var dataset = new vis.DataSet(); // retrieve all items having a property group with value 2 var group2 = dataset.get({ - filter: function (item) { - return (item.group == 2); + filter: (item) => { + return (item.group === 2); } }); // retrieve all items having a property balance with a value above zero var positiveBalance = dataset.get({ - filter: function (item) { + filter: (item) => { return (item.balance > 0); } }); @@ -166,13 +166,10 @@ var edges = new vis.DataSet([ ]); // create a network -var container = document.getElementById('mynetwork'); +var container = document.getElementById('mynetwork'); // provide the data in the vis format -var data2 = { - nodes: nodes, - edges: edges -}; +var data2 = { nodes, edges }; var options = {}; // initialize your network! @@ -187,9 +184,9 @@ var options2 = { configure: { enabled: true, filter: 'nodes,edges', - container: container, + container, showButton: true } -} +}; network.setOptions(options2); \ No newline at end of file diff --git a/vkbeautify/tsconfig.json b/vkbeautify/tsconfig.json index 91709c37ae..2e38ec1be6 100644 --- a/vkbeautify/tsconfig.json +++ b/vkbeautify/tsconfig.json @@ -1,7 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, diff --git a/vkbeautify/vkbeautify-tests.ts b/vkbeautify/vkbeautify-tests.ts index bc91ffad01..a7fd0c4839 100644 --- a/vkbeautify/vkbeautify-tests.ts +++ b/vkbeautify/vkbeautify-tests.ts @@ -2,21 +2,21 @@ import VKBeautify from 'vkbeautify'; /* * Beautifying - * + * * vkbeautify.xml(text [,indent_pattern]); * vkbeautify.json(text [,indent_pattern]); * vkbeautify.css(text [,indent_pattern]); * vkbeautify.sql(text [,indent_pattern]); - * + * * @text - String; text to beatufy; * @indent_pattern - Integer | String; * Integer: number of white spaces; * String: character string to visualize indentation ( can also be a set of white spaces ) */ -let exampleContent = "here-be-xml-json-css-or-sql-content-that-is-about-to-get-formatted"; +const exampleContent = "here-be-xml-json-css-or-sql-content-that-is-about-to-get-formatted"; -//xml +// xml function xmlWithDefault() { VKBeautify.xml(exampleContent); } @@ -29,7 +29,7 @@ function xmlWithStringPattern() { VKBeautify.xml(exampleContent, ' '); } -//json +// json function jsonWithDefault() { VKBeautify.json(exampleContent); } @@ -42,7 +42,7 @@ function jsonWithStringPattern() { VKBeautify.json(exampleContent, ' '); } -//css +// css function cssWithDefault() { VKBeautify.css(exampleContent); } @@ -55,7 +55,7 @@ function cssWithStringPattern() { VKBeautify.css(exampleContent, ' '); } -//sql +// sql function sqlWithDefault() { VKBeautify.sql(exampleContent); } @@ -71,18 +71,18 @@ function sqlWithStringPattern() { /* * Minifying - * + * * vkbeautify.xmlmin(text [,preserve_comments]); * vkbeautify.jsonmin(text); * vkbeautify.cssmin(text [,preserve_comments]); * vkbeautify.sqlmin(text); - * + * * @text - String; text to minify; * @preserve_comments - Bool; [optional]; * Set this flag to true to prevent removing comments from @text ( minxml and mincss functions only. ) */ -//xml +// xml function xmlminWithDefault() { VKBeautify.xmlmin(exampleContent); } @@ -95,12 +95,12 @@ function xmlminAndRemoveComments() { VKBeautify.xmlmin(exampleContent, false); } -//json +// json function jsonmin() { VKBeautify.jsonmin(exampleContent); } -//css +// css function cssminWithDefault() { VKBeautify.cssmin(exampleContent); } @@ -113,7 +113,7 @@ function cssminAndRemoveComments() { VKBeautify.cssmin(exampleContent, false); } -//sql +// sql function sqlmin() { VKBeautify.sqlmin(exampleContent); } \ No newline at end of file diff --git a/voca/index.d.ts b/voca/index.d.ts new file mode 100644 index 0000000000..7a7fa6e6c5 --- /dev/null +++ b/voca/index.d.ts @@ -0,0 +1,304 @@ +// Type definitions for Voca 1.2 +// Project: https://vocajs.com/ +// Definitions by: Pine Mizune +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var v: v.VocaStatic; + +export = v; +export as namespace v; + +declare namespace v { + type CountPredicate = (character: string, index: number, str: string) => boolean; + type ReplacementFunction = (match?: string, ...groups: string[]) => string; + + interface WordWrapOptions { + width?: number; + newLine?: string; + indent?: string; + cut?: boolean; + } + + interface VocaStatic { + // Case + camelCase(subject?: string): string; + capitalize(subject?: string, restToLower?: boolean): string; + decapitalize(subject?: string): string; + kebabCase(subject?: string): string; + lowerCase(subject?: string): string; + snakeCase(subject?: string): string; + titleCase(subject?: string, ignoreWords?: string[]): string; + upperCase(subject?: string): string; + + // Chain + (subject: any): Chain; + chain(subject: T): ExplicitChain; + + // Chop + charAt(subject?: string, position?: number): string; + codePointAt(subject?: string, position?: number): string; + first(subject?: string, length?: number): string; + graphemeAt(subject?: string, position?: number): string; + last(subject?: string, length?: number): string; + prune(subject?: string, length?: number, end?: string): string; + slice(subject?: string, start?: number, end?: number): string; + substr(subject?: string, start?: number, length?: number): string; + substring(subject?: string, start?: number, end?: number): string; + truncate(subject?: string, length?: number, end?: string): string; + + // Count + count(subject?: string): number; + countGraphemes(subject?: string): number; + countSubstrings(subject?: string, substring?: string): number; + countWhere(subject?: string, predicate?: CountPredicate, context?: any): number; + countWords(subject?: string, pattern?: string|RegExp, flags?: string): number; + + // Escape + escapeHtml(subject?: string): string; + escapeRegExp(subject?: string): string; + unescapeHtml(subject?: string): string; + + // Format + sprintf(format?: string, ...replacements: any[]): string; + vprintf(format?: string, ...replacements: any[]): string; + + // Index + indexOf(subject?: string, search?: string, fromIndex?: number): number; + lastIndexOf(subject?: string, search?: string, fromIndex?: number): number; + search(subject?: string, pattern?: string|RegExp, fromIndex?: number): number; + + // Manipulate + insert(subject?: string, toInsert?: string, position?: number): string; + latinise(subject?: string): string; + pad(subject?: string, length?: number, pad?: string): string; + padLeft(subject?: string, length?: number, pad?: string): string; + padRight(subject?: string, length?: number, pad?: string): string; + repeat(subject?: string, times?: number): string; + replace(subject?: string, pattern?: string|RegExp, replacement?: string|ReplacementFunction): string; + replaceAll(subject?: string, pattern?: string|RegExp, replacement?: string|ReplacementFunction): string; + reverse(subject?: string): string; + reverseGrapheme(subject?: string): string; + slugify(subject?: string): string; + splice(subject?: string, start?: number, deleteCount?: number, toAdd?: string): string; + trim(subject?: string, whitespace?: string): string; + trimLeft(subject?: string, whitespace?: string): string; + trimRight(subject?: string, whitespace?: string): string; + wordWrap(subject?: string, options?: WordWrapOptions): string; + + // Query + endsWith(subject?: string, end?: string, position?: number): boolean; + includes(subject?: string, search?: string, position?: number): boolean; + isAlpha(subject?: string): boolean; + isAlphaDigit(subject?: string): boolean; + isBlank(subject?: string): boolean; + isDigit(subject?: string): boolean; + isEmpty(subject?: string): boolean; + isLowerCase(subject?: string): boolean; + isNumeric(subject?: string): boolean; + isString(subject?: any): boolean; + isUpperCase(subject?: string): boolean; + matches(subject?: string, pattern?: string|RegExp, flags?: string): boolean; + startsWith(subject?: string, start?: string, position?: number): boolean; + + // Split + chars(subject?: string): string[]; + codePoints(subject?: string): number[]; + graphemes(subject?: string): string[]; + split(subject?: string, separator?: string|RegExp, limit?: number): string[]; + words(subject?: string, pattern?: string|RegExp, flag?: string): string[]; + + // Strip + stripBom(subject?: string): string; + stripTags(subject?: string, allowbleTags?: string|string[], replacement?: string): string; + + // Util + noConflict(): VocaStatic; + version: string; + } + + interface Chain { + // Case + camelCase(): Chain; + capitalize(restToLoweropt?: boolean): Chain; + decapitalize(): Chain; + kebabCase(): Chain; + lowerCase(): Chain; + snakeCase(): Chain; + titleCase(ignoreWordsopt?: string[]): Chain; + upperCase(): Chain; + + // Chain + value(): string; + chain(): ExplicitChain; + + // Chop + charAt(position?: number): Chain; + codePointAt(position?: number): Chain; + first(length?: number): Chain; + graphemeAt(position?: number): Chain; + last(length?: number): Chain; + prune(length?: number, end?: string): Chain; + slice(start?: number, end?: number): Chain; + substr(start?: number, length?: number): Chain; + substring(start?: number, end?: number): Chain; + truncate(length?: number, end?: string): Chain; + + // Count + count(): number; + countGraphemes(): number; + countSubstrings(substring?: string): number; + countWhere(predicate?: CountPredicate, context?: any): number; + countWords(pattern?: string|RegExp, flags?: string): number; + + // Escape + escapeHtml(): Chain; + escapeRegExp(): Chain; + unescapeHtml(): Chain; + + // Format + sprintf(...replacements: any[]): Chain; + vprintf(...replacements: any[]): Chain; + + // Index + indexOf(search?: string, fromIndex?: number): number; + lastIndexOf(search?: string, fromIndex?: number): number; + search(pattern?: string|RegExp, fromIndex?: number): number; + + // Multipulate + insert(toInsert?: string, position?: number): Chain; + latinise(): Chain; + pad(length?: number, pad?: string): Chain; + padLeft(length?: number, pad?: string): Chain; + padRight(length?: number, pad?: string): Chain; + repeat(times?: number): Chain; + replace(pattern?: string|RegExp, replacement?: string|ReplacementFunction): Chain; + replaceAll(pattern?: string|RegExp, replacement?: string|ReplacementFunction): Chain; + reverse(): Chain; + reverseGrapheme(): Chain; + slugify(): Chain; + splice(start?: number, deleteCount?: number, toAdd?: string): Chain; + trim(whitespace?: string): Chain; + trimLeft(whitespace?: string): Chain; + trimRight(whitespace?: string): Chain; + wordWrap(options?: WordWrapOptions): Chain; + + // Query + endsWith(end?: string, position?: number): boolean; + includes(search?: string, position?: number): boolean; + isAlpha(): boolean; + isAlphaDigit(): boolean; + isBlank(): boolean; + isDigit(): boolean; + isEmpty(): boolean; + isLowerCase(): boolean; + isNumeric(): boolean; + isString(): boolean; + isUpperCase(): boolean; + matches(pattern?: string|RegExp, flags?: string): boolean; + startsWith(start?: string, position?: number): boolean; + + // Split + chars(): string[]; + codePoints(): number[]; + graphemes(): string[]; + split(separator?: string|RegExp, limit?: number): string[]; + words(pattern?: string|RegExp, flag?: string): string[]; + + // Strip + stripBom(): Chain; + stripTags(allowbleTags?: string|string[], replacement?: string): Chain; + } + + interface ExplicitChain { + // Case + camelCase(): ExplicitChain; + capitalize(restToLoweropt?: boolean): ExplicitChain; + decapitalize(): ExplicitChain; + kebabCase(): ExplicitChain; + lowerCase(): ExplicitChain; + snakeCase(): ExplicitChain; + titleCase(ignoreWordsopt?: string[]): ExplicitChain; + upperCase(): ExplicitChain; + + // Chain + value(): T; + thru(changer: (subjects: T) => U): ExplicitChain; + + // Chop + charAt(position?: number): ExplicitChain; + codePointAt(position?: number): ExplicitChain; + first(length?: number): ExplicitChain; + graphemeAt(position?: number): ExplicitChain; + last(length?: number): ExplicitChain; + prune(length?: number, end?: string): ExplicitChain; + slice(start?: number, end?: number): ExplicitChain; + substr(start?: number, length?: number): ExplicitChain; + substring(start?: number, end?: number): ExplicitChain; + truncate(length?: number, end?: string): ExplicitChain; + + // Count + count(): ExplicitChain; + countGraphemes(): ExplicitChain; + countSubstrings(substring?: string): ExplicitChain; + countWhere(predicate?: CountPredicate, context?: any): ExplicitChain; + countWords(pattern?: string|RegExp, flags?: string): ExplicitChain; + + // Escape + escapeHtml(): ExplicitChain; + escapeRegExp(): ExplicitChain; + unescapeHtml(): ExplicitChain; + + // Format + sprintf(...replacements: any[]): ExplicitChain; + vprintf(...replacements: any[]): ExplicitChain; + + // Index + indexOf(search?: string, fromIndex?: number): ExplicitChain; + lastIndexOf(search?: string, fromIndex?: number): ExplicitChain; + search(pattern?: string|RegExp, fromIndex?: number): ExplicitChain; + + // Multipulate + insert(toInsert?: string, position?: number): ExplicitChain; + latinise(): ExplicitChain; + pad(length?: number, pad?: string): ExplicitChain; + padLeft(length?: number, pad?: string): ExplicitChain; + padRight(length?: number, pad?: string): ExplicitChain; + repeat(times?: number): ExplicitChain; + replace(pattern?: string|RegExp, replacement?: string|ReplacementFunction): ExplicitChain; + replaceAll(pattern?: string|RegExp, replacement?: string|ReplacementFunction): ExplicitChain; + reverse(): ExplicitChain; + reverseGrapheme(): ExplicitChain; + slugify(): ExplicitChain; + splice(start?: number, deleteCount?: number, toAdd?: string): ExplicitChain; + trim(whitespace?: string): ExplicitChain; + trimLeft(whitespace?: string): ExplicitChain; + trimRight(whitespace?: string): ExplicitChain; + wordWrap(options?: WordWrapOptions): ExplicitChain; + + // Query + endsWith(end?: string, position?: number): ExplicitChain; + includes(search?: string, position?: number): ExplicitChain; + isAlpha(): ExplicitChain; + isAlphaDigit(): ExplicitChain; + isBlank(): ExplicitChain; + isDigit(): ExplicitChain; + isEmpty(): ExplicitChain; + isLowerCase(): ExplicitChain; + isNumeric(): ExplicitChain; + isString(): ExplicitChain; + isUpperCase(): ExplicitChain; + matches(pattern?: string|RegExp, flags?: string): ExplicitChain; + startsWith(start?: string, position?: number): ExplicitChain; + + // Split + chars(): ExplicitChain; + codePoints(): ExplicitChain; + graphemes(): ExplicitChain; + split(separator?: string|RegExp, limit?: number): ExplicitChain; + words(pattern?: string|RegExp, flag?: string): ExplicitChain; + + // Strip + stripBom(): ExplicitChain; + stripTags(allowbleTags?: string|string[], replacement?: string): ExplicitChain; + } +} diff --git a/voca/tsconfig.json b/voca/tsconfig.json new file mode 100644 index 0000000000..e7cd2ff035 --- /dev/null +++ b/voca/tsconfig.json @@ -0,0 +1,23 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "voca-tests.ts" + ] +} diff --git a/voca/tslint.json b/voca/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/voca/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/voca/voca-tests.ts b/voca/voca-tests.ts new file mode 100644 index 0000000000..5c6f1f4bc9 --- /dev/null +++ b/voca/voca-tests.ts @@ -0,0 +1,331 @@ +import v = require('voca'); + +var str: string; +var num: number; +var bool: boolean; +var strAry: string[]; +var numAry: number[]; + +// Case +str = v.camelCase(); +str = v.camelCase('bird flight'); +str = v('bird flight').camelCase().value(); +str = v.chain('bird flight').camelCase().value(); + +str = v.capitalize(); +str = v.capitalize('apple'); +str = v.capitalize('aPPle', true); +str = v('apple').capitalize().value(); +str = v('apple').capitalize(true).value(); +str = v.chain('apple').capitalize(true).value(); + +str = v.decapitalize('Sun'); +str = v.kebabCase('goodbye blue sky'); +str = v.lowerCase('Green'); +str = v.snakeCase('learning to fly'); +str = v.titleCase('learning to fly'); +str = v.titleCase('another brick in the wall', ['in', 'the']); +str = v.upperCase('school'); + +// Chain +strAry = v('Back to School') + .lowerCase() + .words(); +str = v(" Back to School ") + .trim() + .truncate(7) + .value(); + +strAry = v + .chain('Back to School') + .lowerCase() + .words() + .value(); + +strAry = v('Back to School') + .chain() + .lowerCase() + .words() + .value(); +str = v(" Back to School ") + .chain() + .trim() + .truncate(7) + .value(); + +str = v + .chain('sun is shining') + .words() + .thru((words: string[]) => { + return words[0]; + }) + .value(); + +str = v + .chain('Hello world') + .replace('Hello', 'Hi') + .lowerCase() + .slugify() + .value(); +str = v(' Space travel ') + .trim() + .truncate(8) + .value(); + +// Chop +str = v.charAt('helicopter', 0); +str = v('helicopter').charAt(0).value(); +str = v.chain('helicopter').charAt(0).value(); + +str = v.codePointAt('rain', 1); +str = v.first('helicopter'); +str = v.first('vehicle', 2); +str = v.graphemeAt('\uD835\uDC00\uD835\uDC01', 0); +str = v.last('helicopter'); +str = v.last('vehicle', 2); +str = v.prune('Once upon a time', 7); +str = v.prune('Good day, Little Red Riding Hood', 16, ' (more)'); +str = v.slice('miami', 1); +str = v.slice('florida', 1, 4); +str = v.substr('infinite loop', 9); +str = v.substr('dreams', 2, 2); +str = v.substring('beach', 1); +str = v.substring('ocean', 1, 3); +str = v.truncate('Once upon a time', 7); +str = v.truncate('Good day, Little Red Riding Hood', 14, ' (...)'); + +// Count +num = v.count(); +num = v.count('rain'); +num = v('rain').count(); +num = v.chain('rain').count().value(); + +num = v.countGraphemes('cafe\u0301'); +num = v.countSubstrings('bad boys, bad boys whatcha gonna do?', 'boys'); +num = v.countWhere('hola!', v.isAlpha); +num = v.countWhere('2022', (character: string, index: number, str: string) => { + return character === '2'; +}); +num = v.countWords('gravity can cross dimensions'); + +// Escape +str = v.escapeHtml(); +str = v.escapeHtml('

wonderful world

'); +str = v('

wonderful world

').escapeHtml().value(); +str = v.chain('

wonderful world

').escapeHtml().value(); + +str = v.escapeRegExp(); +str = v.escapeRegExp('(hours)[minutes]{seconds}'); +str = v('(hours)[minutes]{seconds}').escapeRegExp().value(); +str = v.chain('(hours)[minutes]{seconds}').escapeRegExp().value(); + +str = v.unescapeHtml(); +str = v.unescapeHtml('<p>wonderful world</p>'); +str = v('<p>wonderful world</p>').unescapeHtml().value(); +str = v.chain('<p>wonderful world</p>').unescapeHtml().value(); + +// Format +str = v.sprintf(); +str = v.sprintf('%s, %s!', 'Hello', 'World'); +str = v.sprintf('%s costs $%d', 'coffee', 2); +str = v.sprintf('%1$s %2$s %1$s %2$s, watcha gonna %3$s', 'bad', 'boys', 'do'); +str = v.sprintf('% 6s', 'bird'); +str = v.sprintf('%d %i %+d', 15, -2, 25); +str = v.sprintf("%06d", 15); +str = v.sprintf('%.2e %g', 100.5, 0.455); +str = v('%s, %s!').sprintf('Hello', 'World').value(); +str = v.chain('%s, %s!').sprintf('Hello', 'World').value(); + +str = v.vprintf(); +str = v.vprintf('%s', ['Welcome']); +str = v.vprintf('%s has %d apples', ['Alexandra', 3]); +str = v('%s').vprintf(['Welcome']).value(); +str = v.chain('%s').vprintf(['Welcome']).value(); + +// Index +num = v.indexOf(); +num = v.indexOf('morning'); +num = v.indexOf('morning', 'n'); +num = v('morning').indexOf('n'); +num = v.chain('morning').indexOf('n').value(); + +num = v.lastIndexOf(); +num = v.lastIndexOf('morning'); +num = v.lastIndexOf('morning', 'n'); +num = v('morning').lastIndexOf('n'); +num = v.chain('morning').lastIndexOf('n').value(); + +num = v.search('morning', /rn/); +num = v.search('evening', '/\d/'); + +// Manipulate +str = v.insert(); +str = v.insert('ct'); +str = v.insert('ct', 'a'); +str = v.insert('ct', 'a', 1); +str = v('ct').insert('a', 1).value(); +str = v.chain('ct').insert('a', 1).value(); + +str = v.latinise(); +str = v.latinise('cafe\u0301'); + +str = v.pad(); +str = v.pad('dog'); +str = v.pad('dog', 5); +str = v.pad('bird', 6, '-'); + +str = v.padLeft(); +str = v.padLeft('dog'); +str = v.padLeft('dog', 5); +str = v.padLeft('bird', 6, '-'); + +str = v.padRight(); +str = v.padRight('dog'); +str = v.padRight('dog', 5); +str = v.padRight('bird', 6, '-'); + +str = v.repeat(); +str = v.repeat('w'); +str = v.repeat('w', 3); + +str = v.replace(); +str = v.replace('swan', 'wa', 'u'); +str = v.replace('domestic duck', /domestic\s/, ''); +str = v.replace('nice duck', /(nice)(duck)/, (match: string, nice: string, duck: string) => { + return 'the ' + duck + ' is ' + nice; +}); + +str = v.replaceAll(); +str = v.replaceAll('good morning', 'o', '*'); +str = v.replaceAll('evening', /n/, 's'); + +str = v.reverse(); +str = v.reverse('winter'); + +str = v.reverseGrapheme(); +str = v.reverseGrapheme('summer'); + +str = v.slugify(); +str = v.slugify('Italian cappuccino drink'); + +str = v.splice(); +str = v.splice('new year'); +str = v.splice('new year', 0); +str = v.splice('new year', 0, 4); +str = v.splice('new year', 0, 3, 'happy'); + +str = v.trim(); +str = v.trim(' Mother nature '); +str = v.trim('--Earth--', '-'); + +str = v.trimLeft(); +str = v.trimLeft(' Starship Troopers'); +str = v.trimLeft('***Mobile Infantry', '*'); + +str = v.trimRight(); +str = v.trimRight('the fire rises '); +str = v.trimRight('do you feel in charge?!!!', '!'); + +str = v.wordWrap(); +str = v.wordWrap('Hello world'); +str = v.wordWrap('Hello world', { + width: 5 +}); +str = v.wordWrap('Hello world', { + width: 5, + newLine: '
', + indent: '__' +}); +str = v.wordWrap('Wonderful world', { + width: 5, + cut: true +}); + +// Query +bool = v.endsWith(); +bool = v.endsWith('red alert'); +bool = v.endsWith('red alert', 'alert'); +bool = v.endsWith('Murphy', 'ph', 5); +bool = v('Murphy').endsWith('ph', 5); +bool = v.chain('Murphy').endsWith('ph', 5).value(); + +bool = v.includes(); +bool = v.includes('starship'); +bool = v.includes('starship', 'star'); +bool = v.includes('galaxy', 'g', 1); +bool = v('galaxy').includes('g', 1); +bool = v.chain('galaxy').includes('g', 1).value(); + +bool = v.isAlpha(); +bool = v.isAlpha('bart'); + +bool = v.isAlphaDigit(); +bool = v.isAlphaDigit('year2020'); + +bool = v.isBlank(); +bool = v.isBlank(''); + +bool = v.isDigit(); +bool = v.isDigit('35'); + +bool = v.isEmpty(); +bool = v.isEmpty(''); + +bool = v.isLowerCase(); +bool = v.isLowerCase('motorcycle'); + +bool = v.isNumeric(); +bool = v.isNumeric('350'); + +bool = v.isString(); +bool = v.isString('vacation'); +bool = v.isString(560); +bool = v('vacation').isString(); +bool = v(560).isString(); +bool = v.chain('vacation').isString().value(); +bool = v.chain(560).isString().value(); + +bool = v.isUpperCase(); +bool = v.isUpperCase('ACDC'); + +bool = v.matches(); +bool = v.matches('pluto'); +bool = v.matches('pluto', /plu.{2}/); +bool = v.matches('sun', 'S', 'i'); +bool = v.matches('apollo 11', '\\d{3}'); + +bool = v.startsWith(); +bool = v.startsWith('say hello to my little friend'); +bool = v.startsWith('say hello to my little friend', 'say hello'); +bool = v.startsWith('tony', 'on', 1); +bool = v.startsWith('the world is yours', 'world'); + +// Split +strAry = v.chars(); +strAry = v.chars('cloud'); + +numAry = v.codePoints(); +numAry = v.codePoints('rain'); + +strAry = v.graphemes(); +strAry = v.graphemes('\uD835\uDC00\uD835\uDC01'); + +strAry = v.split('rage against the dying of the light', ' '); +strAry = v.split('the dying of the light', /\s/, 3); + +strAry = v.words(); +strAry = v.words('gravity can cross dimensions'); +strAry = v.words('Earth gravity', /[^\s]+/g); + +// Strip +str = v.stripBom(); +str = v.stripBom('\uFEFFsummertime sadness'); + +str = v.stripTags(); +str = v.stripTags('Summer is nice'); +str = v.stripTags('Winter is cold', ['b', 'i']); +str = v.stripTags('Sun
set', '', '-'); + +// Util +var voca: v.VocaStatic = v.noConflict(); +var version: string = v.version; diff --git a/wampy/index.d.ts b/wampy/index.d.ts index 840829f653..f74695503a 100644 --- a/wampy/index.d.ts +++ b/wampy/index.d.ts @@ -3,9 +3,8 @@ // Definitions by: Konstantin Burkalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -interface WampyOptions { +interface WampyOptions +{ autoReconnect?: boolean; reconnectInterval?: number; maxRetries?: number; @@ -23,82 +22,95 @@ interface WampyOptions { msgpackCoder?: any; } -interface WampyOpStatus { +interface WampyOpStatus +{ code: number; description: string; reqId?: number; } -interface SuccessErrorCallbacksHash { +interface SuccessErrorCallbacksHash +{ onSuccess?: (data: any) => void; - onError?: (err: string) => void; + onError?: (err: string, details: any) => void; } -interface SubscribeCallbacksHash extends SuccessErrorCallbacksHash { - onEvent: (data: any) => void; +interface SubscribeCallbacksHash extends SuccessErrorCallbacksHash +{ + onEvent: (args: any[], kwargs: any) => void; } -interface RegisterCallbacksHash extends SuccessErrorCallbacksHash { +interface RegisterCallbacksHash extends SuccessErrorCallbacksHash +{ rpc: (data: any, options: any) => any[]; } -interface CallSuccessErrorCallbacksHash { - onSuccess: (data: any) => any; - onError?: (err: string) => void; +interface CallSuccessErrorCallbacksHash +{ + onSuccess: (args: any[], kwargs: any) => any; + onError?: (err: string, details: any, args: any[], kwargs: any) => void; } -interface AdvancedOptions { +interface AdvancedOptions +{ exclude?: number | number[]; eligible?: number | number[]; exclude_me?: boolean; disclose_me?: boolean; } -interface PublishAdvancedOptions extends AdvancedOptions { +interface PublishAdvancedOptions extends AdvancedOptions +{ exclude_authid?: string | string[]; exclude_authrole?: string | string[]; eligible_authid?: string | string[]; eligible_authrole?: string | string[]; } -interface CallAdvancedOptions { +interface CallAdvancedOptions +{ disclose_me?: boolean; receive_progress?: boolean; timeout?: number; } -interface CancelAdvancedOptions { +interface CancelAdvancedOptions +{ mode?: "skip" | "kill" | "killnowait"; } -interface Wampy { +interface Wampy +{ + new (url?: string, options?: WampyOptions): Wampy; options(opts?: WampyOptions): WampyOptions | Wampy; getOpStatus(): WampyOpStatus; getSessionId(): number; connect(url?: string): Wampy; disconnect(): Wampy; abort(): Wampy; - subscribe(topicURI: string, callbacks: (((data: any) => void) | SubscribeCallbacksHash)): Wampy; - unsubscribe(topicURI: string, callbacks?: (((data: any) => void) | SubscribeCallbacksHash)): Wampy; + subscribe(topicURI: string, callbacks: (((args: any[], kwargs: any) => void) | SubscribeCallbacksHash)): Wampy; + unsubscribe(topicURI: string, callbacks?: (((args: any[], kwargs: any) => void) | SubscribeCallbacksHash)): Wampy; publish(topicURI: string, - payload?: any, - callbacks?: SuccessErrorCallbacksHash, - advancedOptions?: PublishAdvancedOptions): Wampy; + payload?: any, + callbacks?: SuccessErrorCallbacksHash, + advancedOptions?: PublishAdvancedOptions): Wampy; call(topicURI: string, - payload?: any, - callbacks?: (((data: any) => void) | CallSuccessErrorCallbacksHash), - advancedOptions?: CallAdvancedOptions): Wampy; + payload?: any, + callbacks?: (((args: any[], kwargs: any) => void) | CallSuccessErrorCallbacksHash), + advancedOptions?: CallAdvancedOptions): Wampy; cancel(reqId: number, - callbacks?: ((() => void) | SuccessErrorCallbacksHash), - advancedOptions?: CancelAdvancedOptions): Wampy; + callbacks?: ((() => void) | SuccessErrorCallbacksHash), + advancedOptions?: CancelAdvancedOptions): Wampy; register(topicURI: string, callbacks: (((data: any, options: any) => any[]) | RegisterCallbacksHash)): Wampy; unregister(topicURI: string, callbacks?: ((() => void) | SuccessErrorCallbacksHash)): Wampy; } -interface WampyInstance { - new (url?: string, options?: WampyOptions): Wampy; +declare var wampy: Wampy; + +declare module 'wampy' +{ + export = wampy; } -declare var wampy: WampyInstance; -export default wampy; + diff --git a/wampy/wampy-tests.ts b/wampy/wampy-tests.ts index feed5677bc..e3de0cd019 100644 --- a/wampy/wampy-tests.ts +++ b/wampy/wampy-tests.ts @@ -1,47 +1,50 @@ /// -import Wampy from 'wampy'; +import * as Wampy from 'wampy'; -var ws = new Wampy('http://wamp.router.url', {realm: 'WAMPRealm'}); +let ws = new Wampy('http://wamp.router.url', {realm: 'WAMPRealm'}); ws.options(); ws.options({ reconnectInterval: 1000, maxRetries: 999, - onConnect: function () { console.log('Yahoo! We are online!'); }, - onClose: function () { console.log('See you next time!'); }, - onError: function () { console.log('Breakdown happened'); }, - onReconnect: function () { console.log('Reconnecting...'); }, - onReconnectSuccess: function () { console.log('Successfully reconnected!'); } + onConnect: () => console.log('Yahoo! We are online!'), + onClose: () => console.log('See you next time!'), + onError: () => console.log('Breakdown happened'), + onReconnect: () => console.log('Reconnecting...'), + onReconnectSuccess: () => console.log('Successfully reconnected!') }); ws.connect(); ws.connect('/my-socket-path'); ws.connect('wss://socket.server.com:5000/ws'); -var id: number = ws.getSessionId(); + +let id: number = ws.getSessionId(); + ws.disconnect(); ws.abort(); -ws.subscribe('system.monitor.update', function (data) { +ws.subscribe('system.monitor.update', (args: any[], kwargs: any) => { console.log('Received system.monitor.update event!'); }) - .subscribe('client.message', function (data) { + .subscribe('client.message', function (args: any[], kwargs: any) { console.log('Received client.message event!'); }); -var f1 = function () { console.log('Subscribe processing!'); }; +let f1 = () => console.log('Subscribe processing!'); + ws.unsubscribe('subscribed.topic', f1); ws.unsubscribe('chat.message.received'); ws.call('get.server.time', null, { - onSuccess: function (stime) { + onSuccess: (args: any[], kwargs: any) => { console.log('RPC successfully called'); - console.log('Server time is ' + stime); + console.log('Server time is ' + kwargs); }, - onError: function (err) { + onError: (err: string, details: any, args: any[], kwargs: any) => { console.log('RPC call failed with error ' + err); } }); @@ -54,67 +57,48 @@ ws.publish('chat.message.received', 'user message'); ws.publish('chat.message.received', ['user message1', 'user message2']); ws.publish('user.modified', { field1: 'field1', field2: true, field3: 123 }); ws.publish('user.modified', { field1: 'field1', field2: true, field3: 123 }, { - onSuccess: function () { console.log('User successfully modified'); } + onSuccess: () => console.log('User successfully modified') }); ws.publish('user.modified', { field1: 'field1', field2: true, field3: 123 }, { - onSuccess: function () { console.log('User successfully modified'); }, - onError: function (err) { console.log('User modification failed', err); } + onSuccess: () => console.log('User successfully modified'), + onError: (err: string, details: any) => console.log('User modification failed', err) }); ws.publish('chat.message.received', ['Private message'], null, { eligible: 123456789 }); -ws.call('server.time', null, function (data) { console.log('Server time is ' + data[0]); }); +ws.call('server.time', null, (args: any[], kwargs: any) => console.log('Server time is ' + args[0])); ws.call('start.migration', null, { - onSuccess: function (data) { - console.log('RPC successfully called'); - }, - onError: function (err) { - console.log('RPC call failed!',err); - } + onSuccess: (args: any[], kwargs: any) => console.log('RPC successfully called'), + onError: (err: string, details: any, args: any[], kwargs: any) => console.log('RPC call failed!',err) }); ws.call('restore.backup', { backupFile: 'backup.zip' }, { - onSuccess: function (data) { - console.log('Backup successfully restored'); - }, - onError: function (err) { - console.log('Restore failed!',err); - } + onSuccess: (args: any[], kwargs: any) => console.log('Backup successfully restored'), + onError: (err: string, details: any, args: any[], kwargs: any) => console.log('Restore failed!',err) }); ws.call('start.migration', null, { - onSuccess: function (data) { - console.log('RPC successfully called'); - }, - onError: function (err) { - console.log('RPC call failed!',err); - } + onSuccess: (args: any[], kwargs: any) => console.log('RPC successfully called'), + onError: (err: string, details: any, args: any[], kwargs: any) => console.log('RPC call failed!',err) }); -var status = ws.getOpStatus(); + +let status = ws.getOpStatus(); ws.cancel(status.reqId); -var sqrt_f = function (x: number, y: any) { return [{}, x*x]; }; +let sqrt_f = (x: number, y: any) => [{}, x*x]; ws.register('sqrt.value', sqrt_f); ws.register('sqrt.value', { rpc: sqrt_f, - onSuccess: function (data) { - console.log('RPC successfully registered'); - }, - onError: function (err) { - console.log('RPC registration failed!',err); - } + onSuccess: (data: any) => console.log('RPC successfully registered'), + onError: (err: string, details: any) => console.log('RPC registration failed!',err) }); ws.unregister('sqrt.value'); ws.unregister('sqrt.value', { - onSuccess: function (data) { - console.log('RPC successfully unregistered'); - }, - onError: function (err) { - console.log('RPC unregistration failed!',err); - } + onSuccess: (data: any) => console.log('RPC successfully unregistered'), + onError: (err: string, details: any) => console.log('RPC unregistration failed!', err) }); diff --git a/watchpack/watchpack-tests.ts b/watchpack/watchpack-tests.ts index 77b78d8c23..7ae28bc514 100644 --- a/watchpack/watchpack-tests.ts +++ b/watchpack/watchpack-tests.ts @@ -3,5 +3,5 @@ const watch = new Watchpack({}); watch.watch(['test.js'], ['lib/'], 1000); -let time: number -time = watch.getTimes()['test.js'] +let time: number; +time = watch.getTimes()['test.js']; diff --git a/web-bluetooth/index.d.ts b/web-bluetooth/index.d.ts index 219dd65f5e..f30269239c 100644 --- a/web-bluetooth/index.d.ts +++ b/web-bluetooth/index.d.ts @@ -17,7 +17,7 @@ interface BluetoothRequestDeviceFilter { interface RequestDeviceOptions { filters: BluetoothRequestDeviceFilter[]; - optionalServices?: number[]; + optionalServices?: BluetoothServiceUUID[]; acceptAllDevices?: boolean; } diff --git a/webappsec-credential-management/webappsec-credential-management-tests.ts b/webappsec-credential-management/webappsec-credential-management-tests.ts index 2a13e943c3..69cae46daf 100644 --- a/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -70,7 +70,7 @@ function passwordPostSignInConfirmation() { if (navigator.credentials) { e.preventDefault(); - let formElem = (e.target as HTMLFormElement); + const formElem = (e.target as HTMLFormElement); var c = new PasswordCredential(formElem); fetch(formElem.action, {method: 'POST', credentials: c}).then(r => { if (r.status === 200) { diff --git a/webdriverio/index.d.ts b/webdriverio/index.d.ts index 8f22d2e5aa..dff87053d7 100644 --- a/webdriverio/index.d.ts +++ b/webdriverio/index.d.ts @@ -395,36 +395,22 @@ declare namespace WebdriverIO { ): Client

; getHTML

(includeSelectorTag: boolean): Client

; - getLocation(selector?: string): Size; - getLocation(selector: string, axis: string): number; - getLocation(axis: string): number; + getLocation(axis: Axis): number; + getLocation

(axis: Axis): Client

; + getLocation(selector?: string): Location; getLocation

(selector?: string): Client

; - getLocation

( - selector: string, - axis: string - ): Client

; - getLocation

(axis: string): Client

; + getLocation(selector: string, axis: Axis): number; + getLocation

(selector: string, axis: Axis): Client

; - getLocationInView(selector: string): Size; - getLocationInView(selector: string): Size[]; - getLocationInView(): Size; - getLocationInView(): Size[]; - getLocationInView( - selector: string, - axis: string - ): number; - getLocationInView( - selector: string, - axis: string - ): number[]; - getLocationInView(axis: string): number; - getLocationInView(axis: string): number[]; + getLocationInView(axis: Axis): number; + getLocationInView(axis: Axis): number[]; + getLocationInView

(axis: Axis): Client

; + getLocationInView(selector?: string): Location; + getLocationInView(selector?: string): Location[]; getLocationInView

(selector?: string): Client

; - getLocationInView

( - selector: string, - axis: string - ): Client

; - getLocationInView

(axis: string): Client

; + getLocationInView(selector: string, axis: Axis): number; + getLocationInView(selector: string, axis: Axis): number[]; + getLocationInView

(selector: string, axis: Axis): Client

; getSource(): Client; getSource

(): Client

; @@ -471,7 +457,7 @@ declare namespace WebdriverIO { value: any; } - export interface Location { + export interface GeoLocation { latitude: number; longitude: number; altitude: number; @@ -1027,6 +1013,8 @@ declare namespace WebdriverIO { switchTab

(windowHandle?: string): Client

; } + export type Axis = "x" | "y"; + export interface Options { protocol: string; waitforTimeout: number; diff --git a/webmidi/index.d.ts b/webmidi/index.d.ts index 351a20c58a..a103ea77dd 100644 --- a/webmidi/index.d.ts +++ b/webmidi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Web MIDI API +// Type definitions for Web MIDI API 2.0 // Project: http://www.w3.org/TR/webmidi/ // Definitions by: six a // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ interface Navigator { * When invoked, returns a Promise object representing a request for access to MIDI * devices on the user's system. */ - requestMIDIAccess(options?: WebMidi.MIDIOptions) : Promise; + requestMIDIAccess(options?: WebMidi.MIDIOptions): Promise; } declare namespace WebMidi { @@ -17,7 +17,7 @@ declare namespace WebMidi { * This member informs the system whether the ability to send and receive system * exclusive messages is requested or allowed on a given MIDIAccess object. */ - sysex : boolean; + sysex: boolean; } /** @@ -36,24 +36,24 @@ declare namespace WebMidi { /** * The MIDI input ports available to the system. */ - inputs : MIDIInputMap; + inputs: MIDIInputMap; /** * The MIDI output ports available to the system. */ - outputs : MIDIOutputMap; + outputs: MIDIOutputMap; /** * The handler called when a new port is connected or an existing port changes the * state attribute. */ - onstatechange : (e : MIDIConnectionEvent) => void; + onstatechange: (e: MIDIConnectionEvent) => void; /** * This attribute informs the user whether system exclusive support is enabled on * this MIDIAccess. */ - sysexEnabled : boolean; + sysexEnabled: boolean; } export type MIDIPortType = "input" | "output"; @@ -67,44 +67,44 @@ declare namespace WebMidi { * A unique ID of the port. This can be used by developers to remember ports the * user has chosen for their application. */ - id : string; + id: string; /** * The manufacturer of the port. */ - manufacturer? : string; + manufacturer?: string; /** * The system name of the port. */ - name? : string; + name?: string; /** * A descriptor property to distinguish whether the port is an input or an output * port. */ - type : MIDIPortType; + type: MIDIPortType; /** * The version of the port. */ - version? : string; + version?: string; /** * The state of the device. */ - state : MIDIPortDeviceState; + state: MIDIPortDeviceState; /** * The state of the connection to the device. */ - connection : MIDIPortConnectionState; + connection: MIDIPortConnectionState; /** * The handler called when an existing port changes its state or connection * attributes. */ - onstatechange : (e : MIDIConnectionEvent) => void; + onstatechange: (e: MIDIConnectionEvent) => void; /** * Makes the MIDI device corresponding to the MIDIPort explicitly available. Note @@ -115,7 +115,7 @@ declare namespace WebMidi { * When invoked, this method returns a Promise object representing a request for * access to the given MIDI port on the user's system. */ - open() : Promise; + open(): Promise; /** * Makes the MIDI device corresponding to the MIDIPort @@ -130,11 +130,11 @@ declare namespace WebMidi { * other applications), the vended Promise is resolved. If the port is * disconnected, the Promise is rejected. */ - close() : Promise; + close(): Promise; } export interface MIDIInput extends MIDIPort { - onmidimessage : (e : MIDIMessageEvent) => void; + onmidimessage: (e: MIDIMessageEvent) => void; } export interface MIDIOutput extends MIDIPort { @@ -145,7 +145,7 @@ declare namespace WebMidi { * to zero (or another time in the past), the data is to be sent as soon as * possible. */ - send(data : number[], timestamp? : number) : void; + send(data: number[], timestamp?: number): void; /** * Clears any pending send data that has not yet been sent from the MIDIOutput 's @@ -153,44 +153,44 @@ declare namespace WebMidi { * state, so if the output port is in the middle of a sysex message, a sysex * termination byte (0xf7) should be sent. */ - clear() : void; + clear(): void; } export interface MIDIMessageEvent extends Event { /** * A timestamp specifying when the event occurred. */ - receivedTime : number; + receivedTime: number; /** * A Uint8Array containing the MIDI data bytes of a single MIDI message. */ - data : Uint8Array; + data: Uint8Array; } export interface MIDIMessageEventInit extends EventInit { /** * A timestamp specifying when the event occurred. */ - receivedTime : number; + receivedTime: number; /** * A Uint8Array containing the MIDI data bytes of a single MIDI message. */ - data : Uint8Array; + data: Uint8Array; } export interface MIDIConnectionEvent extends Event { /** * The port that has been connected or disconnected. */ - port : MIDIPort; + port: MIDIPort; } export interface MIDIConnectionEventInit extends EventInit { /** * The port that has been connected or disconnected. */ - port : MIDIPort; + port: MIDIPort; } } diff --git a/webmidi/tsconfig.json b/webmidi/tsconfig.json index e7957af823..2d4444827a 100644 --- a/webmidi/tsconfig.json +++ b/webmidi/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/webmidi/tslint.json b/webmidi/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/webmidi/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/webmidi/webmidi-tests.ts b/webmidi/webmidi-tests.ts index f6b5546abd..f361202895 100644 --- a/webmidi/webmidi-tests.ts +++ b/webmidi/webmidi-tests.ts @@ -3,7 +3,7 @@ var onFulfilled = (item: WebMidi.MIDIAccess) => { this._midiPort = item; - item.onstatechange = (event : WebMidi.MIDIConnectionEvent) => { + item.onstatechange = (event: WebMidi.MIDIConnectionEvent) => { console.log("onstatechange"); console.log(event); }; @@ -11,27 +11,27 @@ var onFulfilled = (item: WebMidi.MIDIAccess) => { console.log("sysexenabled"); console.log(item.sysexEnabled); - var inputs = this._midiPort.inputs.values(); + var inputs = this._midiPort.inputs.values(); - for(const o of inputs){ + for (const o of inputs) { this._inputs.push(o); console.log(o); } var outputs = item.outputs.values(); - for(const op of outputs){ + for (const op of outputs) { this._outputs.push(op); op.send([ 0x90, 0x45, 0x7f ] ); } - for(var cnt = 0; cnt < this._inputs.length; cnt++){ - this._inputs[cnt].onmidimessage = (event: WebMidi.MIDIMessageEvent)=>{ + for (const input of this._inputs) { + input.onmidimessage = (event: WebMidi.MIDIMessageEvent) => { this.onMidiMessage(event.data); }; } }; -var onRejected = (e: Error)=>{ console.error(e) }; +var onRejected = (e: Error) => { console.error(e); }; if (navigator.requestMIDIAccess !== undefined) { navigator.requestMIDIAccess().then(onFulfilled, onRejected); diff --git a/webpack-dev-middleware/webpack-dev-middleware-tests.ts b/webpack-dev-middleware/webpack-dev-middleware-tests.ts index 63d32332b5..3764a6b9aa 100644 --- a/webpack-dev-middleware/webpack-dev-middleware-tests.ts +++ b/webpack-dev-middleware/webpack-dev-middleware-tests.ts @@ -31,6 +31,6 @@ app.use(webpackDevMiddlewareInstance); webpackDevMiddlewareInstance.close(); webpackDevMiddlewareInstance.invalidate(); -webpackDevMiddlewareInstance.waitUntilValid(function(){ +webpackDevMiddlewareInstance.waitUntilValid(() => { console.log('Package is in a valid state'); }); diff --git a/webpack-notifier/index.d.ts b/webpack-notifier/index.d.ts index 8caff77388..1b8e92651f 100644 --- a/webpack-notifier/index.d.ts +++ b/webpack-notifier/index.d.ts @@ -3,21 +3,23 @@ // Definitions by: Benjamin Lim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Plugin, Webpack } from 'webpack'; +import { Plugin } from 'webpack'; export = WebpackNotifierPlugin; -declare class WebpackNotifierPlugin implements Plugin { - constructor(options?: WebpackNotifierPlugin.Config); - apply(thisArg: Webpack, ...args: any[]): void; +declare class WebpackNotifierPlugin extends Plugin { + constructor(options?: WebpackNotifierPlugin.Options); } declare namespace WebpackNotifierPlugin { - export interface Config { - title?: string; - contentImage?: string; - excludeWarnings?: boolean; - alwaysNotify?: boolean; - skipFirstNotification?: boolean; - } + interface Options { + alwaysNotify?: boolean; + contentImage?: string; + excludeWarnings?: boolean; + skipFirstNotification?: boolean; + title?: string; + } + + /** @deprecated use Options */ + type Config = Options; } diff --git a/webpack-notifier/webpack-notifier-tests.ts b/webpack-notifier/webpack-notifier-tests.ts index 9ec1dede26..f71fe5800f 100644 --- a/webpack-notifier/webpack-notifier-tests.ts +++ b/webpack-notifier/webpack-notifier-tests.ts @@ -1,14 +1,14 @@ -import WebpackNotifierPlugin = require('webpack-notifier'); import { Plugin } from 'webpack'; +import * as WebpackNotifierPlugin from 'webpack-notifier'; -const configs: Array = [ - { - title: 'Webpack', - contentImage: 'logo.png', - excludeWarnings: true, - alwaysNotify: true, - skipFirstNotification: true, - }, +const optionsArray: WebpackNotifierPlugin.Options[] = [ + { + title: 'Webpack', + contentImage: 'logo.png', + excludeWarnings: true, + alwaysNotify: true, + skipFirstNotification: true, + }, ]; -const plugins: Array = configs.map(config => new WebpackNotifierPlugin(config)); +const plugins: Plugin[] = optionsArray.map(options => new WebpackNotifierPlugin(options)); diff --git a/webpack-stream/index.d.ts b/webpack-stream/index.d.ts index 9a36906a03..74b8d01544 100644 --- a/webpack-stream/index.d.ts +++ b/webpack-stream/index.d.ts @@ -1,48 +1,26 @@ -// Type definitions for webpack-stream v3.2.0 +// Type definitions for webpack-stream 3.2 // Project: https://github.com/shama/webpack-stream -// Definitions by: Ian Clanton-Thuon +// Definitions by: Ian Clanton-Thuon , Benjamin Lim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /// -declare module "webpack-stream" { - import webpack = require("webpack"); +import * as webpack from 'webpack'; - interface WebpackStreamStatic { - /** - * Run webpack with the default configuration. - */ - (): NodeJS.ReadWriteStream; +export = webpackStream; - /** - * Run webpack with the specified configuration. - * - * @param {config} Webpack configuration - */ - (config: webpack.Configuration): NodeJS.ReadWriteStream; +/** + * Run webpack with the specified configuration and webpack instance + * + * @param {webpack.Configuration} config - Webpack configuration + * @param {webpack} wp - A webpack object + * @param {webpack.Compiler.Handler} callback - A callback with the webpack stats and error objects. + */ +declare function webpackStream( + config?: webpack.Configuration, + wp?: typeof webpack, + callback?: webpack.Compiler.Handler, +): NodeJS.ReadWriteStream; - /** - * Run webpack with the specified configuration and webpack instance - * - * @param {config} Webpack configuration - * @param {webpack} A webpack object - */ - (config: webpack.Configuration, webpack: webpack.Webpack): NodeJS.ReadWriteStream; - - /** - * Run webpack with the specified configuration and webpack instance - * - * @param {config} Webpack configuration - * @param {webpack} A webpack object - * @param {callback} A callback with the webpack stats and error objects. - */ - (config: webpack.Configuration, - webpack: webpack.Webpack, - callback?: (err: Error, stats: webpack.compiler.Stats) => void): NodeJS.ReadWriteStream; - } - - var webpackStream: WebpackStreamStatic; - - export = webpackStream; +declare namespace webpackStream { } diff --git a/webpack-stream/tsconfig.json b/webpack-stream/tsconfig.json index e1986eac35..65fc295fdf 100644 --- a/webpack-stream/tsconfig.json +++ b/webpack-stream/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "webpack-stream-tests.ts" ] -} \ No newline at end of file +} diff --git a/webpack-stream/tslint.json b/webpack-stream/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/webpack-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/webpack-stream/webpack-stream-tests.ts b/webpack-stream/webpack-stream-tests.ts index 9f13f53b02..b6e4cce807 100644 --- a/webpack-stream/webpack-stream-tests.ts +++ b/webpack-stream/webpack-stream-tests.ts @@ -1,5 +1,5 @@ -import webpackStream = require("webpack-stream"); -import webpack = require("webpack"); +import * as webpack from 'webpack'; +import * as webpackStream from 'webpack-stream'; let output: NodeJS.ReadWriteStream; diff --git a/webpack/index.d.ts b/webpack/index.d.ts index 1ef2fa168f..4f6ae6e211 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -5,15 +5,35 @@ /// +import * as Tapable from 'tapable'; import * as UglifyJS from 'uglify-js'; -import * as tapable from 'tapable'; + +export = webpack; + +declare function webpack( + options: webpack.Configuration, + handler: webpack.Compiler.Handler +): webpack.Compiler.Watching | webpack.Compiler; +declare function webpack(options?: webpack.Configuration): webpack.Compiler; + +declare function webpack( + options: webpack.Configuration[], + handler: webpack.MultiCompiler.Handler +): webpack.MultiWatching | webpack.MultiCompiler; +declare function webpack(options: webpack.Configuration[]): webpack.MultiCompiler; declare namespace webpack { interface Configuration { 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. */ - 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; + // 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; /** Options affecting the output. */ output?: Output; /** Options affecting the normal modules (NormalModuleFactory) */ @@ -46,7 +66,7 @@ declare namespace webpack { cache?: boolean | any; /** Enter watch mode, which rebuilds on file change. */ watch?: boolean; - watchOptions?: WatchOptions; + watchOptions?: Options.WatchOptions; /** Switch loaders to debug mode. */ debug?: boolean; /** Can be used to configure the behaviour of webpack-dev-server when the webpack config is passed to webpack-dev-server CLI. */ @@ -64,9 +84,9 @@ declare namespace webpack { /** Add additional plugins to the compiler. */ plugins?: Plugin[]; /** Stats options for logging */ - stats?: compiler.StatsToStringOptions; + stats?: Options.Stats; /** Performance options */ - performance?: PerformanceOptions; + performance?: Options.Performance; } interface Entry { @@ -324,15 +344,6 @@ declare namespace webpack { type ExternalsFunctionElement = (context: any, request: any, callback: (error: any, result: any) => void) => any; - interface WatchOptions { - /** Delay the rebuilt after the first change. Value is a time in ms. */ - aggregateTimeout?: number; - /** For some systems, watching many file systems can result in a lot of CPU or memory usage. It is possible to exclude a huge folder like node_modules. It is also possible to use anymatch patterns. */ - ignored?: RegExp | string; - /** true: use polling, number: use polling with specified interval */ - poll?: boolean | number; - } - interface Node { console?: boolean; global?: boolean; @@ -417,7 +428,8 @@ declare namespace webpack { /** * An object with parser options. All applied parser options are merged. * - * For each different parser options object a new parser is created and plugins can apply plugins depending on the parser options. Many of the default plugins apply their parser plugins only if a property in the parser options is not set or true. + * For each different parser options object a new parser is created and plugins can apply plugins depending on the parser options. + * Many of the default plugins apply their parser plugins only if a property in the parser options is not set or true. */ parser?: { [optName: string]: any }; /** An array of Rules that is also used when the Rule matches. */ @@ -468,272 +480,338 @@ declare namespace webpack { } type Rule = LoaderRule | UseRule | RulesRule | OneOfRule; - interface Plugin extends tapable.Plugin { - apply(thisArg: Webpack, ...args: any[]): void; + namespace Options { + interface Performance { + /** This property allows webpack to control what files are used to calculate performance hints. */ + assetFilter?(assetFilename: string): boolean; + /** + * Turns hints on/off. In addition, tells webpack to throw either an error or a warning when hints are + * found. This property is set to "warning" by default. + */ + hints?: 'warning' | 'error' | boolean; + /** + * An asset is any emitted file from webpack. This option controls when webpack emits a performance hint + * based on individual asset size. The default value is 250000 (bytes). + */ + maxAssetSize?: number; + /** + * An entrypoint represents all assets that would be utilized during initial load time for a specific entry. + * This option controls when webpack should emit performance hints based on the maximum entrypoint size. + * The default value is 250000 (bytes). + */ + maxEntrypointSize?: number; + } + type Stats = webpack.Stats.ToStringOptions; + type WatchOptions = ICompiler.WatchOptions; } - interface Webpack { - (config: Configuration, callback?: compiler.CompilerCallback): compiler.Compiler; - /** - * optimize namespace - */ - optimize: Optimize; - /** - * dependencies namespace - */ - dependencies: Dependencies; - /** - * Replace resources that matches resourceRegExp with newResource. - * If newResource is relative, it is resolve relative to the previous resource. - * If newResource is a function, it is expected to overwrite the ‘request’ attribute of the supplied object. - */ - NormalModuleReplacementPlugin: NormalModuleReplacementPluginStatic; - /** - * Replaces the default resource, recursive flag or regExp generated by parsing with newContentResource, - * newContentRecursive resp. newContextRegExp if the resource (directory) matches resourceRegExp. - * If newContentResource is relative, it is resolve relative to the previous resource. - * If newContentResource is a function, it is expected to overwrite the ‘request’ attribute of the supplied object. - */ - ContextReplacementPlugin: ContextReplacementPluginStatic; - /** - * Don’t generate modules for requests matching the provided RegExp. - */ - IgnorePlugin: IgnorePluginStatic; - /** - * A request for a normal module, which is resolved and built even before a require to it occurs. - * This can boost performance. Try to profile the build first to determine clever prefetching points. - */ - PrefetchPlugin: PrefetchPluginStatic; - /** - * Apply a plugin (or array of plugins) to one or more resolvers (as specified in types). - */ - ResolverPlugin: ResolverPluginStatic; - /** - * Adds a banner to the top of each generated chunk. - */ - BannerPlugin: BannerPluginStatic; - /** - * Define free variables. Useful for having development builds with debug logging or adding global constants. - */ - DefinePlugin: DefinePluginStatic; - /** - * Automatically loaded modules. - * Module (value) is loaded when the identifier (key) is used as free variable in a module. - * The identifier is filled with the exports of the loaded module. - */ - ProvidePlugin: ProvidePluginStatic; - /** - * Adds SourceMaps for assets. - */ - SourceMapDevToolPlugin: SourceMapDevToolPluginStatic; - /** - * Adds SourceMaps for assets, but wrapped inside eval statements. - * Much faster incremental build speed, but harder to debug. - */ - EvalSourceMapDevToolPlugin: EvalSourceMapDevToolPluginStatic; - /** - * Enables Hot Module Replacement. (This requires records data if not in dev-server mode, recordsPath) - * Generates Hot Update Chunks of each chunk in the records. - * It also enables the API and makes __webpack_hash__ available in the bundle. - */ - HotModuleReplacementPlugin: HotModuleReplacementPluginStatic; - /** - * Adds useful free vars to the bundle. - */ - ExtendedAPIPlugin: ExtendedAPIPluginStatic; - /** - * When there are errors while compiling this plugin skips the emitting phase (and recording phase), - * so there are no assets emitted that include errors. The emitted flag in the stats is false for all assets. - */ - NoEmitOnErrorsPlugin: NoEmitOnErrorsPluginStatic; - /** - * Alias for NoEmitOnErrorsPlugin - * @deprecated - */ - NoErrorsPlugin: NoEmitOnErrorsPluginStatic; - /** - * Does not watch specified files matching provided paths or RegExps. - */ - WatchIgnorePlugin: WatchIgnorePluginStatic; - /** - * Uses the module name as the module id inside the bundle, instead of a number. - * Helps with debugging, but increases bundle size. - */ - NamedModulesPlugin: NamedModulesPluginStatic; - /** - * Some loaders need context information and read them from the configuration. - * This need to be passed via loader options in the long-term. See loader documentation for relevant options. - * To keep compatibility with old loaders, these options can be passed via this plugin. - */ - LoaderOptionsPlugin: LoaderOptionsPluginStatic; + // tslint:disable-next-line:interface-name + interface ICompiler { + run(handler: ICompiler.Handler): void; + watch(watchOptions: ICompiler.WatchOptions, handler: ICompiler.Handler): Watching; } - interface Optimize { - /** - * Search for equal or similar files and deduplicate them in the output. - * This comes with some overhead for the entry chunk, but can reduce file size effectively. - * This is experimental and may crash, because of some missing implementations. (Report an issue) - */ - DedupePlugin: optimize.DedupePluginStatic; - /** - * Limit the chunk count to a defined value. Chunks are merged until it fits. - */ - LimitChunkCountPlugin: optimize.LimitChunkCountPluginStatic; - /** - * Merge small chunks that are lower than this min size (in chars). Size is approximated. - */ - MinChunkSizePlugin: optimize.MinChunkSizePluginStatic; - /** - * Assign the module and chunk ids by occurrence count. Ids that are used often get lower (shorter) ids. - * This make ids predictable, reduces to total file size and is recommended. - */ - // TODO: This is a typo, and will be removed in Webpack 2. - OccurenceOrderPlugin: optimize.OccurenceOrderPluginStatic; - OccurrenceOrderPlugin: optimize.OccurenceOrderPluginStatic; - /** - * Minimize all JavaScript output of chunks. Loaders are switched into minimizing mode. - * You can pass an object containing UglifyJs options. - */ - UglifyJsPlugin: optimize.UglifyJsPluginStatic; - CommonsChunkPlugin: optimize.CommonsChunkPluginStatic; - /** - * A plugin for a more aggressive chunk merging strategy. - * Even similar chunks are merged if the total size is reduced enough. - * As an option modules that are not common in these chunks can be moved up the chunk tree to the parents. - */ - AggressiveMergingPlugin: optimize.AggressiveMergingPluginStatic; + namespace ICompiler { + type Handler = (err: Error, stats: Stats) => void; + + interface WatchOptions { + /** + * Add a delay before rebuilding once the first file changed. This allows webpack to aggregate any other + * changes made during this time period into one rebuild. + * Pass a value in milliseconds. Default: 300. + */ + aggregateTimeout?: number; + /** + * For some systems, watching many file systems can result in a lot of CPU or memory usage. + * It is possible to exclude a huge folder like node_modules. + * It is also possible to use anymatch patterns. + */ + ignored?: string | RegExp; + /** Turn on polling by passing true, or specifying a poll interval in milliseconds. */ + poll?: boolean | number; + } } - interface Dependencies { - /** - * Support Labeled Modules. - */ - LabeledModulesPlugin: dependencies.LabeledModulesPluginStatic; + interface Watching { + close(callback: () => void): void; + invalidate(): void; } - interface DirectoryDescriptionFilePluginStatic { - new (file: string, files: string[]): Plugin; + class Compiler extends Tapable implements ICompiler { + constructor(); + + name: string; + options: Configuration; + outputFileSystem: any; + run(handler: Compiler.Handler): void; + watch(watchOptions: Compiler.WatchOptions, handler: Compiler.Handler): Compiler.Watching; } - interface NormalModuleReplacementPluginStatic { - new (resourceRegExp: any, newResource: any): Plugin; + namespace Compiler { + type Handler = ICompiler.Handler; + type WatchOptions = ICompiler.WatchOptions; + + class Watching implements webpack.Watching { + constructor(compiler: Compiler, watchOptions: Watching.WatchOptions, handler: Watching.Handler); + + close(callback: () => void): void; + invalidate(): void; + } + + namespace Watching { + type WatchOptions = ICompiler.WatchOptions; + type Handler = ICompiler.Handler; + } } - interface ContextReplacementPluginStatic { - new (resourceRegExp: any, newContentResource?: any, newContentRecursive?: any, newContentRegExp?: any): Plugin; + abstract class MultiCompiler implements ICompiler { + run(handler: MultiCompiler.Handler): void; + watch(watchOptions: MultiCompiler.WatchOptions, handler: MultiCompiler.Handler): MultiWatching; } - interface IgnorePluginStatic { - new (requestRegExp: any, contextRegExp?: any): Plugin; + namespace MultiCompiler { + type Handler = ICompiler.Handler; + type WatchOptions = ICompiler.WatchOptions; } - interface PrefetchPluginStatic { + abstract class MultiWatching implements Watching { + close(callback: () => void): void; + invalidate(): void; + } + + abstract class Plugin implements Tapable.Plugin { + apply(compiler: Compiler): void; + } + + abstract class Stats { + /** Returns true if there were errors while compiling. */ + hasErrors(): boolean; + /** Returns true if there were warnings while compiling. */ + hasWarnings(): boolean; + /** Returns compilation information as a JSON object. */ + toJson(options?: Stats.ToJsonOptions): any; + /** Returns a formatted string of the compilation information (similar to CLI output). */ + toString(options?: Stats.ToStringOptions): string; + } + + namespace Stats { + type Preset + = boolean + | 'errors-only' + | 'minimal' + | 'none' + | 'normal' + | 'verbose'; + + interface ToJsonOptionsObject { + /** Add asset Information */ + assets?: boolean; + /** Sort assets by a field */ + assetsSort?: string; + /** Add information about cached (not built) modules */ + cached?: boolean; + /** Add children information */ + children?: boolean; + /** Add built modules information to chunk information */ + chunkModules?: boolean; + /** Add the origins of chunks and chunk merging info */ + chunkOrigins?: boolean; + /** Add chunk information (setting this to `false` allows for a less verbose output) */ + chunks?: boolean; + /** Sort the chunks by a field */ + chunksSort?: string; + /** Context directory for request shortening */ + context?: string; + /** Add details to errors (like resolving log) */ + errorDetails?: boolean; + /** Add errors */ + errors?: boolean; + /** Add the hash of the compilation */ + hash?: boolean; + /** Add built modules information */ + modules?: boolean; + /** Sort the modules by a field */ + modulesSort?: string; + /** Add public path information */ + publicPath?: boolean; + /** Add information about the reasons why modules are included */ + reasons?: boolean; + /** Add the source code of modules */ + source?: boolean; + /** Add timing information */ + timings?: boolean; + /** Add webpack version information */ + version?: boolean; + /** Add warnings */ + warnings?: boolean; + } + + type ToJsonOptions = Preset | ToJsonOptionsObject; + + interface ToStringOptionsObject extends ToJsonOptionsObject { + /** `webpack --colors` equivalent */ + colors?: boolean; + } + + type ToStringOptions = Preset | ToStringOptionsObject; + } + + /** + * Plugins + */ + + class BannerPlugin extends Plugin { + constructor(banner: any, options: any); + } + + class ContextReplacementPlugin extends Plugin { + constructor(resourceRegExp: any, newContentResource?: any, newContentRecursive?: any, newContentRegExp?: any); + } + + class DefinePlugin extends Plugin { + constructor(definitions: {[key: string]: any}); + } + + class EvalSourceMapDevToolPlugin extends Plugin { + constructor(options?: false | string | EvalSourceMapDevToolPlugin.Options); + } + + namespace EvalSourceMapDevToolPlugin { + interface Options { + append?: false | string; + columns?: boolean; + lineToLine?: boolean | { + exclude?: Condition | Condition[]; + include?: Condition | Condition[]; + test?: Condition | Condition[]; + }; + module?: boolean; + moduleFilenameTemplate?: string; + sourceRoot?: string; + } + } + + class ExtendedAPIPlugin extends Plugin { + constructor(); + } + + class HotModuleReplacementPlugin extends Plugin { + constructor(options?: any); + } + + class IgnorePlugin extends Plugin { + constructor(requestRegExp: any, contextRegExp?: any); + } + + class LoaderOptionsPlugin extends Plugin { + constructor(options: any); + } + + class NamedModulesPlugin extends Plugin { + constructor(); + } + + class NoEmitOnErrorsPlugin extends Plugin { + constructor(); + } + + /** @deprecated use webpack.NoEmitOnErrorsPlugin */ + class NoErrorsPlugin extends Plugin { + constructor(); + } + + class NormalModuleReplacementPlugin extends Plugin { + constructor(resourceRegExp: any, newResource: any); + } + + class PrefetchPlugin extends Plugin { // tslint:disable-next-line:unified-signatures - new (context: any, request: any): Plugin; - new (request: any): Plugin; + constructor(context: any, request: any); + constructor(request: any); } - interface ResolverPluginStatic { - new (plugins: Plugin[], files?: string[]): Plugin; - DirectoryDescriptionFilePlugin: DirectoryDescriptionFilePluginStatic; - /** - * This plugin will append a path to the module directory to find a match, - * which can be useful if you have a module which has an incorrect “main” entry in its package.json/bower.json etc (e.g. "main": "Gruntfile.js"). - * You can use this plugin as a special case to load the correct file for this module. Example: - */ - FileAppendPlugin: FileAppendPluginStatic; + class ProvidePlugin extends Plugin { + constructor(definitions: {[key: string]: any}); } - interface FileAppendPluginStatic { - new (files: string[]): Plugin; + class SourceMapDevToolPlugin extends Plugin { + constructor(options?: null | false | string | SourceMapDevToolPlugin.Options); } - interface BannerPluginStatic { - new (banner: any, options: any): Plugin; - } - - interface DefinePluginStatic { - new (definitions: {[key: string]: any}): Plugin; - } - - interface ProvidePluginStatic { - new (definitions: {[key: string]: any}): Plugin; - } - - interface SourceMapDevToolPluginStatic { - // if string | false | null, maps to the filename option - new (options?: string | false | null | SourceMapDevToolPluginOptions): Plugin; - } - - interface SourceMapDevToolPluginOptions { - // output filename pattern (false/null to append) - filename?: string | false | null; - // source map comment pattern (false to not append) - append?: false | string; - // template for the module filename inside the source map - moduleFilenameTemplate?: string; - // fallback used when the moduleFilenameTemplate produces a collision - fallbackModuleFilenameTemplate?: string; - // test/include/exclude files - test?: Condition | Condition[]; - include?: Condition | Condition[]; - exclude?: Condition | Condition[]; - // whether to include the footer comment with source information - noSources?: boolean; - // the source map sourceRoot ("The URL root from which all sources are relative.") - sourceRoot?: string | null; - // whether to generate per-module source map - module?: boolean; - // whether to include column information in the source map - columns?: boolean; - // whether to preserve line numbers between source and source map - lineToLine?: boolean | { - test?: Condition | Condition[]; - include?: Condition | Condition[]; + namespace SourceMapDevToolPlugin { + /** @todo extend EvalSourceMapDevToolPlugin.Options */ + interface Options { + append?: false | string; + columns?: boolean; exclude?: Condition | Condition[]; - }; - } - - interface EvalSourceMapDevToolPluginStatic { - // if string | false, maps to the append option - new (options?: string | false | EvalSourceMapDevToolPluginOptions): Plugin; - } - - interface EvalSourceMapDevToolPluginOptions { - append?: false | string; - moduleFilenameTemplate?: string; - sourceRoot?: string; - module?: boolean; - columns?: boolean; - lineToLine?: boolean | { - test?: Condition | Condition[]; + fallbackModuleFilenameTemplate?: string; + filename?: null | false | string; include?: Condition | Condition[]; - exclude?: Condition | Condition[]; - }; + lineToLine?: boolean | { + exclude?: Condition | Condition[]; + include?: Condition | Condition[]; + test?: Condition | Condition[]; + }; + module?: boolean; + moduleFilenameTemplate?: string; + noSources?: boolean; + sourceRoot?: null | string; + test?: Condition | Condition[]; + } } - interface HotModuleReplacementPluginStatic { - new (options?: any): Plugin; + class WatchIgnorePlugin extends Plugin { + constructor(paths: RegExp[]); } - interface ExtendedAPIPluginStatic { - new (): Plugin; + namespace optimize { + class AggressiveMergingPlugin extends Plugin { + constructor(options?: { + minSize?: number; + maxSize?: number; + }); + } + + class CommonsChunkPlugin extends Plugin { + constructor(options?: any); + } + + /** @deprecated */ + class DedupePlugin extends Plugin { + constructor(); + } + + class LimitChunkCountPlugin extends Plugin { + constructor(options: any); + } + + class MinChunkSizePlugin extends Plugin { + constructor(options: any); + } + + class OccurrenceOrderPlugin extends Plugin { + constructor(preferEntry: boolean); + } + + class UglifyJsPlugin extends Plugin { + constructor(options?: UglifyJsPlugin.Options); + } + + namespace UglifyJsPlugin { + type CommentFilter = (astNode: any, comment: any) => boolean; + + interface Options extends UglifyJS.MinifyOptions { + beautify?: boolean; + comments?: boolean | RegExp | CommentFilter; + exclude?: Condition | Condition[]; + include?: Condition | Condition[]; + sourceMap?: boolean; + test?: Condition | Condition[]; + } + } } - interface NoEmitOnErrorsPluginStatic { - new (): Plugin; - } - - interface WatchIgnorePluginStatic { - new (paths: RegExp[]): Plugin; - } - - interface NamedModulesPluginStatic { - new (): Plugin; - } - - interface LoaderOptionsPluginStatic { - new (options: any): Plugin; + namespace dependencies { } namespace loader { @@ -799,7 +877,7 @@ declare namespace webpack { data?: any; - callback: loaderCallback | void; + callback: loaderCallback; /** @@ -821,16 +899,16 @@ declare namespace webpack { * In the example: * [ * { request: "/abc/loader1.js?xyz", - * path: "/abc/loader1.js", - * query: "?xyz", - * module: [Function] - * }, + * path: "/abc/loader1.js", + * query: "?xyz", + * module: [Function] + * }, * { request: "/abc/node_modules/loader2/index.js", - * path: "/abc/node_modules/loader2/index.js", - * query: "", - * module: [Function] - * } - *] + * path: "/abc/node_modules/loader2/index.js", + * query: "", + * module: [Function] + * } + * ] */ loaders: any[]; @@ -850,7 +928,7 @@ declare namespace webpack { * The resource file. * In the example: "/abc/resource.js" */ - resourcePath: string + resourcePath: string; /** * The query of the resource. @@ -887,14 +965,14 @@ declare namespace webpack { * @param request * @param callback */ - resolve(context: string, request: string, callback: (err: Error, result: string) => void): any + resolve(context: string, request: string, callback: (err: Error, result: string) => void): any; /** * Resolve a request like a require expression. * @param context * @param request */ - resolveSync(context: string, request: string): string + resolveSync(context: string, request: string): string; /** @@ -917,7 +995,7 @@ declare namespace webpack { * Add a directory as dependency of the loader result. * @param directory */ - addContextDependency(directory: string): void + addContextDependency(directory: string): void; /** * Remove all dependencies of the loader result. Even initial dependencies and these of other loaders. Consider using pitch. @@ -980,7 +1058,7 @@ declare namespace webpack { * @param content * @param sourceMap */ - emitFile(name: string, content: Buffer|String, sourceMap: any): void + emitFile(name: string, content: Buffer|string, sourceMap: any): void; /** @@ -996,7 +1074,7 @@ declare namespace webpack { /** * Hacky access to the Compiler object of webpack. */ - _compiler: compiler.Compiler; + _compiler: Compiler; /** @@ -1006,148 +1084,40 @@ declare namespace webpack { } } - namespace optimize { - interface DedupePluginStatic { - new (): Plugin; - } - interface LimitChunkCountPluginStatic { - new (options: any): Plugin; - } - interface MinChunkSizePluginStatic { - new (options: any): Plugin; - } - interface OccurenceOrderPluginStatic { - new (preferEntry: boolean): Plugin; - } - interface UglifyJsPluginStatic { - new (options?: UglifyJS.MinifyOptions): Plugin; - } - interface CommonsChunkPluginStatic { - new (chunkName: string, filenames?: string | string[]): Plugin; - new (options?: any): Plugin; - } - interface AggressiveMergingPluginStatic { - new (options: any): Plugin; - } - } - - namespace dependencies { - interface LabeledModulesPluginStatic { - new (): Plugin; - } - } - + /** @deprecated */ namespace compiler { - interface Compiler { - /** Builds the bundle(s). */ - run(callback: CompilerCallback): void; - /** - * Builds the bundle(s) then starts the watcher, which rebuilds bundles whenever their source files change. - * Returns a Watching instance. Note: since this will automatically run an initial build, so you only need to run watch (and not run). - */ - watch(watchOptions: WatchOptions, handler: CompilerCallback): Watching; - //TODO: below are some of the undocumented properties. needs typings - outputFileSystem: any; - name: string; - options: Configuration; - } + /** @deprecated use webpack.Compiler */ + type Compiler = webpack.Compiler; - interface Watching { - close(callback: () => void): void; - } + /** @deprecated use webpack.Compiler.Watching */ + type Watching = webpack.Compiler.Watching; - interface WatchOptions { - /** After a change the watcher waits that time (in milliseconds) for more changes. Default: 300. */ - aggregateTimeout?: number; - /** For some systems, watching many file systems can result in a lot of CPU or memory usage. It is possible to exclude a huge folder like node_modules. It is also possible to use anymatch patterns. */ - ignored?: RegExp | string; - /** The watcher uses polling instead of native watchers. true uses the default interval, a number specifies a interval in milliseconds. Default: undefined (automatic). */ - poll?: number | boolean; - } + /** @deprecated use webpack.Compiler.WatchOptions */ + type WatchOptions = webpack.Compiler.WatchOptions; - interface Stats { - /** Returns true if there were errors while compiling */ - hasErrors(): boolean; - /** Returns true if there were warnings while compiling. */ - hasWarnings(): boolean; - /** Return information as json object */ - toJson(options?: StatsOptions): any; //TODO: type this - /** Returns a formatted string of the result. */ - toString(options?: StatsToStringOptions): string; - } + /** @deprecated use webpack.Stats */ + type Stats = webpack.Stats; - interface StatsOptions { - /** Add asset Information */ - assets?: boolean; - /** Sort assets by a field */ - assetsSort?: string; - /** Add information about cached (not built) modules */ - cached?: boolean; - /** Add children information */ - children?: boolean; - /** Add chunk information (setting this to `false` allows for a less verbose output) */ - chunks?: boolean; - /** Add built modules information to chunk information */ - chunkModules?: boolean; - /** Add the origins of chunks and chunk merging info */ - chunkOrigins?: boolean; - /** Sort the chunks by a field */ - chunksSort?: string; - /** Context directory for request shortening */ - context?: string; - /** Add errors */ - errors?: boolean; - /** Add details to errors (like resolving log) */ - errorDetails?: boolean; - /** Add the hash of the compilation */ - hash?: boolean; - /** Add built modules information */ - modules?: boolean; - /** Sort the modules by a field */ - modulesSort?: string; - /** Add public path information */ - publicPath?: boolean; - /** Add information about the reasons why modules are included */ - reasons?: boolean; - /** Add the source code of modules */ - source?: boolean; - /** Add timing information */ - timings?: boolean; - /** Add webpack version information */ - version?: boolean; - /** Add warnings */ - warnings?: boolean; - } + /** @deprecated use webpack.Stats.ToJsonOptions */ + type StatsOptions = webpack.Stats.ToJsonOptions; - interface StatsToStringOptions extends StatsOptions { - /** With console colors */ - colors?: boolean; - } + /** @deprecated use webpack.Stats.ToStringOptions */ + type StatsToStringOptions = webpack.Stats.ToStringOptions; - type CompilerCallback = (err: Error, stats: Stats) => void; + /** @deprecated use webpack.Compiler.Handler */ + type CompilerCallback = webpack.Compiler.Handler; } - interface PerformanceOptions { - /** - * Turns hints on/off. In addition, tells webpack to throw either an error or a warning when hints are found. This property is set to "warning" by default. - */ - hints?: boolean | 'error' | 'warning'; - /** - * An entrypoint represents all assets that would be utilized during initial load time for a specific entry. This option controls when webpack should emit performance hints based on the maximum entrypoint size. The default value is 250000 (bytes). - */ - maxEntryPointSize?: number; - /** - * An asset is any emitted file from webpack. This option controls when webpack emits a performance hint based on individual asset size. The default value is 250000 (bytes). - */ - maxAssetSize?: number; - /** - * This property allows webpack to control what files are used to calculate performance hints. - */ - assetFilter?: (assetFilename: string) => boolean; - } + /** @deprecated use webpack.Options.Performance */ + type PerformanceOptions = webpack.Options.Performance; + /** @deprecated use webpack.Options.WatchOptions */ + type WatchOptions = webpack.Options.WatchOptions; + /** @deprecated use webpack.EvalSourceMapDevToolPlugin.Options */ + type EvalSourceMapDevToolPluginOptions = webpack.EvalSourceMapDevToolPlugin.Options; + /** @deprecated use webpack.SourceMapDevToolPlugin.Options */ + type SourceMapDevToolPluginOptions = webpack.SourceMapDevToolPlugin.Options; + /** @deprecated use webpack.optimize.UglifyJsPlugin.CommentFilter */ + type UglifyCommentFunction = webpack.optimize.UglifyJsPlugin.CommentFilter; + /** @deprecated use webpack.optimize.UglifyJsPlugin.Options */ + type UglifyPluginOptions = webpack.optimize.UglifyJsPlugin.Options; } - -declare var webpack: webpack.Webpack; - -//export default webpack; -export = webpack; diff --git a/webpack/tsconfig.json b/webpack/tsconfig.json index f85a099ac3..1a1c5440ce 100644 --- a/webpack/tsconfig.json +++ b/webpack/tsconfig.json @@ -5,7 +5,7 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, + "noImplicitThis": true, "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ @@ -19,4 +19,4 @@ "index.d.ts", "webpack-tests.ts" ] -} \ No newline at end of file +} diff --git a/webpack/tslint.json b/webpack/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/webpack/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/webpack/webpack-tests.ts b/webpack/webpack-tests.ts index 086592b4de..c1369f78bc 100644 --- a/webpack/webpack-tests.ts +++ b/webpack/webpack-tests.ts @@ -32,18 +32,6 @@ rule = { query: { mimetype: "image/png" } }; -// -// https://webpack.github.io/docs/using-plugins.html -// - -configuration = { - plugins: [ - new webpack.ResolverPlugin([ - new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"]) - ], ["normal", "loader"]) - ] -}; - // // http://webpack.github.io/docs/tutorials/getting-started/ // @@ -74,7 +62,10 @@ configuration = { filename: "bundle.js" }, plugins: [ - new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js") + new webpack.optimize.CommonsChunkPlugin({ + name: "vendor", + filename: "vendor.bundle.js", + }), ] }; @@ -112,7 +103,7 @@ configuration = { } }; -let CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; +const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; configuration = { entry: { p1: "./page1", @@ -138,10 +129,6 @@ configuration = { output: { filename: "[name].js" }, - plugins: [ - new CommonsChunkPlugin("admin-commons.js", ["ap1", "ap2"]), - new CommonsChunkPlugin("commons.js", ["p1", "p2", "admin-commons.js"]) - ] }; //